0

目前我想用 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。

4

2 回答 2

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

否则,其中一个视图可能会覆盖另一个视图。

于 2012-05-09T08:31:01.060 回答
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); 
于 2012-05-09T08:39:03.810 回答