Rhyno_H
Rhyno_H

Reputation: 49

select item in a listview

I have created a basic list for a menu in a little app im making but im struggling to create the method that will trigger the events when a user clicks on an item in the list.

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

for now its just displaying a Toast but I want it to start new activities or fragments

Upvotes: 0

Views: 236

Answers (3)

Kaidul
Kaidul

Reputation: 15875

This is very easy :

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

        }
});

Upvotes: 0

Paresh Mayani
Paresh Mayani

Reputation: 128428

Try:

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

        }
    });

Upvotes: 1

Jose L Ugia
Jose L Ugia

Reputation: 6250

So what is your question? To start an activity just use an Intent.

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

Upvotes: 0

Related Questions