代码
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 我怎么能这样做?
答案 0 :(得分:1)
您的第二个setContentView
删除了第一个,这就是为什么您只有message
而不是mytime - message
。
要执行您想要的操作,您需要添加一个setContentView
容器,该容器本身可以容纳多个View。
一个这样的容器是LinearLayout
。您必须创建它,将其方向设置为Horizontal,并添加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);
}