将setOnCheckedChangeListener用于动态创建的单选按钮

时间:2018-11-01 05:47:56

标签: android radio-button radio-group

我已经关注stackoverflow很长时间了,但这是我在这里的第一篇文章。如果有错误,请对此感到抱歉。预先感谢。

我正在创建一些单选按钮,并尝试将其ID从100开始。在单选组中进行第二次选择后,它不会取消选中先前的单选按钮,并显示所有单选按钮具有相似的ID 110。

I/ContentValues: Radio button id Changed to:110 tea
I/ContentValues: Radio button id Changed to:110 tea
I/ContentValues: Radio button id Changed to:110 tea

这是屏幕截图。 https://image.ibb.co/mQHxtL/Screen-Shot-2018-11-01-at-12-58-25-AM.png

DashboardActivity.java

private List<Product> products_by_category;
private Menu menu;
private RadioGroup radioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);
        List<Product> arrayListProduct = Product.listAll(Product.class);
            radioGroup = (RadioGroup) findViewById(R.id.radioGroup_list);

        menu = new Menu(arrayListProduct);
        categories = menu.findAllCategories();

        addRadioButtons(menu.findAllCategories().size(), menu.findAllCategories());
        products_by_category = menu.findProductsByCategory(categories.get(0).getCatid());

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Log.i(TAG, "Radio button id Changed to:"+(i)+ " " + categories.get(i-101).getCategory());
                products_by_category = menu.findProductsByCategory(categories.get(i-101).getCatid());
                adapter.updateMenu(products_by_category);
            }
        });
}

public void addRadioButtons(int number,List<Category> categories) {
    for (int i = 1; i <= number; i++) {
       final RadioButton rdbtn = new RadioButton(getApplicationContext());
        rdbtn.setId(100+number);
        rdbtn.setTag(number);      rdbtn.setTextColor(ContextCompat.getColorStateList(this,R.color.custom_radio_color));             rdbtn.setTextColor(getResources().getColor(R.color.custom_radio_color,getTheme()));            
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        rdbtn.setBackground(getDrawable(R.drawable.custom_radio_btn));
        }else {
       rdbtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.custom_radio_btn,getTheme()));
        }
        rdbtn.setButtonDrawable(null);
        String str = categories.get(i-1).getCategory();
        rdbtn.setText(Const.makeCapitalFirstLettersOfAllWords(str));
        radioGroup.addView(rdbtn);
    }
    if(radioGroup.getChildCount() > 0)
        radioGroup.check(radioGroup.getChildAt(0).getId());
    }
}

activity_dashboard.xml

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.berkayayaz.restaurantdemo.DashboardActivity">

<HorizontalScrollView
    android:id="@+id/radioGroup_scroll_view"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:fillViewport="true"
    android:scrollbars="none"
    app:layout_constraintEnd_toStartOf="@+id/ll_1"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <RadioGroup
        android:id="@+id/radioGroup_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/custom_border"
        android:gravity="center"
        android:orientation="horizontal">

    </RadioGroup>


</HorizontalScrollView>
</android.support.constraint.ConstraintLayout>

如果我删除“ rdbtn.setId(100 + number);”在行中,setOnCheckedChangeListener可以正常工作,但是当我按下“后退”按钮并返回“ Dashboard Activity”时,已经使用不同的ID创建了单选按钮。这就是为什么它在“ menu.findProductsByCategory(categories.get(i-101).getCatid())”崩溃的原因;                     adapter.updateMenu(products_by_category);“行。

我找不到他们继续检查的任何原因。感谢所有帮助。 祝你今天愉快。

编辑:

我解决了我的问题。

private List<Product> products_by_category;
private Menu menu;
private RadioGroup radioGroup;
private int firstRadiobuttonId;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);
        List<Product> arrayListProduct = Product.listAll(Product.class);
            radioGroup = (RadioGroup) findViewById(R.id.radioGroup_list);

        menu = new Menu(arrayListProduct);
        categories = menu.findAllCategories();

        addRadioButtons(menu.findAllCategories().size(), menu.findAllCategories());
        products_by_category = menu.findProductsByCategory(categories.get(0).getCatid());

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                Log.i(TAG, "Radio button id Changed to:"+(i)+ " " + categories.get(i-firstRadiobuttonId).getCategory());
                products_by_category = menu.findProductsByCategory(categories.get(i-firstRadiobuttonId).getCatid());
                adapter.updateMenu(products_by_category);
            }
        });
}

public void addRadioButtons(int number,List<Category> categories) {
    for (int i = 1; i <= number; i++) {
       final RadioButton rdbtn = new RadioButton(getApplicationContext());
        rdbtn.setId(100+number);
        rdbtn.setTag(number);      rdbtn.setTextColor(ContextCompat.getColorStateList(this,R.color.custom_radio_color));             rdbtn.setTextColor(getResources().getColor(R.color.custom_radio_color,getTheme()));            
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        rdbtn.setBackground(getDrawable(R.drawable.custom_radio_btn));
        }else {
       rdbtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.custom_radio_btn,getTheme()));
        }
        rdbtn.setButtonDrawable(null);
        String str = categories.get(i-1).getCategory();
        rdbtn.setText(Const.makeCapitalFirstLettersOfAllWords(str));
        radioGroup.addView(rdbtn);
    }
    if(radioGroup.getChildCount() > 0)
        firstRadiobuttonId = radioGroup.getChildAt(0).getId();
        radioGroup.check(firstRadiobuttonId);
    }
}

0 个答案:

没有答案