【问题标题】:How to call different intents from each listview item in android如何从android中的每个listview项目调用不同的意图
【发布时间】:2012-09-24 05:12:36
【问题描述】:
我的列表视图中有超过 10 行,我正在使用 JSON 从 Web URL 获取记录,但现在我想为每一行调用特定的意图,例如:-对于第一行,我想调用 (this),对于第二行,(http://domainname.com/s/b) 等等,
所以请建议我需要在我的 ListActivity 类中添加哪些代码以及在哪里调用......
public class MainActivity extends Activity {
ListView mListView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// URL to the JSON data
String strUrl = "http://domainname.in/first.php/count/";
// Creating a new non-ui thread task to download json data
DownloadTask downloadTask = new DownloadTask();
// Starting the download process
downloadTask.execute(strUrl);
// Getting a reference to ListView of activity_main
mListView = (ListView) findViewById(R.id.lv_count);
}
【问题讨论】:
标签:
android
android-intent
android-emulator
【解决方案1】:
您可以通过编写自己的自定义适配器来实现此目的。如下:
class CustomAdapter extends ArrayAdapter {
HashMap<String, String> map;
ArrayList mList;
public CustomAdapter(Context context, int resource,
int textViewResourceId, HashMap<String, String> map) {
super(context, resource, textViewResourceId);
this.map = map;
mList = new ArrayList<String>(map.keySet());
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int position) {
return mList.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// do your stuff with layouts.
String item = (String)mList.get(position);
// either you can set the url as tag to view so that the same url will be
//retrieved when an item is clicked or declare the map as global variable.
String url = map.get(item);
convertView.setTag(url);
return convertView;
}
}
/// 在你的活动中
@Override
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
// you can get the url from the tag
String url = view.getTag().toString();
// or else declare the HashMap as global variable which will be accessible through out the class.
String url = new ArrayList<String>(map.keySet()).get(position);
// Now launch web with this url
}
【解决方案2】:
您需要将ListView数据与为每个项目指定的URL附加在一起,您可以处理ListView的onItemClick()从选定项目的基础上获取ListView项目获取URL并在WebView中打开链接。