点击不同的元素时,我一直在努力让listView将用户onClick重定向到网址。 例: 点击" apple"会打开" stackoverflow.com", 但点击番茄会打开" google.com"等等 任何人都可以给我一些建议我怎样才能做到这一点,因为经过2天的尝试和搜索后,所有我都很头疼......
displayMainMenu.java
public class DisplayMainMenu extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_main_menu);
final String[] food = new String[] {"Apple", "Tomato", "Potato"};
ListAdapter adapter = new MyAdapter(this, food);
ListView listView = (ListView) findViewById(R.id.mainMenu);
listView.setAdapter(adapter);
}
class MyAdapter extends ArrayAdapter<String>
{
public MyAdapter(Context context, String[] values)
{
super(context, R.layout.entry, values);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.entry, parent, false);
String text = getItem(position);
TextView textView = (TextView) view.findViewById(R.id.listTextView1);
textView.setText(text);
return view;
}
}
}
答案 0 :(得分:0)
您应该创建一个包含所显示的字符串值(Apple,Tomato,Potato等)的新类,并保存您要链接到的URL。
然后使ArrayAdapter使用该类。您已经足够的getView函数(当它更新为使用新类时)。
然后在你的活动中,使用'setOnItemClickListener'来设置一个新的监听器。
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyItem clickedItem = () parent.getItemAtPosition(position);
<< Insert code to open the link with the URL you can get from 'clickedItem' >>
}
});
应该这样做。