gpt4 book ai didi

java - java 中的 Android Activity 与 XML 崩溃

转载 作者:行者123 更新时间:2023-12-01 09:57:36 24 4
gpt4 key购买 nike

我是 Android 开发的新手。我试图显示一个完全用 Java 编写、没有 XML 的简单 Activity ,但它崩溃了。我究竟做错了什么?这是代码:

public class TestActivity extends Activity
{
@Override
public void onCreate(Bundle savedinstancestate)
{
super.onCreate(savedinstancestate);
RelativeLayout thislayout = new RelativeLayout(this);
RelativeLayout.LayoutParams TextViewParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
TextViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
TextViewParams.addRule(RelativeLayout.CENTER_VERTICAL);
TextView outputtext = new TextView(this);
outputtext.setText("Poop!");
thislayout.addView(outputtext, TextViewParams);
setContentView(thislayout);
}
}

最佳答案

好吧,您正在初始化 LayoutParams,但没有将其设置为 TextView。而且您还必须为父布局定义 LayoutParams ,即 RelativeLayout

我测试了您的代码并做了一些更改。 尝试这样做

@Override
public void onCreate(Bundle savedinstancestate) {
super.onCreate(savedinstancestate);

// setting RelativeLayout Params
RelativeLayout thislayout = new RelativeLayout(this);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
thislayout.setLayoutParams(params);

// setting TextView Params
TextView outputtext = new TextView(this);
RelativeLayout.LayoutParams TextViewParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
TextViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
TextViewParams.addRule(RelativeLayout.CENTER_VERTICAL);
outputtext.setLayoutParams(TextViewParams);
outputtext.setText("Poop!");

thislayout.addView(outputtext);
setContentView(thislayout);
}

希望对你有帮助。

关于java - java 中的 Android Activity 与 XML 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37064138/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com