以编程方式更改 Textview 的高度和宽度

Programatically changing Textview height and width

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

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

TextView

           <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

您的 TextView 父布局是什么?线性、相对还是什么? 如果 LinearLayout:

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

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

假设您的 parent 是 LinearLayout

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

您已经给出了 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。