以编程方式在Android v7.0与Android 5.0中设置布局参数

时间:2017-08-18 15:14:48

标签: android android-layout android-version

背景

在我的Android应用中,我以编程方式添加,删除和操作表中的行元素。我需要在这些表操作事件上设置TableRow()中元素的布局参数。

问题

从Android 5.0迁移到Android 7.0并在其他平板电脑上运行该应用后,表格行不会反映已定义的布局参数。

澄清:

配置1:

  • 硬件:三星Galaxy Tab4
  • Android版本:5.0.2
  • 结果:表格行格式正确

配置2

  • 硬件:三星Galaxy Tab S2

  • Android版本:7.0

  • 结果:表格行未格式化

代码示例

//Define Layout Parameters
rowLayoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
tableLayoutParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
editTextLayoutParams = new TableRow.LayoutParams(100, 40);
tvLayoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);

//Create new table tow
tableRow = new TableRow(getActivity());
tableRow.setLayoutParams(rowLayoutParams);

//Define Margins
int etMargin1 = (int)getActivity().getResources().getDimension(R.dimen.etMargin1);
int etMargin2 = (int)getActivity().getResources().getDimension(R.dimen.etMargin2);

int tvMargin1 = (int)getActivity().getResources().getDimension(R.dimen.tvMargin1);
int tvMargin2 = (int)getActivity().getResources().getDimension(R.dimen.tvMargin2);


if(editable)
{
    //Create Edit Texts
    EditText exampleEt = new EditText(getActivity());
    editTextLayoutParams.setMargins(etMargin1,5,etMargin2,5);
    exampleEt.setLayoutParams(editTextLayoutParams);
    tableRow.setLayoutParams(rowLayoutParams);
    tableRow.addView(exampleEt);
}
else
{
    //Create Text Views
    TextView exampleTv = new TextView(getActivity());

    //Set Layout Params
    tvLayoutParams.setMargins(tvMargin1,5,tvMargin2,5);
    exampleTv.setLayoutParams(tvLayoutParams);

    tableRow.setLayoutParams(rowLayoutParams);
    tableRow.addView(exampleTv);
}

进一步说明

在代码示例中请注意编辑文本与文本视图。只有Edit Text元素无法正确格式化。文本视图边距按预期格式化。

1 个答案:

答案 0 :(得分:0)

这最终成为了一个围绕平板电脑不同屏幕尺寸的2部分解决方案。 Android版本不是一个因素。

第1部分是根据与密度无关的像素而不是硬编码值来定义行布局宽度和高度参数

int etHeight = (int)getActivity().getResources().getDimension(R.dimen.etHeight);
int etWidth = (int)getActivity().getResources().getDimension(R.dimen.etWidth);

editTextLayoutParams = new TableRow.LayoutParams(etWidth, etHeight);

在dimens.xml中的位置

<dimen name="etHeight">40dp</dimen>
<dimen name="etWidth">100dp</dimen>

第2部分是更改布局文件中xml表定义引用的表宽度维度。边缘实际上是格式正确的,但是表格对于屏幕来说太大了,并且产生了元素被打包到表格左侧的错觉。

现在的问题是,是否在较大的平板电脑上设计较小的平板电脑和废弃屏幕空间,或创建支持不同平板电脑尺寸的多个布局/尺寸文件。但是,这是一个不同主题的主题。