开发者

Adding views to an activity programmatically

开发者 https://www.devze.com 2023-03-26 19:51 出处:网络
I have this code on the onCreate() of an Activity that is inside a Tab: String[] info = getResources().getStringArray(R.array.fc_1);

I have this code on the onCreate() of an Activity that is inside a Tab:

String[] info = getResources().getStringArray(R.array.fc_1);
TextView q = new TextView(this);
q.setText(info[0]);

TextView a1 = new TextView(this);
a1.setText(info[1]);

TextView a2 = new TextView(this);
a2.setText(info[2]);

TextView a3 = new TextView(this);
a3.setText(info[3]);

LinearLayout linlay = new LinearLayout(this);
linlay.addView(q);
linlay.addView(a1);
linlay.addView(a2);
linlay.addView(a3);
setContentView(linlay);

What happens is that only the first textview gets shown, with the correct value of info[0], but the others textviews just aren't there.

Any ideas what I might be doi开发者_如何学运维ng wrong?


Default orientation of LinearLayout is horizontal. So the other TextViews are to the right of the first which takes all the space. Change the orientation of the LinearLayout to vertical.


The standard height and width of the LinearLayout is fill_parent. That makes your first textView to use all the space hiding the rest of the views (putting them outside of the screen).

You can either change the orientation of linlay to be vertical, or change the width of the different textviews. You will need to play with LinearLayout.LayoutParams to achieve this.


String[] info = getResources().getStringArray(R.array.fc_1);

TextView q = new TextView(this);
q.setText(info[0]);
TextView a1 = new TextView(this);
a1.setText(info[1]);

TextView a2 = new TextView(this);
a2.setText(info[2]);

TextView a3 = new TextView(this);
a3.setText(info[3]);

LinearLayout linlay = new LinearLayout(this);
linlay.setOrientation(1);//set vertical orientation
linlay.addView(q);
linlay.addView(a1);
linlay.addView(a2);
linlay.addView(a3);
setContentView(linlay);

try this code block

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号