简体   繁体   English

根据宽度更改按钮的高度[Android]

[英]Change button height depending on width [Android]

I have a problem with buttons in Android Studio . 我在Android Studio遇到按钮问题。 I want some buttons to be square, and at the same time have a non-fix width based on weight . 我希望某些按钮为正方形,并且同时具有基于weightnon-fix width 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. 我知道不可能通过XML做到这一点,所以我在Java代码中尝试了btn.getWidth()btn.getLayoutParams().width ...,但是它们都return 0作为值。

Any idea? 任何想法?

If you want to set button size by code, you should do something like this (in your class that extends Button ): 如果要通过代码设置按钮大小,则应执行以下操作(在扩展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. 但是有一种更好的方法:为所有dpi创建正方形png并将其设置为按钮的背景。

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. 之所以得到0,是因为在您检查视图时未进行度量。 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. 就在onCreate()结束之前。 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. 如果您有任何疑问,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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