the*_*osh 6 android listadapter android-listview onclicklistener
我正在构建一个将请求发送到Web的应用程序,然后将结果解析并放入对象的ArrayList中.
然后,此列表填充ListView.我想创建一个onClickListener允许我知道单击了哪个对象的东西,但我找不到实现它的正确方法.
或者将onClick分配给原始活动中的ListView,或者getView在自定义适配器中的函数内分配侦听器.
在我看来,分配监听器getView有太多的开销.
它是如何工作的?什么是更好的?
主要活动的代码:
public class NoPicList extends Activity {
ListView list;
NoPicAdapter adapter;
ProgressDialog mDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.no_pic_list);
list = (ListView) findViewById(R.id.noPicListView);
Bundle b = getIntent().getExtras();
String request = b.getString("REQUEST");
mDialog = new ProgressDialog(this);
mDialog.setCancelable(false);
mDialog.setMessage("Lodaing Data");
mDialog.show();
new GetNewsAndCalendar().execute(request);
}
@Override
protected void onPause() {
mDialog.dismiss();
super.onPause();
}
class GetNewsAndCalendar extends
AsyncTask<String, Void, ArrayList<Message>> {
@Override
protected ArrayList<Message> doInBackground(String... params) {
String url = params[0];
DOMFeedParser parser = new DOMFeedParser(url);
return parser.parse();
}
@Override
protected void onPostExecute(ArrayList<Message> result) {
adapter = new NoPicAdapter(NoPicList.this, result);
list.setAdapter(adapter);
//FIRST OPTION TO INSERT onClickListener
mDialog.dismiss();
}
} //end of GetNewsAndCalendar
}
Run Code Online (Sandbox Code Playgroud)
列表适配器的代码:
public class NoPicAdapter extends BaseAdapter {
private ArrayList<Message> data;
private Activity mActivity;
private LayoutInflater inflater = null;
public NoPicAdapter(Activity a, ArrayList<Message> result) {
mActivity = a;
data = result;
inflater = (LayoutInflater) mActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = LayoutInflater.from(mActivity).inflate(R.layout.no_pic_list_item,
null);
TextView title = (TextView) vi.findViewById(R.id.noPicTitle);
TextView subtitle = (TextView) vi.findViewById(R.id.noPicSubtitle);
title.setText(data.get(position).getTitle());
subtitle.setText(data.get(position).getDate());
// SECOND PLACE TO INSERT THE onClickListener
return vi;
}
}
Run Code Online (Sandbox Code Playgroud)
根据我的担忧,将onClick 分配给原始活动中的 ListView是个好主意,而不是将其分配给getView()自定义适配器。因为在getView()你的适配器中它总是创建一个新的 View.onClick() 对象..
list.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
adapter.get(position);
// Get data from your adapter, the above code of line give the custom adapter's object of current position of selected list item
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6267 次 |
| 最近记录: |