gpt4 book ai didi

android - 如何在 fragment 中获取按钮的宽度/高度

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:58:42 30 4
gpt4 key购买 nike

如何在 fragment 中获取任何 View (Button、TextView、RelativeLayout)的高度/宽度,我尝试类似的方法

 public static class FirstDemoFragment extends Fragment {

int width,height;
private Button button;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
button = (Button) view.findViewById(R.id.fragment_demo_button);

width = button.getWidth();
height = button.getHeight();


System.out.println("==== View Width : " + width);
System.out.println("==== View height : " + height);

width = button.getMeasuredWidth();
height = button.getMeasuredHeight();


System.out.println("==== View Width : " + width);
System.out.println("==== View height : " + height);

return view;
}

我的layout.xml文件是

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/does_really_work_with_fragments"
android:id="@+id/fragment_demo_button"
android:layout_centerInParent="true" />

我对此进行了一些研究,我使用这种方法找到了 Activity 中按钮的宽度/高度。

@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
relMain = (RelativeLayout) findViewById(R.id.layoutMain);

width = relMain.getMeasuredWidth();
height = relMain.getMeasuredHeight();

width = relMain.getWidth();
height = relMain.getHeight();

//System.out.println("=== Width : " + width);
//System.out.println("=== height : " + height);


}

但是 onWindowFocusChanged() 在 android Fragment 中不可用?

最佳答案

在 Fragment 的 onCreateView 方法中尝试下面的代码:

button = (Button) view.findViewById(R.id.fragment_demo_button);   
ViewTreeObserver vto = button.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
button.getViewTreeObserver().removeOnPreDrawListener(this);
Log.d("", "Height: " + button.getMeasuredHeight()+ " Width: " + button.getMeasuredWidth());
return true;
}
});

关于android - 如何在 fragment 中获取按钮的宽度/高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37477420/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com