我正在开发 Android 应用程序。在我的项目中,我需要创建 Listview。我的布局即 info.xml 包含带有一个 ImageView 的顶栏,带有其他 ImageView 的页脚。同样在布局的中心,我保留了一个 ImageView ,并在其上创建了 ListView 。我还为 TextView 创建了 row.xml 以显示列表项。现在,当我点击每个列表项时,应该调用一个新的 Intent ......即当我点击第一个列表项时,page1 应该打开。同样,如果我点击第二个列表项 page2 应该打开等等。那我怎么能那样呢。自 3 天以来,我一直在为此苦苦挣扎,但没有找到任何正确的解决方案。请帮助我解决这个问题。
我的代码:
public class Information extends Activity
{
private String[] Countries;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
Countries = getResources().getStringArray(R.array.countries);
ListView list = (ListView)findViewById(R.id.listnew);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.row, Countries);
list.setAdapter(adapter);
registerForContextMenu(list); }
}
最佳答案
所有你需要添加的是
list.setOnItemClickListener(this);
然后让您的类实现 OnItemClickListener 接口(interface)并创建此方法:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
Intent firstIntent = new Intent(this, MyClass.class);
startActivity(firstIntentIntent);
break;
case 1:
Intent secondIntent = new Intent(this, MySecondClass.class);
startActivity(secondIntentIntent);
break;
[... etc ...]
}
}
在这种情况下,如果第一个项目被点击,它将启动 MyClass Activity,如果第二个项目被点击,MySecondClass Activity 将被启动,等等。
是的,这有点乏味,但这是最好的方法。
关于android - 如何从android中的每个 ListView 项调用不同的 Intent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7931365/