【问题标题】:How to set android:layout_width="match_parent" from code?如何从代码中设置 android:layout_width="match_parent"?
【发布时间】:2021-08-15 01:17:42
【问题描述】:

我有不同的布局。一些由 xml 创建。其他一些通过代码动态。当我在 xml 上时,我可以使用“wrap_content”值设置宽度或高度。如何动态获得相同的结果?这是我的动态 TextView 的 sn-p。我需要删除“final int width = 440;”并获得相同的“wrap_content”值。怎么样?

final int width = 440;
final int height = textViewHeight;
final int top = getNewTop(height);

FrameLayout.LayoutParams layoutParams;
layoutParams = getLayoutParams(width, height, top);

TextView textView;
textView = new TextView(_registerNewMealActivity);
textView.setText(text);
textView.setLayoutParams(layoutParams);

_frameLayout.addView(textView);

【问题讨论】:

  • 你在谷歌看到了 wrap_content 吗?

标签: android


【解决方案1】:

你可以使用:

textView.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, height));

【讨论】:

  • +1 用于提及 FrameLayout 而不是 RelativeLayout
  • @ArunkumarSharma : 你能告诉我它有什么不同吗,实际上在使用 LayoutParams 时总是很困惑,我应该导入哪个,或者如果你可以建议任何链接或帖子。
  • @VishwasSharma LayoutParams are used by views to tell their parents how they want to be laid out. Check This
  • 所以我们使用 LayoutParams 的 FrameLayout 变体,因为 TextView 被添加到 FrameLayout?如果将它添加到 LinearLayout,我们是否应该使用 LinearLayout.LayourParams,例如?
【解决方案2】:

尝试如下:

FrameLayout.LayoutParams layoutParams;
layoutParams = getLayoutParams(LayoutParams.WRAP_CONTENT, height, top);

  TextView textView;
textView = new TextView(_registerNewMealActivity);
textView.setText(text);
textView.setLayoutParams(layoutParams);

【讨论】:

    【解决方案3】:

    您可以将FrameLayout.LayoutParams.WRAP_CONTENT 用于width

    【讨论】:

      【解决方案4】:

      你可以这样做。

          RelativeLayout.LayoutParams flparams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,(int)height);
                  youlayoutname.setLayoutParams(flparams);
      

      【讨论】:

        【解决方案5】:

        一般来说,你应该使用

        textView.setLayoutParams(new FrameLayout.LayoutParams(width, height));
        

        其中widthheight 分别为以下各项之一:

        • 一个数字,使视图的宽度或高度精确到多少像素(要在 dp 中指定数字而不是像素,请参阅here
        • FrameLayout.LayoutParams.WRAP_CONTENT
        • FrameLayout.LayoutParams.MATCH_PARENT

        此外,如果您使用的是LinearLayout,则应改为使用LinearLayout.LayoutParamsRelativeLayout 也是如此。

        例如,如果您希望 textView 具有与声明为 <TextView android:layout_width="wrap_content" android:layout_height="match_parent"/> 相同的行为,您可以这样做

        textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT));
        

        【讨论】:

          【解决方案6】:

          试试这个>>>

          layoutParams.getLayoutParams().width = 20;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-11-11
            • 2013-07-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-03-08
            • 1970-01-01
            相关资源
            最近更新 更多