Reputation: 1600
Currently I want to make a custom UI in java code and not worry about xml files. I'm at the point where I want to add a textView underneath an already existing textView in my linearLayout. Here's what I have so far.
View linearLayout = findViewById(R.id.rockLayout);
ImageView mineralPicture = new ImageView(this);
TextView mineralName = new TextView(this);
TextView mineralProperties = new TextView(this);
mineralProperties.setText("The properties are: " + Statics.rockTable.get(rockName).getDistinctProp());
mineralProperties.setId(2);
mineralName.setText("This mineral is: " + rockName);
mineralName.setId(1);
mineralName.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.MATCH_PARENT));
mineralProperties.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.MATCH_PARENT));
/** Need to figure out the picture....
* mineralPicture.setId(2);
* mineralPicture.setImageResource(R.drawable.rocks);
* mineralPicture.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
*/
((LinearLayout)linearLayout).addView(mineralName);
((LinearLayout)linearLayout).addView(mineralProperties);
The problem is that it only adds the mineralName textView and not the mineralProperties textView. I would like for it be the mineralName textView on the very top, then the mineralProperties textView right underneath it.
Upvotes: 0
Views: 108
Reputation: 1185
your code is working with small changes, hope it can help you.
View linearLayout = findViewById(R.id.rockLayout);
ImageView mineralPicture = new ImageView(this);
TextView mineralName = new TextView(this);
TextView mineralProperties = new TextView(this);
mineralProperties.setText("The properties are: " + Statics.rockTable.get(rockName).getDistinctProp());
mineralProperties.setId(2);
mineralName.setText("This mineral is: " + rockName);
mineralName.setId(1);
Change MATCH_PARENT with WRAP_CONTENT
mineralName.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
mineralProperties.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
/** Need to figure out the picture....
* mineralPicture.setId(2);
* mineralPicture.setImageResource(R.drawable.rocks);
* mineralPicture.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
*/
((LinearLayout)linearLayout).addView(mineralName);
((LinearLayout)linearLayout).addView(mineralProperties);
Upvotes: 1
Reputation: 1738
Child views in a LinearLayout will be stacked horizontally by default. Try changing that with linearLayout.setOrientation(LinearLayout.VERTICAL)
.
Also you should change your text view layout params to:
mineralName.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
mineralProperties.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
Otherwise one of the views might cover the other.
Upvotes: 2