【问题标题】:Is it possible set wrapContent attribute on view without parrent?是否可以在没有父视图的情况下设置包装内容属性?
【发布时间】:2016-03-07 12:15:41
【问题描述】:

我有一个简单的按钮视图,并将其设置为内容视图。是否可以通过编程方式将此视图的大小调整为“wrap_content”?

Button button = new Button(getContext());
button.setText("Some text");
setContentView(button);

【问题讨论】:

    标签: android view android-wrap-content


    【解决方案1】:

    使用以下代码设置您的属性:

    Button button = new Button(getContext());
    
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT);
    button.setLayoutParams(params);
    
    button.setText("Some text");
    setContentView(button);
    

    【讨论】:

      【解决方案2】:

      您不能为没有父视图的视图设置LayoutParams

      【讨论】:

      • 这是否意味着我没有任何方法可以更改视图大小而无需在布局中包装此视图?
      • 是的,如果没有布局,您的按钮将无法显示。
      • 我的按钮可以显示,它的 with 和 height 等于屏幕尺寸,但似乎 android 不会隐式创建一些布局,因为 getParrent() 或 getLayoutParams() 返回 null
      • @VitaliZaharenko 实际上,在这种情况下,您的按钮将添加到由WindowManager 管理的Window。阅读更多:stackoverflow.com/a/22442702/1798031
      【解决方案3】:

      你必须使用 LinearLayout.LayoutParams 这样的东西:

      Button button = new Button(getContext());
      
      LinearLayout.LayoutParams params = new   LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
              LayoutParams.WRAP_CONTENT);
      button.setLayoutParams(params);
      params.weight = 1.0f;
      button.setText("Some text");
      setContentView(button);
      

      【讨论】:

        猜你喜欢
        • 2019-06-16
        • 1970-01-01
        • 1970-01-01
        • 2018-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多