在列表视图中选择项目

时间:2013-04-08 19:08:06

标签: java android

我已经在一个小应用程序中创建了一个菜单的基本列表,但我很难创建在用户点击列表中的项目时触发事件的方法。

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);
    final ListView lv = (ListView) findViewById(R.id.listview);
    String[] values = new String[] {
      "Home", "Profile", "Messenger", "Discussion", "Browse Library", "Grades", "Help"
    };
    final ArrayList<String> list = new ArrayList<String>();
    for (int i = 0; i < values.length; ++i) {
      list.add(values[i]);
    }
    final StableArrayAdapter adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, list);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Context context = getApplicationContext();
        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_SHORT;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
      }
    });
  }
}

现在它只显示一个Toast但我想让它开始新的活动或片段

3 个答案:

答案 0 :(得分:1)

尝试:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View v, int arg2,
                long arg3) {
          Intent intent = new Intent(MainActivity.this, ActivityB.class);
          startActivity(intent);

        }
    });

答案 1 :(得分:0)

那你的问题是什么? 要开始活动,只需使用Intent。

startActivty(new Intent(YourCurrentActivity.this, YourNewActivity.class));

答案 2 :(得分:0)

这很容易:

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg1, View v, int arg2,
                long arg3) {
          Intent intent = new Intent(MainActivity.this, anotherActivity.class);
          startActivity(intent);

        }
});