在Android中将TextView添加到LinearLayout



我有两个TextView,我想把它们添加到LinearLayout中,但当我运行项目时,只看到一个TextView。

这是我的代码:

public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        TextView textView = new TextView(this);
        textView.setText("Thank you, Jesus!");
        textView.setTextColor(Color.BLACK);
        TextView textView2 = new TextView(this);
        textView.setText("Dont give up on me!");
        textView.setTextColor(Color.BLACK);
        LinearLayout layout = new LinearLayout(this);
        layout.setBackgroundColor(Color.WHITE);
        layout.addView(textView);
        layout.addView(textView2);
        setContentView(layout);
    }
}

运行后,textView2是LinearLayout中唯一的视图。

有人能向我解释一下发生了什么事吗?

使用textView2调用setText,使用setTextColor方法调用textView2,因为当前使用的是textView:

    TextView textView2 = new TextView(this);
    textView2.setText("Dont give up on me!");
    textView2.setTextColor(Color.BLACK);

建议还通过调用setLayoutParams方法为所有视图设置height/width

另一个建议:使用layout.setOrientation(LinearLayout.VERTICAL);

为线性布局添加方向

最新更新