0

我正在尝试以编程方式添加TextView到 may RelativeLayout。它不工作。

public class MainActivity extends Activity {

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

        RelativeLayout rl = (RelativeLayout) findViewById(R.layout.activity_main);
        TextView tv = new TextView(MainActivity.this);

        tv.setText("Hello World");
        tv.setTextColor(Color.BLACK);
        tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
        rl.addView(tv);     
        setContentView(R.layout.activity_main);

    }
4

2 回答 2

0

你应该setContentView(R.layout.activity_main)在之后打电话super.onCreate

我这样做了:

  1. 我去了 main_activity.xmlandroid:id="@+id/activity_main"并向RelativeLayout 添加了一个属性。

  2. 编辑代码:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        //RelativeLayout rl = (RelativeLayout) findViewById(R.layout.activity_main);
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.activity_main);
        TextView tv = new TextView(MainActivity.this);
    
        tv.setText("Hello World");
        tv.setTextColor(Color.BLACK);
        tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
        rl.addView(tv);     
    
    }
    

    但是,textView 仍然会与 RelativeView 上的其他生成项目重叠。也许您应该考虑使用具有垂直方向的 LinearLayout。

于 2013-08-01T19:15:42.940 回答
0

调用setContentView(R.layout.activity_main)将重新膨胀您的布局,覆盖您之前所做的添加。向上移动它,所以这是super通话后的第一件事。就像是:

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

    RelativeLayout rl = (RelativeLayout) findViewById(R.layout.activity_main);
    TextView tv = new TextView(MainActivity.this);

    tv.setText("Hello World");
    tv.setTextColor(Color.BLACK);
    tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
    rl.addView(tv);     
}
于 2013-08-01T19:16:03.863 回答