Pregunta

I want to start an explicit intent , Here is the code

public class TabView extends ListActivity {
    List<String> list1strings = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.tview);
        ListView listview1 = (ListView) findViewById(R.id.list1);
        TabHost th = (TabHost) findViewById(android.R.id.tabhost);
        th.setup();

        list1strings.add("Programming Language");
        list1strings.add("Database");
        list1strings.add("Java Technologies");
        list1strings.add("Web Technologies");
        list1strings.add("Application/Web Server");
        list1strings.add("operating Systems");
        list1strings.add("PHP framework");
        list1strings.add("PHP CMS");
        listview1.setAdapter(new ArrayAdapter<String>(TabView.this,
                android.R.layout.simple_list_item_1, list1strings));

        th.addTab(th.newTabSpec("Tab1").setIndicator("Training")
                .setContent(R.id.tab1));

        TabSpec specs = th.newTabSpec("Tab2");
        specs.setContent(R.id.tab2);
        specs.setIndicator("Workshops");
        th.addTab(specs);

        specs = th.newTabSpec("Tab 3");
        specs.setContent(R.id.tab3);
        specs.setIndicator("Reach Us");
        th.addTab(specs);

    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);

        String getpos = list1strings.get(position);
        try {
            Class<?> ourclass = Class.forName("in.brainwave.industrialtraining." + getpos);
            Intent ourIntent = new Intent(TabView.this, ourclass);
            startActivity(ourIntent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

}

"list1string" here have data and I want to start an intent when an item on ListView is clicked , but the problem is that class name cannot have space and "String getpos = list1strings.get(position);" returns the string from ArrayList which contains space , Is there any way so that I can start an Intent when any item is clicked. Please guide me .

¿Fue útil?

Solución

You can just initialize a second array/list with the classes of each item, so when you select item N you get the class at the same position. For example:

ArrayList<String> listItems = new ArrayList<String>();
ArrayList<Class> classes = new ArrayList<Class>();

listItems.add("Programming");
classes.add(YourProgrammingActivity.class);
// (...)
listItems.add("PHP CMS");
classes.add(YourPHPCMSActivity.class);

And then to start the right activity in the listener:

Class activityToStart = classes.get(position);
Intent ourIntent = new Intent(TabView.this, activityToStart);
startActivity(ourIntent);

As you can guess, each class you put in that list should be an activity (and be declared in AndroidManifest), otherwise your app will crash.

Also if this is a fixed list, replacing ArrayList with arrays is much less verbose:

String[SIZE] listItems = {"Programming", /* (...) */, "PHP CMS"};
Class[SIZE] classes = {YourProgrammingActivity.class, /* (...) */, YourPHPCMSActivity.class };

(...)
Class activityToStart = classes[position];

Otros consejos

From an Object Oriented Perspective you can encapsulate this information in one class and do a for loop to do it in an automatic manner. Let me show you (and remember there are multiple possible options, in doing this).

Keep in mind that this is more or less pseudocode that looks exactly to Java but I programed from memory, so there could be errors and typos!

First of all let met tell you that there are some things that are done in a "bad" way. For example this piece of code will never work:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    String getpos = list1strings.get(position);
    try {
        Class<?> ourclass = Class.forName("in.brainwave.industrialtraining." + getpos);
        Intent ourIntent = new Intent(TabView.this, ourclass);
        startActivity(ourIntent);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

}

Because you are storing Strings which are titles! Not even Java class names. The best way is to create a class that encapsulate the information you need. This class keeps all information you need to provide to the different components.

public class TabEntry {
    // In here you save the real class to be invoked in the listener
    private Class mEntryClass;

    // You store the title of the tab
    private String mTabTitle;

    // In here you store the content tab id like R.id.tab3
    private int mContentId;

    // Add more fields as necessary
    ...

    public TabEntry(Class clazz, String tabTitle, int contentId) {
        this.mClass = clazz;
        this.mTabTitle = tabTitle;
    }

    public Class getEntryClass() {
        return this.mEntryClass;
    }

    public String getTabTitle() {
        return this.mTabTitle;
    }

    // Add more getters as needed

}

So right now, you have created a class that encapsulates the information you need to create your tabs. Now in the code of the TabActivity:

public class TabView extends ListActivity {
List<TabEntry> mListTabEntries = new ArrayList<TabEntry>();

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

    setContentView(R.layout.tview);
    ListView listview1 = (ListView) findViewById(R.id.list1);
    TabHost th = (TabHost) findViewById(android.R.id.tabhost);
    th.setup();

    // Initalize your list with your tabs entries, this should be done outside this method
    // to don't clutter your code
    mListTabEntries.add(new TabEntry(Activity1.class, "Title", R.id.text1));
    mListTabEntries.add(new TabEntry(Activity2.class, "Title2", R.id.text2));

    listview1.setAdapter(new ArrayAdapter<String>(TabView.this,
            android.R.layout.simple_list_item_1, getTabsStrings(mListTabEntries)));

    // Create a for loop to iterate each entry in your list, so you dont have to do it
    // manually
    for (TabEntry entry : mListTabEntries) {
        th.addTab(th.newTabSpec(entry.getTabTitle())
          .setIndicator(entry.getIndictor())
          .setContent(entry.getContent());
    }

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);

    TabEntry entry = list1strings.get(position);
    Intent ourIntent = new Intent(TabView.this, entry.getTabClass());
    startActivity(ourIntent);

}

private String[] getTabsStrings(List<TabEntry> mEntries) {
    String[] titlesString = new String[mEntries.size()];
    for(int i = 0; i < mEntries.length(); i++) {
      titlesString[i] = mEntries.get(i);
    }
    return titlesString;
}

}

At this point this code should work (but IMHO it not the prettiest one). So we can do better (if you want learn more about code, you can read Clean Code or Effective Java, both books are great to improve your skills with programming).

If you want to learn more about how we can make this code more pretty and succinct let me know! :)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top