Somk
Somk

Reputation: 12057

Android Find out what view is present

I have an activity that when created contains an EditText but if you click a button it is replaced with a custom view called a MinPick. I need another class to get the view via findViewById(). But of course I need to define what the variable getting the id should be. Either EditText or MinPick. How do I do some sort of conditional if it is not an EditText it must be a MinPick.

Upvotes: 0

Views: 77

Answers (2)

rekaszeru
rekaszeru

Reputation: 19220

You can check the returned object's class using instanceof:

final View v = findViewById(R.id.floating_component);
if (v instanceof EditText)
    // do stuff with the EditText instance;
else if (v instanceof MinPick)
    // do stuff with the MinPick instance;

On the other hand, @Sergey Glotov is right, it's a lot nicer technique to deal with states and based on them show the appropriate view.

Upvotes: 1

Jeje Doudou
Jeje Doudou

Reputation: 1706

You can use "instanceof":

final View tempView = findViewById(R.id.XXXxxxxXXX);

if (tempView instanceof EditText)
{
// TODO Do some stuff
}
else
{
// TODO Do some other stuff
}

Upvotes: 0

Related Questions