简体   繁体   中英

Android Buttons same height as width

in my Android App I have 3 Buttons which i set to 33% of the Screen-Width with the weight parameter. Now i want these buttons to have the same height as width, but without "hardcoding" a specific sice to the height, to adjust to different screensizes.

How can i handle this? Thanks!

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

        <Button
            android:id="@+id/buttonPlus1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.33"
            android:layout_margin="5dp"
            android:background="@drawable/buttonstyle"
            android:text="+1" />

        <Button
            android:id="@+id/buttonPlus5"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.33"
            android:layout_margin="5dp"
            android:background="@drawable/buttonstyle"
            android:text="+5" />

        <Button
            android:id="@+id/buttonPlus10"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.33"
            android:layout_margin="5dp"
            android:background="@drawable/buttonstyle"
            android:text="+10" />
</LinearLayout>

I have come up with a solution and it's tested and working properly.

在此处输入图片说明

inside onCreate()

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

     b1 = findViewById(R.id.button1);
     b2 = findViewById(R.id.button2);
     b3 = findViewById(R.id.button3);

    layout = findViewById(R.id.linearContainerOfButton);
    ViewTreeObserver vto = layout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            int width = b1.getWidth();

            ViewGroup.LayoutParams params = b1.getLayoutParams();

            Log.d(tag, "width " + width);
            params.height = width;
            b1.setLayoutParams(params);
            b2.setLayoutParams(params);
            b3.setLayoutParams(params);


        }
    });

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