1. 程式人生 > >使用rediobutton實現多個標題橫向划動

使用rediobutton實現多個標題橫向划動

<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="3dp"
    android:scrollbars="none">

    <RadioGroup
        android:id="@+id/rg_homefragment"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="4dp"
        android:orientation="horizontal"
        android:paddingLeft="2dp"
        android:paddingRight="2dp">
    </RadioGroup>

</Horizo
//獲取區域
public void getAreaData(final List<String> areaString) {
    radioGroup.removeAllViews();
    for (int i = 0; i < areaString.size(); i++) {
        RadioButton radioButton = new RadioButton(MainActivity.this);
        radioButton.setText(areaString.get(i));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(75, ViewGroup.LayoutParams.MATCH_PARENT);
        radioButton.setLayoutParams(params);
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            try {
                Field field = radioButton.getClass().getSuperclass().getDeclaredField("mButtonDrawable");
                field.setAccessible(true);
                field.set(radioButton, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            radioButton.setButtonDrawable(null);
        }
        radioButton.setBackgroundResource(R.drawable.selector_homebg);
       /* if (i == 0) {
            radioButton.setBackgroundResource(R.drawable.selector_shop_show_left_bg);
        }
        radioButton.setBackgroundResource(R.drawable.selector_shop_show_centre_bg);

        if (i == areaString.size() - 1) {
            radioButton.setBackgroundResource(R.drawable.selector_shop_show_right_bg);
        }*/
        ColorStateList colors = getResources().getColorStateList(R.color.selector_home);
        radioButton.setTextColor(colors);
        radioButton.setGravity(Gravity.CENTER | Gravity.CENTER_VERTICAL);

        final int finalI = i;
        radioButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });
        radioGroup.addView(radioButton);
    }
    //設定第一個的背景
    radioGroup.getChildAt(0).setBackgroundResource(R.drawable.item_home_select);
    radioGroup.getChildAt(0).performClick();
}
ntalScrollView>
radioGroup = findViewById(R.id.rg_homefragment);
 list = new ArrayList<>();
 for (int i = 0; i < 10; i++) {
     list.add("title" + i);
 }
 getAreaData(list);