开发者

Calling an Intent dynamically on several buttons

I currently have an application that look like a book: several pages, and 2 buttons at the bottom linking to next page and previous page.

What I am currently doing is something like that, on each o开发者_运维技巧ne of my XML layout, i add two buttons whith onClick property.

For instance on page 5, I have on my previous button:

android:onClick="Page4"

and next button

android:onClick="Page6"

I also wrote a CustomActivity with these properties:

public void Page4(View v) {
    startActivity(new Intent(this, Page04.class));
    finish();
}
public void Page6(View v) {
    startActivity(new Intent(this, Page06.class));
    finish();
} 

This work fine and I wrote a whole application like this, but I really would like to make something more clever.

As you can imagine, when I have something like 100 pages, my code is quite horrible!

I don't know, something like "PreviousPage" or "NextPage"

public void PreviousPage(View v) {
    Intent i= "Generate dynamically an intent for previous page"
    startActivity(i);
    finish();
} 

WHat I was thinking was also giving a parameter in my xml and do something like:

public void GotoPage(View v, int page) {
    startActivity(new Intent(this, Page"+page+".class));
    finish();
} 

I hope you understand what I mean and what I am looking for.


Create a java.util.List or java.Util.Map containing your Activities.

List activities = new ArrayList();
activities.add(Activity1.class);
activities.add(Activity2.class);
activities.add(Activity3.class);

Start your activity by calling

startActivity(new Intent(this,activities.get(i));

If you need to be able to seach by key, you can do the same with a map,

Map activities = new HashMap();
activities.add("activity1",Activity1.class);
activities.add("activity2",Activity2.class);
activities.add("activity3",Activity3.class);

Start your activity by calling

startActivity(new Intent(this,activities.get("activity1"));

By storing it in a List/Map, it should be fairly easy to implement first,previous,next,last functionality.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜