简体   繁体   English

为listItem设置OnItemClickListener

[英]Set OnItemClickListener for a listItem

I get how to do this for a simple ListView, something like: 我得到了如何通过简单的ListView来执行此操作,例如:

listView.setOnItemClickListener(new OnItemClickListener() {

              @Override
              public void onItemClick(AdapterView<?> parent, View view,
                 int position, long id) {

But whenever I do it in my activity I get a nullpointerexception. 但是每当我在活动中这样做时,我都会得到一个nullpointerexception。

Could someone please show me how it is supposed to be? 有人可以告诉我应该怎么做吗? Thanks! 谢谢!

EDIT: I'm sorry! 编辑:对不起! Didn't want to fill up an entire question only with code, I think it's necessary in this case, so I'm putting my entire java code below: 不想只用代码填充整个问题,在这种情况下,我认为这是必要的,因此我将整个Java代码放在下面:

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;


public class Save extends ListActivity {
String FileName;
EditText et;
String listItem[]={};
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.activity_save);
    Button save = (Button) findViewById(R.id.SAVE); //this is my button
    final EditText title = (EditText) findViewById(R.id.save_filename); //This is unused
    final EditText maintext = (EditText) findViewById(R.id.test);
    getActionBar().setDisplayUseLogoEnabled(false);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    et = (EditText) findViewById(R.id.save_filename);
    listView = (ListView) findViewById(R.id.list); //I've specified this listView only for the OnItemClickListener action

    List values = new ArrayList();
    for (int i = 0; i < listItem.length; i++) {
        values.add(listItem[i]);
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);

    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                FileName = et.getText().toString() + ".txt";
                FileOutputStream fout = openFileOutput(FileName, Context.MODE_PRIVATE);
                OutputStreamWriter outsw = new OutputStreamWriter(fout);
                try {
                    outsw.write(String.valueOf(maintext));
                    outsw.flush();
                    outsw.close();
                    Toast.makeText(getBaseContext(), "Your file has been saved", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
            String device;
            switch (view.getId()) {
                case R.id.SAVE:
                    List myList = new ArrayList();
                    device = et.getText().toString();
                    myList.add(device);
                    adapter.add(device);
                    et.setText("");
                    break;
            }
            adapter.notifyDataSetChanged();
        }
    });

    //I think this is wrong, I get no error in Java by the way. How could this work if there's a specific extension for my activity that define the listview? **That's my question**. 
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // ListView Clicked item index
            int itemPosition     = position;

            // ListView Clicked item value
            String  itemValue    = (String) listView.getItemAtPosition(position);

            // Show Alert
            Toast.makeText(getApplicationContext(),
                    "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                    .show();
        }
    });

}

And the xml: 和xml:

<Button
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:id="@+id/SAVE"
    android:text="@string/save_button" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/save_filename"
    android:layout_alignRight="@+id/linearLayout"
    android:hint="@string/save_hint"
    android:layout_alignEnd="@+id/linearLayout"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="5dp" />

<ListView
    android:id="@android:id/list"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:layout_above="@+id/linearLayout"
    android:layout_below="@+id/save_filename">
</ListView>

Sorry again for the cunfusion!! 再次抱歉!

The problem here comes from the fact that you are using ListActivity instead of Activity. 这里的问题来自您使用ListActivity而不是Activity的事实。 For this reason the ListView's ID is not added to the R file so it is not callable by the findById call. 因此,ListView的ID不会添加到R文件中,因此无法通过findById调用进行调用。 This would not happen if Activity were used. 如果使用活动,则不会发生这种情况。 When using ListActivity you can use the built in getListView() method to get the ListView object. 使用ListActivity时,可以使用内置的getListView()方法获取ListView对象。 Also when I ran your given code I got an error that a listView had to be defined by the ID list. 另外,当我运行您的给定代码时,我得到一个错误,即必须由ID列表定义listView。 This comes from an error in your XML file when you defined the ID. 这是由于您在定义ID时XML文件中的错误。

Below I posted two sections from your given XML 下面我从您给定的XML中发布了两个部分

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/save_filename"

<ListView
    android:id="@android:id/list"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:layout_above="@+id/linearLayout"
    android:layout_below="@+id/save_filename">
</ListView>

Notice when defining the id, the top one says android:id="@+id/save_filename" while the bottom says android:id="@android:id/list". Also when you use save_file_name it is done like this 请注意,在定义ID时,最上面的是android:id="@+id/save_filename" ,最下面的是android:id="@android:id/list". Also when you use save_file_name it is done like this android:id="@android:id/list". Also when you use save_file_name it is done like this android:layout_below="@+id/save_filename" This is incorrect. To define an id you use android:id="@android:id/list". Also when you use save_file_name it is done like this android:layout_below =“ @ + id / save_filename” This is incorrect. To define an id you use This is incorrect. To define an id you use @+id`. This is incorrect. To define an id you use @ + id`。 This should be done the first time an element is referenced. 这应该在第一次引用元素时完成。 It tells android to generate a value for it in R.java. 它告诉android在R.java中为其生成一个值。 Errors like this in your XML can cause your R.java file to not be generated and lead to different problems but I think the extra pluses on the ids are forgivable. XML中的此类错误可能会导致无法生成R.java文件,并导致其他问题,但是我认为ID上的多余内容是可以原谅的。

I was getting the error because of how you defined the id for layout. 由于您如何定义布局的ID,因此出现错误。 Instead it should look more like this 相反,它应该看起来像这样

android:id="@+id/android:list"

Notice the + to create a new id and because I am using ListActivity I also must define it as android:list instead of just list. 注意+来创建一个新的ID,因为我使用的是ListActivity,所以我还必须将其定义为android:list而不是list。 I changed your XML to this: 我将您的XML更改为此:

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/save_filename"
    android:layout_alignRight="@+id/linearLayout"
    android:hint="save here"
    android:layout_alignEnd="@id/linearLayout"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="5dp" />

<ListView
    android:id="@+id/android:list"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:layout_above="@id/linearLayout"
    android:layout_below="@id/save_filename">
</ListView>

Here is some corrected code, I noted what I changed. 这是一些更正的代码,我记下了更改。

package com.example.sosandbox;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;


public class Save extends ListActivity {
String FileName;
EditText et;
//Added some test values
String listItem[]={"1","2","3","4","5"};
ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.activity_save);
    Button save = (Button) findViewById(R.id.SAVE); //this is my button
//    This is unused so I commented it out
//    final EditText title = (EditText) findViewById(R.id.save_filename); //This is unused
    final EditText maintext = (EditText) findViewById(R.id.save_filename);
    getActionBar().setDisplayUseLogoEnabled(false);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    et = (EditText) findViewById(R.id.save_filename);
//    This is your issue. 
//    listView = (ListView) findViewById(R.id.list);
//    Change it to this because you are using a listActivity
    listView = getListView();//I've specified this listView only for the OnItemClickListener action

    List values = new ArrayList();
//    This won't run because you initilize listItem to an empty array or 0 so 0 < 0 evaluates to false and the loop doesn't run
    for (int i = 0; i < listItem.length; i++) {
        values.add(listItem[i]);
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);

    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                FileName = et.getText().toString() + ".txt";
                FileOutputStream fout = openFileOutput(FileName, Context.MODE_PRIVATE);
                OutputStreamWriter outsw = new OutputStreamWriter(fout);
                try {
                    outsw.write(String.valueOf(maintext));
                    outsw.flush();
                    outsw.close();
                    Toast.makeText(getBaseContext(), "Your file has been saved", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
            String device;
            switch (view.getId()) {
                case R.id.SAVE:
                    List myList = new ArrayList();
                    device = et.getText().toString();
                    myList.add(device);
                    adapter.add(device);
                    et.setText("");
                    break;
            }
            adapter.notifyDataSetChanged();
        }
    });

    //I think this is wrong, I get no error in Java by the way. How could this work if there's a specific extension for my activity that define the listview? **That's my question**. 
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // ListView Clicked item index
            int itemPosition     = position;

            // ListView Clicked item value
            String  itemValue    = (String) listView.getItemAtPosition(position);

            // Show Alert
            Toast.makeText(getApplicationContext(),
                    "Position :"+itemPosition+"  ListItem : " +itemValue , Toast.LENGTH_LONG)
                    .show();
        }
    });

}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM