我正在尝试将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);
}
答案 0 :(得分:0)
您应该在setContentView(R.layout.activity_main)
之后立即致电super.onCreate
。
我做到了:
我去了main_activity.xml并向RelativeLayout添加了一个属性android:id="@+id/activity_main"
。
编辑代码:
@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);
}