I'm using a viewfager and a fragment on Android. Among them, I want to find the width of the linear layout in one fragment. I'm a student practicing examples.
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = (ViewGroup)inflater.inflate(R.layout.tab_fragment_1, container, false);
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
rootView.getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener);
LinearLayout linearForTime = (LinearLayout) rootView.findViewById(R.id.time);
int Width = forTimeWidth.getMeasuredWidth() / 5;
}
The code is as above. I want to find the width of the linear layout in tab_fragment1, but if I write the code as above, it will not be executed with the following error.
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.LinearLayout.getMeasuredWidth()' on a null object reference at example.com.mptermui.TabFragment1.onActivityCreated(TabFragment1.java:149)
Code 149 is int Width = for Time Width.getMeasuredWidth() / 5; here.
fragment android
The following code to find the width of the code you wrote,
LinearLayout linearForTime = (LinearLayout) rootView.findViewById(R.id.time);
int Width = forTimeWidth.getMeasuredWidth() / 5;
Please write inside ViewTreeObserver.OnGlobalLayoutListener as shown below.
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
rootView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
LinearLayout linearForTime = (LinearLayout) rootView.findViewById(R.id.time);
int Width = linearForTime.getMeasuredWidth() / 5;
}
});
If the same error occurs even after writing it like this, it will be necessary to verify that R.id.time exists inside the layout file tab_fragment_1.xml.
© 2024 OneMinuteCode. All rights reserved.