How to get Width/Height of Button in Fragment - android

How can i Get Height/Width of Any View (Button , TextView , RelativeLayout) in fragment, i try something like that
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;
}
my layout.xml file is
<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" />
i have a little research on that, I have found Width/Height of Button in Activity using this method.
#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);
}
but onWindowFocusChanged() is not available in android Fragment ?

In Fragment try below code in Fragment's onCreateView method:
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;
}
});

In Fragment use below code in Fragment's onCreateView method
ViewTreeObserver mviewtreeobs = button.getViewTreeObserver();
mviewtreeobs .addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
width = button.getWidth();
height = button.getHeight();
}
});

You could add a layout listener to your button like so:
button.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int width = button.getWidth();
if(width > 0){
int height = button.getHeight();
// do something with your width and height
....
// remove layout listener
button.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}

Related

getHeight() of PreferenceFragment

I have multiple FrameLayout inside a ScrollView. In one of the FrameLayout I'm loading a PreferenceFragment. Now I need to set the height of the FrameLayout to the height of the PreferenceFragment to avoid nested scrolling (the PrefrenceFragment is scrollable too).
How can I get the height of the PreferenceFragment?
I tried to override onCreateView() in the PreferenceFragment class, and call View.getHeight(), but its just returning 0.
Setting the FrameLayout to wrap_content, isn't working as well, its just taking the space of a single preference then...
edit:
I tried now to get the height by using addOnGlobalLayoutListener() but the returned value is just the displayed height, not the full height of the PreferenceFragment. So I'm just getting the height of one preference for wrap_content or e.g. 300 if I set the height of the FrameLayout to 300 in the xml. I need the full height of all preferences (visibile and not).
#Override
public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
{
final View v = super.onCreateView(paramLayoutInflater, paramViewGroup, paramBundle);
if (v != null) {
ViewTreeObserver vto = v.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Log.d("TEST", "Height = " + v.getHeight() + " Width = " + v.getWidth());
ViewTreeObserver obs = v.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
}
});
}
return v;
}
You should wait for WindowFocusChange in your activity:
#Override
public void onWindowFocusChanged(boolean hasFocus) {
if(hasFocus)
//LAYOUT FRAGMENT NOW
}
try this
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
height = parentLayout.getheight();// the root layout of the fragment
//TODO:
}
}, 200);

get width, height from Layout

I need to get width and height of Linear layout, however I do not know when the Relative Layout is ready to provide me these two attributes.
but it only returns 0.
my screen
please check my code, i have no idea.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
LinearLayout container = (LinearLayout)findViewById(R.id.container);
int width = container.getWidth();
int height = container.getWidth();
Log.d("MainActivity onCreate", "width #" + width + ", height #" + height);
}
}
and activity_main.xml layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:background="#FFFFFFAA"
android:orientation="vertical"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
</RelativeLayout>
how do i fix this?
Whenever you try to get dimensions on onResume() or on onCreate() method, it always returns 0. So you should use ViewTreeObserver
ViewTreeObserver vto = container.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
container.getViewTreeObserver().removeOnPreDrawListener(this);
finalHeight = container.getMeasuredHeight();
finalWidth = container.getMeasuredWidth();
return true;
}
});
Also you can customize your View which will extends with LinearLayout and in onMeasure() method you can get width and height.
First of all replace
int height = container.getWidth();
by
int height = container.getHeight();
container.getHeight() will return 0 (as well as container.getWidth()) if it's not drawed yet.
Solution would be to get the height after your view is layouted:
container.post(new Runnable(){
public void run(){
int height = container.getHeight();
}
});
You can try and mesaure it first. But make sure you do so only after every other view as been added beacuse your LinearLayout is depended on other views.
LinearLayout.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
LinearLayout.getMeasuredWidth();
Try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final LinearLayout container = (LinearLayout)findViewById(R.id.container);
container.post(new Runnable()
{
#Override
public void run()
{
Log.i("TEST", " Layout width : "+ container.getWidth() +" Layout height "+ container.getHeight()) ;
}
});
First, you are calling getWidth twice - for width and height.
You can try it with measureSpecs, like this:
int matchParentMeasureSpecWidth = View.MeasureSpec.makeMeasureSpec(((View) container.getParent()).getWidth(), View.MeasureSpec.EXACTLY);
int matchParentMeasureSpecHeight = View.MeasureSpec.makeMeasureSpec((View) container.getParent()).getHeight(), View.MeasureSpec.EXACTLY);
v.measure(matchParentMeasureSpecWidth, matchParentMeasureSpecHeight);
int height = container.getMeasuredHeight();

View Height returns 0, I want to return View height from onGlobalLayout

Here is my Code to return Height of view:
int height = 0;
public int getViewHeight(final View v) {
v.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
v.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
} else {
v.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
}
height = v.getMeasuredHeight();
//
Log.v(" height", v.getMeasuredHeight() + "");
}
});
Log.v(" return height", v.getMeasuredHeight() + "");
return height;
}
First It return 0. then the height value changes.
Can anyone let me know how to return height of view when it measured in onGlobalLayout. Return statement not working in overrided method.
OR
Is there any other way to make a static method which return height of view by passing View instance.
***try this way*
i get View Height and Width as per View**
public class Test extends Activity {
private RelativeLayout layout;
private int temp;
ViewTreeObserver vto;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
sharedPreferences = getSharedPreferences("savePref",
Context.MODE_PRIVATE);
layout = (RelativeLayout) findViewById(R.id.layout);
temp = set(layout);
Log.e("temp", "" + sharedPreferences.getInt("key", 0));
}
private int set(final RelativeLayout layout) {
vto = layout.getViewTreeObserver();
final Editor editor = sharedPreferences.edit();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
temp = layout.getMeasuredHeight();
editor.putInt("key", temp);
editor.commit();
}
});
if (sharedPreferences.contains("key")) {
Log.e("contains", "" + sharedPreferences.getInt("key", 0));
}
return sharedPreferences.getInt("key", 0);
}}

Relative Layout get Width/Height return 0

I need to get width and height of Relative layout, however I do not know when the Relative Layout is ready to provide me these two attributes. My activity has several tabs and I call the getWidth() and getHeight() in onCreateView() after inflater.inflate(R.layout.fragment_pizza, container, false);, however it returns 0 for both of them, so they are not apparently ready. Is there some kind of event like afterCreateView() or something similar where I can call these two methods and get the actual width and height?
Code:
public class PizzaFragment extends Fragment {
private static final String TAG = "PizzaFragment";
private Controller controller;
private static final int BUTTON_WIDTH = 70;
private static final int BUTTON_HEIGHT = 20;
private static final int MARGIN_LEFT = 80;
private static final int MARGIN_BOTTOM = 30;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
controller = Controller.getInstance();
controller.loadProducts("pizza", getActivity().getApplicationContext());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pizza, container, false);
RelativeLayout layout = (RelativeLayout) view.findViewById(R.id.rl_order_pizza);
Log.d(TAG, "Width: " + layout.getWidth());
Log.d(TAG, "Height: " + layout.getHeight());
int currentX = 10;
int currentY = 10;
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(BUTTON_WIDTH, BUTTON_HEIGHT);
for (Product product: controller.getProducts("pizza")){
Button tempButton = new Button(getActivity());
tempButton.setId(product.getId());
tempButton.setText(product.getName());
if (layout.getWidth() < currentX + MARGIN_LEFT){
currentX = 10;
currentY = MARGIN_BOTTOM;
}
else{
currentX += MARGIN_LEFT;
}
Log.d(TAG, "CurrentY: " + currentY);
Log.d(TAG, "CurrentX: " + currentX);
layoutParams.leftMargin = currentX;
layoutParams.bottomMargin = currentY;
tempButton.setLayoutParams(layoutParams);
layout.addView(tempButton);
}
return view;
}
}
My suggestion is to use a global layout listener like this in onCreateView:
YOUR_LAYOUT_INSTANCE = view.findViewById(R.id.YOUR_LAYOUT_ID);
...
YOUR_LAYOUT_INSTANCE.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
#Override
public void onGlobalLayout()
{
// gets called after layout has been done but before display.
if (Build.VERSION.SDK_INT < 16) {
YOUR_LAYOUT_INSTANCE.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
YOUR_LAYOUT_INSTANCE.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
// get width and height
}
});
addOnGlobalLayoutListener is deprecated use removeOnGlobalLayoutListener .For better handling extending the solution provided above by #fasteque
YOUR_LAYOUT_INSTANCE.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
#Override
public void onGlobalLayout()
{
// gets called after layout has been done but before display.
if (Build.VERSION.SDK_INT < 16) {
YOUR_LAYOUT_INSTANCE.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
else {
YOUR_LAYOUT_INSTANCE.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
// get width and height
}
});

Measure view in fragment

I need to know ImageView width and height. Is there a way to measure it in fragment ? In standard Activity I use this :
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
image.getWidth();
image.getHeight();
}
But where can I use image.getWidth(); and image.getHeight(); in fragment ?
Use the GlobalLayoutListener. You assign the listener to your ImageView in onCreateView() just like you do in that answer in the link. It also is more reliable than onWindowFocusChanged() for the main Activity so I recommend switching strategies.
EDIT
Example:
final View testView = findViewById(R.id.view_id);
ViewTreeObserver vto = testView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Log.d("TEST", "Height = " + testView.getHeight() + " Width = " + testView.getWidth());
ViewTreeObserver obs = testView.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
}
});

Categories

Resources