我想在 fragment 中创建一个方形按钮。我的 fragment 布局文件是:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="2"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp"
android:weightSum="2"
>
<Button
android:id="@+id/main_menu_news"
android:text="@string/main_menu_news_text"
style="@style/buttons"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_marginRight="5dp"
/>
<Button
android:id="@+id/main_menu_insta"
android:text="@string/main_menu_insta_text"
style="@style/buttons"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_marginLeft="5dp"
/>
</LinearLayout>
我在 onCreateView
中更改了按钮的高度。这个函数的实现是:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreateView(inflater, container, savedInstanceState);
View view=inflater.inflate(R.layout.main_menu, container, false);
ViewGroup layout = (ViewGroup) getActivity().getLayoutInflater().inflate(R.layout.main_menu, null);
for(int i=0;i<layout.getChildCount();i++){
View v=layout.getChildAt(i);
if(v instanceof ViewGroup){
ViewGroup vg=(ViewGroup)v;
for(int j=0;j<vg.getChildCount();j++){
View v2=vg.getChildAt(j);
if(v2 instanceof Button){
Button btn=(Button)v2;
btn.setHeight(btn.getMeasuredWidth());
}
}
}
}
return view;
}
我无法在 onCreateView
中更改按钮的高度,并且 getMeasuredWidth
函数始终返回 0。
我该如何解决?
最佳答案
要解决此问题,您可以创建一个包含内容维度的线性布局,并将此按钮添加到该布局。然后设置按钮的高度,然后我认为 getMeasuredWidth()
不应返回 0。
这是我的一段代码,你可以根据自己的情况定制
LinearLayout newLL = new LinearLayout(mContext);
newLL.setLayoutParams(newLinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
newLL.setOrientation(LinearLayout.HORIZONTAL);
newLL.setGravity(Gravity.LEFT);
newLL.addView(btn);
widthSoFar = btn.getMeasuredWidth();
关于java - 在android中更改高度按钮java代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38224849/