如何显示不同ListView项目的不同活动?

时间:2017-03-11 10:10:23

标签: android listview

我有一个ListView包含多个项目,每个项目都有自己的Activity类来显示详细信息。当用户选择此ListView中的项目时,如何切换到相应的活动?

我目前的代码如下:

 ListView listView;
 ArrayAdapter<String> adapter;

 String[] hotel = {"one room", "double room", "suit", "vip"};

 @Override
 protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   setContentView(R.layout.activity_main);

   listView = (ListView) findViewById(R.id.listView);  
   adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hotel);

   listView.setAdapter(adapter);
}

1 个答案:

答案 0 :(得分:1)

将setOnItemClickListener添加到listView.setAdapter(adapter);下的onCreate中的listView:

 listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                if(position == 0){
                    Intent intent = new Intent(MainActivity.this, OneRoomActivity.class);
                    startActivity(intent);
                }

               else if(position == 1){
                    Intent intent = new Intent(MainActivity.this, DoubleRoomActivity.class);
                    startActivity(intent);
                }

               //Do as above for rest of the list items
            }
        });

希望这有帮助。