JozeRi JozeRi - 1 month ago 7
Android Question

Android - how to get the layout id from a view?

Hello fellow developers!

i'll keep this as simple and short as I can,
I have a fragment, and in my onCreateView I am sometimes giving it different layouts depend on my status.

is there any way of knowing on which layout I am?

code below:

my onCreateView:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View view;

if (programState) {
view = inflater.inflate(R.layout.fragment_home_program_on, container, false);
} else {
view = inflater.inflate(R.layout.fragment_home, container, false);
}

findViews(view);
setupViews();
return view;
}


basically, my "findViews" method gets that View, and I was wondering if there's a way to know which layout i am on with a switch statement for example or something like that.. like this :

private void findViews(View mainView) {

switch(mainView) {
case R.layout.fragment_home:
//do work
break;
case R.layout.fragment_home_program_on:
//do work
break;
}
}


I am trying to do something like that with no success.. all i get is errors and such, is there a way to do that?

thanks a lot in advance

Answer

is there any way of knowing on which layout I am?

Sure. Check programState. You are already doing that to determine which layout to load, so use that to determine which layout you loaded.

I was wondering if there's a way to know which layout i am

Use if (programState), the same way you did in onCreateView().

Beyond that, a widget has no idea what layout resource it came from. So, somewhere, you need to track that information yourself, and you seem to be doing so already in programState.