android - 对 ListView 项目实现 OnClickListener

标签 android mysql listview android-arrayadapter onclicklistener

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

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

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

我希望有人能帮我解决这个问题;任何链接或代码 fragment 都会非常有帮助。

非常感谢。 克里斯汀

屏幕截图 enter image description here

代码 公共(public)课欢迎扩展 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();
}

最佳答案

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

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));

关于android - 对 ListView 项目实现 OnClickListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30180030/

相关文章:

android - 使用钛在 Android 中显示底部选项卡

android - 如何在android/eclipse中使按钮的颜色像玻璃的颜色

listview - 如何在 Listview 上使用 ScrollTo 方法

c# - Windows 窗体 ListView 最小列宽

android - 哪些选项可用于使用Adobe AIR在Android上处理文本输入?

javascript - 如何自动生成android应用程序?

php - mysql(查询) 或 php switch 语句哪个更快?

php - 2 不是有效的 MySQL-Link 资源。怎么修?相同的脚本在另一台服务器上工作(不是配音,因为它在其他服务器上工作)

php - 使用 PHP 和 MySQL 的 jQuery 倒计时

android - DialogFragment 中带有 LinearLayouts 的 ListView 不包装内容