2013-03-07 66 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

相關問題