任何人都请告诉我,如何从列表视图中选择。 listview中的单个项目行包含一个文本,后跟一个单选按钮。
代码: XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="singleChoice"
/>
</LinearLayout>
和活动:
public class MainActivity extends Activity {
String[] countries = new String[] {
"India",
"Pakistan",
"Sri Lanka",
"China",
"Bangladesh",
"Nepal",
"Afghanistan",
"North Korea",
"South Korea",
"Japan"
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Getting object reference to listview of main.xml
ListView listView = (ListView) findViewById(R.id.listview);
// Instantiating array adapter to populate the listView
// The layout android.R.layout.simple_list_item_single_choice creates radio button for each listview item
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice,countries);
listView.setAdapter(adapter);
}
}
代码工作正常..
但我的问题是
1)如何设置默认选择?
2)获取所选项目?
答案 0 :(得分:0)
1)您可以使用setSelection设置默认值。例如,在您的代码中,在设置适配器后将其放入。
listView.setAdapter(adapter);
listview.setSelection(0); //default is India
2)您可以使用getSelectedItem()从列表视图中获取所选国家/地区。例如,如果您有保存方法,则在您的代码中
private void save() {
String selectedCountry = (String) listview.getSelectedItem();
//TODO
}
答案 1 :(得分:0)
我通过这种方式得到了我想要的输出:
回答1)如何设置默认选择:
ctx.save();
// draw all the sprites
ctx.restore();
回答2)获取所选项目:
int defaultselected=0,idnoreid=0;
listView.setItemChecked(defaultselected, true);
listView.performItemClick(listView.getSelectedView(), defaultselected, idnoreid);