Snarky
Snarky

Reputation: 11

Android/java - need to find the ID of the current layout - how?

I'm creating an app for the Android OS, and I'm running into a bit of a stumbling block on one issue. Here's what I want to do:

I'm currently capturing the "Back" button event just fine, but I need it to behave slightly differently, depending on the current layout the user is viewing. I have four layouts that I'm using, and if the user is on layout 1, 2, or 3, I want "Back" to take them to layout 1; but if they are on layout 4, I want them to go back to layout 3 instead.

The problem is, I can't for the life of me figure out the code that will return the id of the CURRENT layout. I'm sure this is a pretty simple problem, so I'm hoping someone will have a quick solution.


Thanks for the pointers - for some reason I'm having trouble getting getCurrentFocus() to work, though...probably due to my own ineptitude in programming Java.

I've broken it down into the following:

View thisView = getCurrentFocus();
if (thisView != null){
int viewID = thisView.getId();
toastLong(Integer.toString(viewID));
} else {
toastLong("thisView is null.");
}

The problem now is that thisView is always null - it's not returning any values. I tried putting in the activity name that I'm using in place of myActivity (making it:

View thisView = myActivityName.getCurrentFocus();

but the IDE gives me the following error and won't compile:

Cannot make a static reference to the non-static method getCurrentFocus from the type Activity.

I'm obviously missing something, and my assumption is that it's a very basic something that I'm missing. Any pointers?

Upvotes: 1

Views: 5802

Answers (2)

Olivier Van Bulck
Olivier Van Bulck

Reputation: 786

I had this problem too and found a very simple solution. Though this is an old question, I'll post it here for people who are searching for help for this problem.

Just create an integer as attribute in your class:

int layoutId;

Then override the setContentView method and save the ID from the parameter:

@Override
public void setContentView(int layoutResID) {
    this.layoutId = layoutResID;
    super.setContentView(layoutResID);
}

Very simple trick!

Upvotes: 4

Asahi
Asahi

Reputation: 13486

You can use ViewFlipper to hold your layouts and implement a simple state machine to control transitions. another option might be creating a separate Activity for every one of your layouts - hard to tell without exact knowledge about what your app is doing.

Upvotes: 0

Related Questions