这个我的代码如下
private ListView listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addItemsOnlistv1();
}
public void addItemsOnlistv1() {
listview = (ListView) findViewById(R.id.listView1);
List<String> list = new ArrayList<String>();
list.add("Option 1");
list.add("Option 2");
final int listsize = list.size() - 1;
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list){
};
listview.setAdapter(dataAdapter);
listview.setSelection(listsize);
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (listview.getSelectedItem().toString().equals("Option 1")){
Toast.makeText(getApplicationContext(), "Option 1 Selected", Toast.LENGTH_LONG).show();
}
if (listview.getSelectedItem().toString().equals("Option 2")){
Toast.makeText(getApplicationContext(), "Option 2 Selected", Toast.LENGTH_LONG).show();
}
}
});
}
但是当我选择我的应用程序强制关闭选项时,任何人都可以弄清楚代码有什么问题我试图直接在java中包含列表而不使用任何xml或任何支持?
这是我的logcat在单击选项
时以红色显示的内容03-31 14:38:56.579:E / AndroidRuntime(23480):致命异常:主要 03-31 14:38:56.579:E / AndroidRuntime(23480): java.lang.NullPointerException 03-31 14:38:56.579: E / AndroidRuntime(23480):at zzz.zzz.zzz.MainActivity $ 2.onItemClick(MainActivity.java:51)03-31 14:38:56.579:E / AndroidRuntime(23480):at android.widget.AdapterView.performItemClick(AdapterView.java:301) 03-31 14:38:56.579:E / AndroidRuntime(23480):at android.widget.AbsListView.performItemClick(AbsListView.java:1280) 03-31 14:38:56.579:E / AndroidRuntime(23480):at android.widget.AbsListView $ PerformClick.run(AbsListView.java:3071) 03-31 14:38:56.579:E / AndroidRuntime(23480):at android.widget.AbsListView $ 1.run(AbsListView.java:3971)03-31 14:38:56.579:E / AndroidRuntime(23480):at android.os.Handler.handleCallback(Handler.java:615)03-31 14:38:56.579:E / AndroidRuntime(23480):at android.os.Handler.dispatchMessage(Handler.java:92)03-31 14:38:56.579:E / AndroidRuntime(23480):at android.os.Looper.loop(Looper.java:137)03-31 14:38:56.579: E / AndroidRuntime(23480):at android.app.ActivityThread.main(ActivityThread.java:4960)03-31 14:38:56.579:E / AndroidRuntime(23480):at java.lang.reflect.Method.invokeNative(Native Method)03-31 14:38:56.579:E / AndroidRuntime(23480):at java.lang.reflect.Method.invoke(Method.java:511)03-31 14:38:56.579: E / AndroidRuntime(23480):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1038) 03-31 14:38:56.579:E / AndroidRuntime(23480):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)03-31 14:38:56.579:E / AndroidRuntime(23480):at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)03-31 14:38:56.579:E / AndroidRuntime(23480):at dalvik.system.NativeStart.main(原生方法)
答案 0 :(得分:0)
从
更改此内容listview.getSelectedItem().toString().equals("Option 1")
到
list.get(position).toString().equals("Option 1")