0

我已经在我正在制作的一个小应用程序中为菜单创建了一个基本列表,但我正在努力创建当用户单击列表中的项目时将触发事件的方法。

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 但我希望它开始新的活动或片段

4

3 回答 3

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);

        }
    });
于 2013-04-08T19:10:40.640 回答
0

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

startActivty(new Intent(YourCurrentActivity.this, YourNewActivity.class));
于 2013-04-08T19:10:10.710 回答
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);

        }
});
于 2013-04-08T19:12:33.137 回答