我使我的代码更简单,当我点击列表视图中的项目时它仍无法为我工作
public class MainActivity extends Activity {
String[] elements = {"item1", "item2"};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
ListView listview = (ListView)findViewById(R.id.listView1);
listview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, elements));
}
public void onListItemClick(ListView parent, View v, int position, long id) {
if ("item1".equals(elements[position]))
{
Toast.makeText(getApplicationContext(), "item1",
Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(MainActivity.this, myactivity.class);
startActivity(myIntent);
}
else if ("item2".equals(elements[position]))
{
Toast.makeText(getApplicationContext(), "item2",
Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(MainActivity.this, myactivity.class);
startActivity(myIntent);
}
}
}
我可以知道实现目标的正确方法是什么?
答案 0 :(得分:0)
你必须在setAdapter('');
之后调用它mainListView.setOnItemClickListener(new OnItemClickListener{
OnClick(item){
// You have to call Intent(main,second) or call another fragment directly.
}
}
答案 1 :(得分:-1)
首先告诉我,当用户点击任何一行然后他将重定向到新活动时,要求这样的功能吗?
是的,那么您可以使用以下代码行:
yourlistviewobject.setOnItemClickListener(new onItemClickListener(){
@Override
protected void onListItemClick(){
//Do stuff
Intent intent=new Intent(this,otherclass);
startActivity(intent);
}
});
希望它会对你有所帮助。