我制作了一个listview,我想让用户输入一个选择。我怎样才能做到这一点? Atm我只设法创建ListView并显示数据。
是否有一种简单的方法可以获取ListView中所选项的值并在以后使用它?类似于ListView RadioButton。
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tiagosilva.amob_android.TubeDataArchive" >
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/lv_tubeData"
android:choiceMode="singleChoice">
</ListView>
列表视图:
public class TubeDataArchive extends Fragment {
public TubeDataArchive() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tube_data_archive, container, false);
ListView tubeDataList = (ListView) view.findViewById(R.id.lv_tubeData);
//load tube data
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
String tubeDataString = settings.getString("tubeData", "");
String[] tubeDataSplit = tubeDataString.split("\n");
List<String> tubeDataItems = new ArrayList<>();
for(int i=0; i<tubeDataSplit.length;i++)
{
tubeDataItems.add(tubeDataSplit[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, tubeDataItems);
// Assign adapter to ListView
tubeDataList.setAdapter(adapter);
return view;
}
}
答案 0 :(得分:0)
是否有一种简单的方法来获取所选项目的价值 ListView并在以后使用它?
在for循环后添加onItemClickListener
。
tubeDataList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// do whatever you want
Log.d("############","Items " + tubeDataSplit[arg2] );
}
});
类似于ListView RadioButton
如果您希望listview
包含radio button
,则需要创建自定义listview
布局。
答案 1 :(得分:-1)
将ItemClickListener添加到列表视图
tubeDataList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getapplicationcontext(), tubeDataItems.get(id),
Toast.LENGTH_LONG).show();
}
});