我要进入android系统的第一步,如果这是个愚蠢的问题,我很抱歉。
我遵循这教程来实现包含ListView的DialogFragment。这是ColorDialogFragment.java
public class ColorDialogFragment extends DialogFragment {
String[] listItems = { "Red", "Blue", "Green"};
ListView myList;
String ipAddress;
public static ColorDialogFragment newInstance(String ipAddress) {
Bundle args = new Bundle();
args.putString("ipAddress",ipAddress);
ColorDialogFragment fragment = new ColorDialogFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ipAddress = getArguments().getString("ipAddress");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_fragment, null, false);
myList = (ListView) view.findViewById(R.id.list);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, listItems);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String colorHex;
switch (i){
case 1:
colorHex = "#FF0000";
break;
case 2:
colorHex = "#0000FF";
break;
case 3:
colorHex = "#00FF00";
break;
default:
dismiss();
return;
}
ClientAsyncTask clientAsyncTask = new ClientAsyncTask(ipAddress, colorHex);
clientAsyncTask.execute();
dismiss();
}
});
}
private class ClientAsyncTask extends AsyncTask<Void, Void, Void> {
...
}
}这是dialog_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
</LinearLayout>问题是,当我单击列表项时,onItemClick()不会被调用(显然,我不明白为什么)。
发布于 2016-02-01 01:13:21
我自己发现问题是switch语句中的错误索引(显然从0开始,而不是从1开始)。
https://stackoverflow.com/questions/35110587
复制相似问题