JonniBravo
JonniBravo

Reputation: 1071

How can I create an activities in a list view

I have created a list view within a tab with a list of teams within it. I want to create a activity which when clicked goes to another class, I want to do this with 20 items that will be in this list. My code so far is:

public class ll2 extends ListActivity {

    static final String[] teams = new String[]{"Accrington Stanley",
            "Aldershot", "Barnet", "Bradford City", "Burton Albion",
            "Bury", "Cheltenham Town", "Chesterfield", "Crewe Alexandra"};

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

        final String[] TEAMS = getResources().getStringArray(R.array.twoteams_array);
        setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, TEAMS));


        ListView lv = getListView();
        lv.setTextFilterEnabled(true);

        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // When clicked, show a toast with the TextView text
                Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
                        Toast.LENGTH_SHORT).show();


                Intent intent;

                intent = new Intent().setClass(this, Bradford.class);


            }
        });
    }

}

I have read some tutorials, but they do not mention how to maka a clickable listview.

How can I achieve this?

Upvotes: 0

Views: 171

Answers (2)

RaiVikrant
RaiVikrant

Reputation: 539

listView = (ListView) findViewById(R.id.listView1);

listView.setAdapter(adapter);

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(getApplicationContext(), AnotherActivity.class);
        intent.putExtra("ID", ""+id);
        startActivity(intent);
        finish();
    }
});

Upvotes: 0

Brian
Brian

Reputation: 16206

You'll probably want to override the onListItemClick method in your ListActivity. Based on the position, you will construct an appropriate intent.

@Override
public void onListItemClick(ListView parent, View v, int position, long id) {
    if (position == appropriate_condition) {
        Intent intent = new Intent(this, Bradford.class);
        startActivity(intent);
    }
}

If you need to access data associated with the item, the documentation provides this suggestion:

Subclasses can call getListView().getItemAtPosition(position) if they need to access the data associated with the selected item.

Upvotes: 1

Related Questions