1:fragmenthack5.java
Public classFragmentHack5extendsFragment {view view; ListView lvcountries; Button btnshow; Countrylistadapter adapter; List<String>list; @Override Public voidOnattach (activity activity) {Super. Onattach (activity); List=NewArraylist<string>(); List.add (China); List.add (Russia); List.add (United States); List.add (Germany); List.add (British); List.add (Spain); List.add (France); List.add (Brazil); List.add (India); } @Override PublicView Oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) {View= Inflater.inflate (R.layout.fragment_hack5,container,false); Btnshow=(Button) View.findviewbyid (r.id.btnshow); Lvcountries=(ListView) View.findviewbyid (r.id.lvcountries); Adapter=NewCountrylistadapter (Getactivity (), r.layout.list_country_item,list); Lvcountries.setadapter (adapter); Btnshow.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (view view) {Toast.maketext (Getactivity (), Adapter.getchoicecountry (), Toast.length_short). Show ( );; } }); returnview; }}
2:countrylistadapter.java
Public classCountrylistadapterextendsArrayadapter<string>{ intresourceId; intChoiceid =-1; PublicCountrylistadapter (Context context,intResourceId, list<string>objects) { Super(context,resourceid,objects); This. ResourceId =resourceId; } @Override PublicView GetView (Final intposition, View Convertview, ViewGroup parent) {String Country=GetItem (position); FinalViewholder Holder; if(convertview==NULL) {Holder=NewViewholder (); Convertview= Layoutinflater.from (GetContext ()). Inflate (ResourceId,NULL); Holder.rbcountry=(RadioButton) Convertview.findviewbyid (r.id.rbcountry); Convertview.settag (holder); }Else{Holder=(Viewholder) Convertview.gettag (); } holder.rbCountry.setText (country); if(choiceid==position) {holder.rbCountry.setChecked (true); }Else{holder.rbCountry.setChecked (false); } holder.rbCountry.setOnClickListener (NewView.onclicklistener () {@Override Public voidOnClick (view view) {if(holder.rbCountry.isChecked ()) {Choiceid= position;//remember the currently selected subscriptCountrylistadapter. This. notifydatasetchanged (); } } }); returnConvertview; } Static classviewholder{ PublicRadioButton Rbcountry; } PublicString getchoicecountry () {returnGetItem (Choiceid); }}
3: Run Results
RadioButton implementation of single selection in ListView