1

我已經成功從我的服務器獲取數據並將其顯示在ListView中,現在我想在ListView Items中實現Click事件。現在我在列表視圖中顯示「id」和「SomeText」。實現OnClickListener到ListView項目

我的問題是如何在ListView中實現一個Click事件,這樣,如果我點擊一個特定的行,它將顯示來自服務器的「id」(而不是從實際的數組開始「0」 )在吐司消息中。

下面是代碼和屏幕截圖,我正在點擊列表項時獲得什麼。

我希望有人能幫助我解決這個問題;任何鏈接或代碼片段都會非常有幫助。

非常感謝你。 恭

SCREENSHOT enter image description here

CODE 公共類歡迎延伸活動{

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

ListView lvList; 
private ArrayAdapter<String>mListData; 
String emailAdd = "[email protected]"; 

@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(); 
} 
+2

上面的代碼將只給你的當前索引可見的數據,我會建議使用一個自定義的基礎適配器與onclick爲每個視圖/行,您設置爲標記或單獨的'textview'的id。 –

回答

1

我要說的主要原因,你不能得到其他的信息不是字符串名稱是因爲沒有其他的信息比在適配器列表中的字符串名稱。所以你需要有一個合適的數據模型和對應於這個模型的適配器。使用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)); 
+0

謝謝@inmyth ..現在它的工作雖然必須作出很多改變......反正,重要的主要事情是一個想法,我感謝你爲...和答案接受:) – Christine

1

你應該實現一個定製的基本適配器See where how。將每個元素(id和name)綁定到列表視圖行,而不是簡單的ArrayAdapter

我也建議來包裝從你的服務器中的Java對象的響應:

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

    // getters and setters 
} 

的那麼當你onItemClick方法被調用時,你將有AgentTask,而不是一個簡單的字符串實例。

希望它可以幫助

+0

謝謝letz給你快速回復^^ ..我會研究它 – Christine

相關問題