我正在使用ArrayAdapter在列表中显示我的朋友。但是,每一行都有两个按钮,可通过POST请求更新朋友的状态。
我在适配器中定义了两个按钮的click侦听器,以及用于处理更新请求的runnable。一个例子:
mToggleAlert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mToggleAlert = (ToggleButton)finalRowView.findViewById(R.id.toggleAlert);
mToggleShow = (ToggleButton)finalRowView.findViewById(R.id.toggleShow);
updateStatus(finalRowView.getId(), mToggleAlert.isChecked(), mToggleShow.isChecked());
}
});
/**
* Send the updated status to the server
*/
private void updateStatus(int id, boolean alert, boolean show) {
final int finalId = id;
final boolean finalAlert = alert;
final boolean finalShow = show;
String.valueOf(mToggleAlert);
Runnable runnable = new Runnable() {
public void run() {
Message msg = handler.obtainMessage();
Bundle bundle = new Bundle();
//Post the update to the server
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.postFriendStatusUrl);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user_id",Common.retrieveAppUser(mContext).getId()));
nameValuePairs.add(new BasicNameValuePair("friend_id", String.valueOf(finalId)));
nameValuePairs.add(new BasicNameValuePair("alert_status", String.valueOf(finalAlert)));
nameValuePairs.add(new BasicNameValuePair("show_status", String.valueOf(finalShow)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
bundle.putString("result", sb.toString());
msg.setData(bundle);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
handler.sendMessage(msg);
}
};
Thread mythread = new Thread(runnable);
mythread.start();
}
我认为这不是一个很好的方法,所以我将更新服务放入它自己的AsyncTask中。
我的问题是:我宁愿为实现ArrayAdapter的Activity中的两个按钮定义单击侦听器,而不是在适配器本身中。我该怎么做?
答案 0 :(得分:0)
mToggleAlert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mToggleAlert = (ToggleButton)finalRowView.findViewById(R.id.toggleAlert);
mToggleShow = (ToggleButton)finalRowView.findViewById(R.id.toggleShow);
updateStatus(finalRowView.getId(), mToggleAlert.isChecked(), mToggleShow.isChecked());
}
});
您是否仅将侦听器设置为mToggleAlert ans而不是mToggleShow是正常的吗?
无论如何,你可以从ArrayAdapter中的按钮中输入getter
public ToogleButton getToggleAlert(){
return mToggleAlert;
}
然后您就可以从主要活动
设置监听器您可能只需要设置&#34; updateStatus&#34;公众从您的活动中调用它