Android:从自定义视图

时间:2017-04-24 05:53:17

标签: android android-radiobutton

我为单选按钮创建了一个自定义视图。 如何从自定义视图中获取RadioButton的值,并希望一次选择一个单选按钮。

public void getData(){
    cappingLayout.removeAllViews();
    for (Capping capping: productList.getCappingList()){
        if (getActivity()!=null) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.product_capping, cappingLayout, false);
            cappingRadio = (RadioButton) view.findViewById(R.id.fragment_product_detail_capping);
            cappingRadio.setText(capping.getCapping_type());
            cappingLayout.addView(view);
        }
    }
}

Product_capping.xml

<RadioButton
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fragment_product_detail_capping"
    style="@style/Widget.AppCompat.CompoundButton.CheckBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textStyle="bold"
    tools:text="Normal"/>

我希望在单击按钮后获得单选按钮的值。

2 个答案:

答案 0 :(得分:0)

你可以试试这个;

  rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                int childCount = group.getChildCount();
                for (int x = 0; x < childCount; x++) {
                    RadioButton btn = (RadioButton) group.getChildAt(x);

                    if (btn.getId() == checkedId) {

                        System.out.println(btn.getText().toString());


                }

            }
        });

或者你可以像这样获得价值manuel;

    public void hesap(View view) {

    if(rb1.isChecked())
        hsp.setText("rb1 Value");
    if(rb2.isChecked())
        hsp.setText("rb2 Value");
    if(rb3.isChecked())
        hsp.setText("rb3 Value");
    }

答案 1 :(得分:0)

你需要把单选按钮放在xml文件中的下面的广播组中

rg_gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId == R.id.rb_male) {
                    gender = "male";
                } else {
                    gender = "female";
                }
            }
        });

然后你可以从java文件中的无线电组中检索选定的单选按钮

SELECT max(whatever) as whatever
FROM MyTable
WHERE something = myQuery
HAVING  COUNT(*) = 1