开发者

Start an activity from a listview [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Start an activity from a listview

I have 24 teams in a list, I have 24 separate .java classes for each team with information about those teams. When the user click on an item(Team) in the list I want to goto that teams java file(Class) and display there information. below is the code,

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ll2 extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String[] myList = new String[] {"Accrington Stanley", "Aldershot Town", "Barnet", "Bradford City", "Burton Albion", "Bury", "Cheltenham Town", "Chesterfield", "Crewe A", "Gillingham", "Hereford Utd", "Lincoln City", "Macclesfield T", "Morecombe", "Nor开发者_如何学Cthampton T", "Oxford Utd", "Port Vale", "Rotherham Utd", "Shrewsbury T", "Southend Utd", "Stevenage", "Stockport C", "Torquay Utd", "Wycombe W"};              
        ListView lv = new ListView(this);
        lv.setAdapter(new ArrayAdapter(this,android.R.layout.simple_list_item_1,myList));
        setContentView(lv);
    }

    public void onItemClick(AdapterView parent, View view,int position, long id) {
       Intent myList = new Intent();
        myList.setClass(this, Bradford.class);

        if ("Bradford City".equals(myList))
            startActivity(Bradford.java);
    }
}

As you can see I have setup the Bradford class and I have registered this in android manifest but when I click on bradford nothing happens, also when I try to set up another intent for another team the mylist value cannot be used again.

How do I make this work


You are trying to compare an intent with a String, but you need to compare the String that comes from the Listview. Try it this way:

public void onItemClick(AdapterView parent, View view,int position, long id) {
     if(((TextView)view).getText().equals("Bradford City"))
     {
        startActivity(new Intent(getApplicationContext(), Bradford.class));
     }
}

Although this might work, doing it to 24 classes it's very inefficient. Maybe you could try make a Switch/Case using the "position" parameter, or even add an attribute to each of your team classes that would then allow you to make an array of Teams and call the correct class on the Intent (I'm sorry if this sound confusing, it's a little bit hard to explain).

Hope it helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜