【问题标题】:Programatically changing Textview height and width以编程方式更改 Textview 的高度和宽度
【发布时间】:2017-02-28 11:54:19
【问题描述】:

我有一个文本视图,我想将宽度更改为 match_parent,并将高度更改为 wrap_content。它嵌套在水平线性布局中。它是 3 个文本视图中的第 2 个,每个文本视图的权重为 1。运行此特定片段时,它将其他两个按钮设置为

previousButton.setVisibility(View.GONE);
nextButton.setVisibility(View.GONE);

文本视图

           <TextView
                android:id="@+id/home"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="HOME"
                android:layout_weight="1"
                android:background="@drawable/button_selector"
                android:layout_marginLeft="10dp"
                android:layout_marginBottom="10dp"
                android:padding="10dp"
                android:gravity="center"
                android:textColor="#000000"
                android:textStyle="bold"
                android:onClick="home"
                />

我正在使用以下内容尝试更改片段中的布局:

homeButton.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

当我运行它时,我得到了错误:

java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams

【问题讨论】:

  • 错误比较明显。您不能将 ViewGroup 转换为 LinearLayout。所以我猜你的TextView 的父布局是Linear?

标签: android layoutparams


【解决方案1】:

您已经给出了 layout_width = "0dp" 和 layout_weight="1"。因此,当其他两个按钮将隐藏时。这个主页按钮将占据全宽。但是 View.INVISIBLE 不会将它们从宽度中移除。您应该使用 View.GONE 以便即使它们不可见,它们也不应该占用宽度。

隐形:

 This view is invisible, but it still takes up space for layout purposes.

走了:

 This view is invisible, and it doesn't take any space for layout purposes.

您无需在 Home TextView 上再次设置 Layout Params。

【讨论】:

  • 开发者已经以编程方式使用了 View.GONE 属性
【解决方案2】:

假设你的父母是LinearLayout

LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
homeButton.setLayoutParams(layoutParam);

【讨论】:

    【解决方案3】:

    你的 TextView 父布局是什么?线性,相对还是什么? 线性布局示例:

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    homeButton.setLayoutParams(params);
    

    您必须根据其父布局创建参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-14
      • 2019-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 2013-01-13
      相关资源
      最近更新 更多