2012-05-09 58 views
0

目前我想在java代码中创建一个自定义UI,而不用担心xml文件。我在我想在我的linearLayout中已经存在的textView下添加一个textView。这是迄今为止我所拥有的。在另一个textView下添加textView

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); 

的问题是,它只是增加了mineralName TextView的,而不是mineralProperties TextView的。我希望它是最上面的mineralName textView,然后是它下面的mineralProperties textView。

回答

2

默认情况下,LinearLayout中的子视图将水平堆叠。尝试改变linearLayout.setOrientation(LinearLayout.VERTICAL)

你也应该改变你的文本视图布局PARAMS到:

mineralName.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); 

mineralProperties.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); 

否则的意见,人们可能会覆盖其他。

1

您的代码正在进行小改动,希望它能帮助您。

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); 

变化MATCH_PARENT与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);