[英]Android app, how to center align ImageView in a TableLayout cell programmatically
I've following code, within an Android app:我在 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++;
This displays a table row dynamically.这会动态显示表格行。 My 2nd table cell is displayed with this code,
我的第二个表格单元格显示有此代码,
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);
The image displayed in the 2nd cell is currently right aligned.显示在第二个单元格中的图像当前是右对齐的。 I want to display this as center aligned in the cell.
我想将其显示为在单元格中居中对齐。 How can I do that?
我怎样才能做到这一点?
Add below line of code添加下面的代码行
lp.gravity = Gravity.CENTER;
Final code最终代码
TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
//rest of code
lp.gravity = Gravity.CENTER;
row.setLayoutParams(lp);
Gravity has below options. 重力有以下选项。
Gravity.CENTER_HORIZONTAL Gravity.CENTER_HORIZONTAL
Gravity.CENTER_VERTICAL Gravity.CENTER_VERTICAL
Try尝试
tv.setGravity(Gravity.CENTER);
row.setGravity(Gravity.CENTER);
OR或者
LayoutParams lp = new LayoutParams();
lp.gravity = Gravity.CENTER;
tv.setLayoutParams(lp);
row.setGravity(Gravity.CENTER);
There is no direct way to apply border on each cell but you can do it manually by using android:background="@drawable/cell_border" wherever you need it.没有直接的方法可以在每个单元格上应用边框,但您可以在任何需要的地方使用 android:background="@drawable/cell_border" 手动完成。
cell_border.xml 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.