2013-03-07 32 views
0

我陷入了一种情况,我需要获取选中的Radiobutton的ID。我知道问题出在哪里,但我无法解决问题,请在我的代码基础上给我建议。自定义列表视图中的Radiobutton - 一次只能选择一个

@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; 
} 

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

回答

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)。

+0

我已经使用它,但不是与listview,所以我使用单个单选按钮和使用RadioGroup可能不是很好的地方只需要单个单选按钮。是的,它可能是简单的方法,但更多的项目将在我的列表视图中,更多的radiogroups将被创建。使用radioGroup将是我完成此操作的最后一招。谢谢。 – IamExpo 2013-03-07 10:15:27

+0

好的,先生,下次我会介意它。我感谢你的建议。谢谢。 – IamExpo 2013-03-07 10:18:31

+0

不客气,希望您找到高效的解决方案! :) – 2013-03-07 10:19:27

1

enter image description here

我已经从我的身边做,并张贴了完整的源代码在我的Android博客的参考。

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

希望这个博客会帮助你。

谢谢,您的反馈将不胜感激。

如果这篇文章符合您的要求,请接受我的回答。

+0

谢谢你的帖子阿米特,但我认为这是更重要的,我们应该处理这些事情没有太多的帮助。我试过了,我完成了任务。所以我不需要你的教程。将来如果我卡住某处,我会寻找使用它。再次感谢阿米特。我们会保持联系。 – IamExpo 2013-03-07 13:22:16

相关问题