【问题标题】:Programmatically Set Layout Params in Android v7.0 vs. Android 5.0在 Android v7.0 与 Android 5.0 中以编程方式设置布局参数
【发布时间】:2025-12-10 17:40:02
【问题描述】:

背景

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

问题

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

澄清一下:

配置一:

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

配置2

  • 硬件:三星 Galaxy Tab S2

  • 安卓版本: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);
}

进一步规范

请注意代码示例中的编辑文本与文本视图。只有编辑文本元素的格式不正确。文本视图边距格式符合预期。

【问题讨论】:

    标签: android android-layout android-version


    【解决方案1】:

    这最终成为一个两部分的解决方案,围绕平板电脑的不同屏幕尺寸展开。安卓版本不是一个因素。

    第 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 表格定义所引用的表格宽度尺寸。边距实际上格式正确,但表格对于屏幕来说太大了,并产生了元素被打包到表格左侧的错觉。

    现在的问题是,是为较小的平板电脑设计布局并在较大的平板电脑上浪费屏幕空间,还是创建支持不同平板电脑尺寸的多个布局/尺寸文件。但是,这是另一个主题的主题。

    【讨论】: