always display 3 buttons in a HorizontalScrollView

前端 未结 1 891
耶瑟儿~
耶瑟儿~ 2021-01-15 09:05

\"3

Hello everyone I am trying to display 3 to X buttons on android. The idea is to always

相关标签:
1条回答
  • 2021-01-15 10:03

    If you are setting the size dynamically and there are unknown number of child views, then weight approach isn't that feasible. Instead get the width of the screen, and based on that set the width of the button. Also, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 0.33f)); this line in your code will not work as you expected. You need to set the params to button to make it work.

    You can try something like this,

    HomeCircledButton button = HomeCircledButton_.build(this);
    button.title.setText(sc.get(i).getLabel());
    //divide the screen width by 3
    int buttonWidth = getScreenWidth() / 3;
    LinearLayout.LayoutParams buttonparams= new LinearLayout.LayoutParams(buttonWidth, LinearLayout.LayoutParams.MATCH_PARENT);
    button.setLayoutParams(buttonparams);
    homeButtonsLL.addView(button);
    

    ...

    private int getScreenWidth( ) {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            int width;
            getWindowManager().getDefaultDisplay()
            .getMetrics(displayMetrics);
            width = displayMetrics.widthPixels;
            return width;
        }
    

    and you don't have to set weight sum in xml,

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:orientation="horizontal"
                    android:gravity="center"
                    android:id="@+id/home_buttons_ll">
               </LinearLayout>
      </HorizontalScrollView>
    
    0 讨论(0)
提交回复
热议问题