1

我正在尝试用代码和java进行设计。这是活动 xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" 
android:id="@+id/hello">

</RelativeLayout>

这是我正在尝试的Java代码。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    RelativeLayout layout=(RelativeLayout)findViewById(R.id.hello);
    TextView txt=new TextView(this);
    txt.setText("Hello World Problem");
    layout.addView(txt);
    setContentView(R.layout.activity_main);
}

在相对布局中,我想在 java 代码中添加 textview。但上面的java代码不起作用。错误:应用程序已不幸停止。我该如何编码?

4

4 回答 4

2

R.id.hellofindViewById直到您调用setContentView并添加R.id.hello到您的活动视图之后才能找到。移动setContentView到你的findViewById线之上。

于 2013-04-13T06:32:12.017 回答
2

setContentView您必须在使用 findViewById() 获取视图之前进行安排。

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   RelativeLayout layout=(RelativeLayout)findViewById(R.id.hello);

   LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                      (LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT));

   TextView txt=new TextView(this);
   txt.setLayoutParams(lp);
   txt.setText("Hello World Problem");
   layout.addView(txt);
}
于 2013-04-13T06:33:34.337 回答
1

您好 RedHat_Father 用以下代码替换您的 java 代码,它可能会对您有所帮助:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    //  Do not forget to set your layout file before you done the mapping of the elements

    RelativeLayout layout=(RelativeLayout)findViewById(R.id.hello);
    TextView txt=new TextView(this);
    txt.setText("Hello World Problem");
    layout.addView(txt);
}

我希望这会奏效...... :)

于 2013-04-13T07:01:39.750 回答
1

由于您的编码完全错误,要在运行时添加 textview,您必须执行以下操作:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RelativeLayout layout=(RelativeLayout)findViewById(R.id.hello);
    TextView txt = new TextView(this);
    txt.setText("Hello World");
    txt.setId(1);
    txt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
    layout.addView(txt);
于 2013-04-13T06:34:32.740 回答