在android中以编程方式创建和添加TextView

时间:2013-08-01 19:12:27

标签: android textview

我正在尝试将TextView以编程方式添加到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);

    }

2 个答案:

答案 0 :(得分:0)

您应该在setContentView(R.layout.activity_main)之后立即致电super.onCreate

我做到了:

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

  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。

答案 1 :(得分: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);     
}