Programatically changing Textview height and width

浪子不回头ぞ 提交于 2019-12-02 20:15:53

问题


I have a textview that I want to change the width to match_parent and height to remain at wrap_content. It is nested within a horizontal linearlayout. It is the 2nd in 3 textviews each of which has a weight of 1. When this particular fragment is run it sets the other two buttons to

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"
                />

I am using the following to try to change the layout in a fragment:

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

When I run it I get the error:

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

回答1:


What is your TextView parent layout? Linear, Relative or what? Sample if LinearLayout:

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

You must create param base on its parent layout.




回答2:


Assuming your parent is a LinearLayout

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



回答3:


You have already given the layout_width = "0dp" and layout_weight="1". So, when other two buttons will hide. This home button will take full width. But View.INVISIBLE won't remove them from taking width. You should use View.GONE so that even if they are not visible, they shouldn't take width.

INVISIBLE:

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

GONE:

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

You don't need to set Layout Params again on Home TextView.



来源:https://stackoverflow.com/questions/40121265/programatically-changing-textview-height-and-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!