Morpheu5
Morpheu5

Reputation: 2801

How do I pass information from an XML layout to its Activity class?

My Android app has two layouts, one for <= normal, and one for >= large. I can re-use my corresponding activity 99.9% in both cases, but I need it to know different bits of information for the two layouts. I could of course write a giant if expression, but I'd rather let Android work its magic, since it's already doing it by loading the two different layouts.

So, can I embed pieces of information in the two XML files and retrieve them in my activity class? Or am I completely off the map and the right approach is completely different?

Upvotes: 0

Views: 70

Answers (3)

Simon Featherstone
Simon Featherstone

Reputation: 1796

If you are using values to differentiate between the two layouts, then you can have different values that overload depending on screen size. See this answer.

You could do the same sort of thing with the layouts directory to create different layouts, but then use common subsections using the < include > tag to make the different views based on common sections.

Or a combination of the two. If you the want to change the behaivoir of the Activity/Fragment, you could key that on the presence of missing or present screen widgets.

Upvotes: 1

DeeV
DeeV

Reputation: 36035

If you're willing to go the custom View route, then yes, you can. What you have to do is create custom attributes and apply them to your custom views which are parsed when they are created. Here is a thread that goes in to a great bit of detail about it.

The Views themselves don't have to be special. You can say, have a view called a PropertyView view which extends FrameLayout and has a method called getProperty(). You then put the property in the XML like so:

<com.example.ProperyView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   app:property="My Custom Property"/>

Then you would parse it using the methods described in that link.

EDIT:

Alternatively, there are other elements in the XML landscape that can be put in to buckets similar to how Layouts are. Any folder in the /res folder can have the same buckets that the Layouts can. That includes anything in the values, drawables, raw, or xml folders. You can reference these in your Layouts and the Android system will pick which ones you want. More example for how dimens work.

Upvotes: 1

Pooya
Pooya

Reputation: 6136

Sure you can, just in the values directory define values for each size and retrieve them dynamically in your program.

/res/values-xxx
 -> a.xml
/res/values-yyy
 -> a.xml
...

here is an example:

<resources>    
    <integer name="maximum">100</integer>
    ...

</resources>

in your program just put:

int max = getContext().getResources().getInteger(R.integer.maximum);

for each size android will magically do the job and give you the correct value!

Upvotes: 1

Related Questions