自定义列表视图中的单选按钮 - 应该只选择一次

时间:2013-03-07 10:00:35

标签: android android-listview radio-button

我陷入了需要获取已检查Radiobutton ID的情况。我知道问题出在哪里,但我无法解决,所以请根据我的代码建议我。

@Override
public View getView(int position, View convertView, ViewGroup parent) {     
    ViewHolder holder=null;

    bean=arrayListCountry.get(position);

    LayoutInflater inflater=(LayoutInflater)context.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
    if(convertView==null)
    {
        convertView=inflater.inflate(R.layout.custom_layout_listview, null);
        holder=new ViewHolder();
        holder.textCountryName=(TextView)convertView.findViewById(R.id.textView1);
        holder.radioCountry=(RadioButton)convertView.findViewById(R.id.radioButton1);
        RelativeLayout relativeLayout=(RelativeLayout)convertView.findViewById(R.id.relativeCustomLayout);
        relativeLayout.addView(convertView);
        convertView.setTag(holder);
        convertView.setTag(R.id.textView1,holder.textCountryName);


    }
    else
        holder=(ViewHolder)convertView.getTag();

    holder.radioCountry.setTag(position);

    holder.textCountryName.setText(bean.getCountryName());
    holder.radioCountry.setChecked(bean.getIsSelected());

    holder.radioCountry.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub

            int pos=(Integer)buttonView.getTag();

            Country_Bean country_Bean=arrayListCountry.get(pos);


            coubean.setIsSelected(buttonView.isChecked());


            //buttonView.setChecked(bean.getIsSelected());

            Toast.makeText(context, "POs:"+pos+"\ncountry:"+bean.getCountryName()+"\ncountry_check:"+bean.getIsSelected()+"\nbuttonCheck:"+buttonView.isChecked(), Toast.LENGTH_SHORT).show();
        }
    });

    return convertView;
}

请告诉我如何获得特定的radiobutton。我也想知道为什么getView正常使用,我们如何手动调用该方法。先谢谢你。

2 个答案:

答案 0 :(得分:1)

enter image description here

我已经从我这边做了,并在我的Android博客上发布了完整的源代码供参考。

http://amitandroid.blogspot.in/2013/03/android-custon-single-choice-lsitview.html

答案 1 :(得分:0)

你试过RadioGroup吗?它是许多RadioButton的容器。它甚至有一个名为getCheckedRadioButtonId()的方法。


除此之外,我发现你没有遵循打字惯例。我对此非常严格,并为我内部的代码语法 - 纳粹道歉。

如果bean是成员变量,那么使用mBean。

bean=arrayListCountry.get(position);

将是:

mBean=arrayListCountry.get(position);

Country_Bean不是类的正确名称。

Country_Bean

将是:

CountryBean

范围变量名country_Bean也是错误的。

country_Bean

将是:

countryBean

此外,如果使用Eclipse,请尝试使用自动格式,因为它会使代码更漂亮(CTRL + SHIFT + F)。

相关问题