2016-11-22 37 views
0

我创造了很多图像按钮的这样的代码:编程设置ImageButton的利润率

TableRow tr = new TableRow(this); 
if (db != null) { 
     if (db.moveToFirst()) { 
      do { 
       ImageButton button = new ImageButton(this); 
       int ID = Integer.parseInt(db.getString(db.getColumnIndex("ID"))); 
       int resource = getResources().getIdentifier("unit" + ID, "drawable", getPackageName()); 
       System.out.println("unit" + ID + ":" + resource); 
       button.setImageResource(resource); 
       button.setOnClickListener(MainActivity.this); 
       tr.addView(button); 
       button.getLayoutParams().height = 250; 
       button.getLayoutParams().width = 250; 
       button.setScaleType(ImageView.ScaleType.FIT_CENTER); 
       //button.setLayoutParams(tableRowParams); 
       rowcount++; 
       if (rowcount % 5 == 0) { 
        layout.addView(tr); 
        tr = new TableRow(this); 
       } 
      } while (db.moveToNext()); 
     } 
    } 

而且我发现代码:

 TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT); 
     tableRowParams.setMargins(0, 0, 0, 0); 

,并在做,而在按钮适用。

button.setLayoutParams(tableRowParams); 

它会显示错误消息 “android.widget.TableLayout $的LayoutParams不能转换到android.widget.TableRow $的LayoutParams”

+0

可能重复[在代码中动态设置边距-Android](http://stackoverflow.com/questions/12826067/setting-margins-dynamically-in-code-android) –

回答

0

更换TableLayout.LayoutParamsTableRow.LayoutParams

TableRow.LayoutParams tableRowParams = 
     new TableRow.LayoutParams(
      TableRow.LayoutParams.WRAP_CONTENT, 
      TableRow.LayoutParams.WRAP_CONTENT); 
tableRowParams.setMargins(0, 0, 0, 0); 
+0

谢谢你,这是我的错误 – LittleTin

0

的您使用的LayoutParams类型由视图的容器决定,而不是视图本身。因此,由于您的按钮在TableRow之内,因此您需要使用TableRow.LayoutParams而不是TableLayout.LayoutParams。如果您需要为TableRow或Button设置样式,而不是创建类的新实例并以这种方式查看边距,那么可以使用Button button = (Button) LayoutInflater.from(context).inflate(R.layout.button, tr, false);来扩充XML布局,并且以这种方式使用Button button = (Button) LayoutInflater.from(context).inflate(R.layout.button, tr, false);您可以在XML文件中设置边距。