如何以编程方式将TableView对齐在TableLayout单元格中

时间:2017-04-11 05:46:33

标签: android

我已经关注了代码:

TableRow row = new TableRow(this);
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
lp.setMargins(0,5,0,0);
row.setLayoutParams(lp);
List<List<String>> cList2 = displayTemp.getCList2();
StringBuffer sb = new StringBuffer();
List<String> lStr = cList2.get(0);
for (int ix = 0; ix < lStr.size(); ix++) {
    sb.append(lStr.get(ix));
    if (ix != lStr.size() - 1) {
        sb.append("\n");
    }
}
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f));
tv.setText(sb.toString());
tv.setTextSize(COMPLEX_UNIT_DIP, 20);
row.addView(tv);
byte[] decodedString = Base64.decode(cList2.get(1).get(0), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
ImageView iView = new ImageView(this);
iView.setImageBitmap(decodedByte);
row.addView(iView);
tableLayout2.addView(row, rowNum);
rowNum++;

这会动态显示表格行。我的第二个表格单元格显示为此代码

byte[] decodedString = Base64.decode(cList2.get(1).get(0), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
ImageView iView = new ImageView(this);
iView.setImageBitmap(decodedByte);
row.addView(iView);

第二个单元格中显示的图像当前是右对齐的。我希望将其显示为单元格中的对齐方式。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

添加以下代码行

lp.gravity = Gravity.CENTER;

最终代码

TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
//rest of code
lp.gravity = Gravity.CENTER;
row.setLayoutParams(lp);

Gravity有以下选项。

Gravity.CENTER_HORIZONTAL
Gravity.CENTER_VERTICAL

答案 1 :(得分:1)

尝试

tv.setGravity(Gravity.CENTER);
row.setGravity(Gravity.CENTER);

OR

LayoutParams lp = new LayoutParams();
lp.gravity = Gravity.CENTER;
tv.setLayoutParams(lp);
row.setGravity(Gravity.CENTER);

没有直接的方法在每个单元格上应用边框,但你可以使用android:background =&#34; @ drawable / cell_border&#34;手动完成。无论你需要它。

<强> cell_border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape= "rectangle"  >
    <solid android:color="#000"/>
    <stroke android:width="1dp"  android:color="#ff9"/>
</shape>