Android问题setContentView()

时间:2013-06-25 09:23:12

标签: android textview

代码

TextView textView = new TextView(this);
textView.setTextSize(20);
textView.append(mytime+ "-");

TextView textView2 = new TextView(this);
textView2.setTextSize(20);
textView2.setTextColor(-16776961);
textView2.append(message);

//set the text view as the activity layout
setContentView(textView);
setContentView(textView2);

实际输出:消息。

我想输出的是mytime - message 我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

您的第二个setContentView删除了第一个,这就是为什么您只有message而不是mytime - message

要执行您想要的操作,您需要添加一个setContentView容器,该容器本身可以容纳多个View。

一个这样的容器是LinearLayout。您必须创建它,将其方向设置为Horizo​​ntal,并添加TextView:

TextView textView = new TextView(this);
textView.setTextSize(20);
textView.append(mytime+ "-");

TextView textView2 = new TextView(this);
textView2.setTextSize(20);
textView2.setTextColor(-16776961);
textView2.append(message);

LinearLayout linear = new LinearLayout(this);
// Not necessary as it's the default but useful to know
linear.setOrientation(LinearLayout.HORIZONTAL); 
linear.addView(textView);
linear.addView(textView2);


//set the text view as the activity layout
setContentView(linear);

答案 1 :(得分:0)

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

    TextView textView1 = new TextView(this);
    textView1.setTextSize(20);
    textView1.append("myTime"+ "-");
    textView1.setGravity(Gravity.CENTER);

    TextView textView2 = new TextView(this);
    textView2.setTextSize(20);
    textView2.setTextColor(-16776961);
    textView2.append("message");

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.HORIZONTAL);
    layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

   layout.setGravity(Gravity.CENTER);

   layout.addView(textView1);
   layout.addView(textView2);


    setContentView(layout);

}