简体   繁体   中英

Change button height depending on width [Android]

I have a problem with buttons in Android Studio . I want some buttons to be square, and at the same time have a non-fix width based on weight . I mean this:

android:layout_width="0dip"
android:layout_weight="0.5"
android:layout_height="wrap_content"

I have looked for answers here, but none of them worked for me. I know it is not possible to do it via XML , so I've tried with the btn.getWidth() , btn.getLayoutParams().width ... in my Java code, but all of them return 0 as value.

Any idea?

If you want to set button size by code, you should do something like this (in your class that extends Button ):

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int width = getMeasuredWidth();
    int height = width;
    heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);}

or

    @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    int width = getMeasuredWidth();
    int height = width;
    setMeasuredDimension(width, height);
}

But there are an better way: create square png for all dpis and set it as a background of your button.

Use the following listener:

ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
       view.getViewTreeObserver().removeOnGlobalLayoutListener(this);

       //Here you can get and set the TextViews size.
    }
 });
}

You were getting 0's because at the time you checked the views weren't measured. To be sure that you'll get the actual view you can use this listener.

I have tested code this code at my end. Just Before onCreate() ends. just write these lines.

Button button= (Button ) findViewById(R.id.button);
button.post(new Runnable() {

            @Override
            public void run() {

                Log.e("",""+button.getHeight()+" "+button.getWidth());
            }
        });

If you have any query please let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM