对 ListView 项目实施 OnClickListener

Implement OnClickListener to the ListView Items

我已成功从我的服务器获取数据并将其显示在我的 ListView 中,现在我想在 ListView 项目中实现 Click 事件。现在我在列表视图中显示 "id" 和 "SomeText"。

我的问题是如何在 ListView 中实现 Click 事件,如果我单击一个特定的行,它将显示来自服务器的 "id"(而不是来自从"0") 在 toast 消息中。

下面是单击列表项时我得到的代码和屏幕截图。

我希望有人能帮我解决这个问题;任何 link 或一段代码都会很有帮助。

非常感谢。 克里斯汀

屏幕截图

代码 public class 欢迎扩展 Activity {

public static String token;
String nam;
String dat;
String name;
JSONArray tasks;
long id2;
TextView textView;

ListView lvList;
private ArrayAdapter<String>mListData;
String emailAdd = "rohan@bbtdigital.com";

@SuppressLint("NewApi") @Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.welcome);
    //======================================================================================================
    //======================== GETTING THE VALUE FROM THE SHARED PREF ======================================

    SharedPreferences sharedpreferences = getSharedPreferences(Login.MyPREFERENCES, Context.MODE_PRIVATE);
    token = sharedpreferences.getString("tokenKey","");
    //Log.e("TOKEN", token);

    //======================================================================================================
    //=====================================================================================================
    lvList = (ListView) findViewById(R.id.chat_drawer);
    textView = (TextView) findViewById(R.layout.msg_chat);

    mListData = new ArrayAdapter<String>(this, R.layout.msg_chat);
    lvList.setAdapter(mListData);
    mListData.setNotifyOnChange(true);

    historyMessage();
}

private void historyMessage() {
    // TODO Auto-generated method stub

    new Thread(new Runnable(){

        @Override
        public void run() {
            // TODO Auto-generated method stub
            try{
                HttpClient client = new DefaultHttpClient();
                String SetServerString = "";
                HttpGet httpget = new HttpGet("http://xxxx.xxx.com/api/v1/agent-tasks?token="+token);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                SetServerString = client.execute(httpget, responseHandler);
                //Log.e("LIST vIEW ", SetServerString);
                HttpResponse mike = client.execute(httpget);
                HttpEntity entit = mike.getEntity();
                dat = EntityUtils.toString(entit);
                //Log.e("STRING From ", dat);

                try{
                    JSONObject responseObject = new JSONObject(SetServerString);
                    JSONArray responseArray = responseObject.getJSONArray("response");
                    JSONObject firstResponse = responseArray.getJSONObject(0);
                    tasks = firstResponse.getJSONArray("tasks");
                    //System.out.println("asdfasdfsadf" + tasks);

                        runOnUiThread(new Runnable(){

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                for(int i = 0; i < tasks.length(); i++){
                                    try{
                                    JSONObject task = tasks.getJSONObject(i);

                                    id2 = task.getInt("id");
                                    name = task.getString("name");
                                    String fulldata = id2 + "." + " " + name;

                                mListData.add(fulldata);


                                //mListData.notifyDataSetChanged();
                                ListView lvList = (ListView) findViewById(R.id.chat_drawer);
                                lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {


                                    public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
                                            long id2) {
                                        // TODO Auto-generated method stub

                                        TextView textView = (TextView) viewClicked;
                                        String message = "you clicked #"+id2+" "+ ",which is string:"+ " " +textView.getText().toString();
                                        Toast.makeText(Welcome.this, message, Toast.LENGTH_LONG).show();

                                    }


                                });
                                    }
                                    catch (JSONException e){
                                        e.printStackTrace();
                                    }
                            }
                            }


                        });
                } catch (JSONException e){
                    e.printStackTrace();
                }
            }catch (ClientProtocolException e){
                Log.d("HTTPCLIENT", e.getLocalizedMessage());
            } catch (IOException e) {
                Log.d("HTTPCLIENT", e.getLocalizedMessage());
            }


        }

    }).start();
}

您应该实现一个自定义基础适配器 See where how。将每个元素(id 和名称)绑定到列表视图行,而不是简单的 ArrayAdapter.

我还建议将服务器的响应包装在 java 对象中:

public class AgentTask {
    private int id;
    private String name;

  // getters and setters
}

然后当您的 onItemClick 方法被调用时,您将拥有 AgentTask 的实例而不是简单的字符串。

希望对您有所帮助

我想说除了字符串名称之外您无法获得其他信息的主要原因是因为适配器列表中除了字符串名称之外没有其他信息。因此,您需要有一个合适的数据模型和与该模型对应的适配器。使用 ArrayAdapter 是完全没问题的。该片段将如下所示:

class Data {
  String name;
  int id;

  public Data(String name, int id){
      this.name = name;
      this.id = id;
  }
}

class ViewHolder {
    TextView msg;

    public ViewHolder(View convertView){
       msg = (TextView)findViewById(R.id.msgid);//appropriate text view element
                                               // from R.layout.msg_chat
    }

}

class MyAdapter extends ArrayAdapter<Data>{
    public MyAdapter(Context context) {
        super(context, R.layout.msg_chat);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

      if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.msg_chat, parent, false);

        ViewHolder viewHolder = new ViewHolder(convertView);
        rowView.setTag(viewHolder);
      }

      ViewHolder holder = (ViewHolder) rowView.getTag();
      Data data = getItem(position);
      holder.msg.setText("The id is" + data.id);
      return convertView;           
    }  
}

实例化它:

 private MyAdapter mListData;
 ...
 mListData = new MyAdapter(this);

然后像这样将数据添加到适配器:

mListData.add(new Data(name, id2));