如何在TableLayout内的TableRow中设置以编程方式创建的ImageView的高度?

时间:2017-08-03 18:10:13

标签: java android

TableLayout mTableLayout = (TableLayout) findViewById(R.id.tableLayout);

        JSONArray Rows = obj.getJSONArray("Rows");
        for(int i=0;i<Rows.length();i++) {
            TableRow Row1 = new TableRow(this);
            JSONArray RowN = Rows.getJSONArray(i);
            for(int j=0;j<RowN.length();j++) {
                ImageView Tile=new ImageView(this.getApplicationContext());
                Tile.setImageResource(0);
                Tile.setBackgroundColor(0x4133FF70);
                Row1.addView(Tile);
            }
            mTableLayout.addView(Row1);
        }

这是我的代码。在循环中,创建ImageViews时不显示图像,只显示背景。

使用

ImageView imageView = findViewById(R.id.dl_image);
imageView.getLayoutParams().width = 120;

只返回一个NullPointerexception,我没有更多想法尝试。

编辑:

解决方案原来是

TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(120, 120);
                Tile.setLayoutParams(layoutParams);

2 个答案:

答案 0 :(得分:0)

您可以使用以下方法设置imageview的高度和宽度。只要记住保持它小于单元格高度,你也必须手动增加单元格高度。

ImageView imageView = (ImageView)findViewById(R.id.dl_image);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
imageView.setLayoutParams(layoutParams);

答案 1 :(得分:0)

由于.getLayoutParams().width,你得到空指针异常,你设置了params了吗?答案是否定的,你怎么能指望params在那里。

更新此内容
Tile.getLayoutParams().width = 120;

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(120, 120);
Tile.setLayoutParams(layoutParams);
相关问题