在另一个textView下面添加一个textView

时间:2012-05-09 08:24:50

标签: android views textview android-linearlayout

目前我想在java代码中创建自定义UI,而不用担心xml文件。我正处于我想在linearLayout中已经存在的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 个答案:

答案 0 :(得分:2)

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

此外,您应该将文本视图布局参数更改为:

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

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

否则其中一个观点可能会覆盖另一个观点。

答案 1 :(得分: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);

使用WRAP_CONTENT更改MATCH_PARENT

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