Mark F Mark F -4 years ago 158
Android Question

Determine Which Layout Application is Currently Using

I have 2 Fragments and a Main Activity. An Item from a List in Fragment A is Clicked, the id is retrieved in the Main Activity and the 2nd Fragment replaces the First. This happens in the following interface method within Main Activity:

@Override
public void onCLicked(int id) {
//Launch Fragment B/Pass id to it
}


That works well on a phone screen.

I now made a 2nd layout for a Tablet where the Fragments are side by side. My new layout is in my resource layout-sw720-land folder and looks like this:

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">

<FrameLayout
android:id="@+id/container"
android:layout_width="600dp"
android:layout_height="0dp"
tools:context="com.markf.popularmovies.activities.MainActivity"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent">
</FrameLayout>

<FrameLayout
android:id="@+id/containerDetail"
android:layout_width="600dp"
android:layout_height="0dp"
tools:context="com.markf.popularmovies.activities.MainActivity"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toRightOf="@id/container"
app:layout_constraintRight_toRightOf="parent">
</FrameLayout>
</android.support.constraint.ConstraintLayout>


This layout launches when I'm using my tablet but when I click on an item, Fragment A is replaced with Fragment B as if it was still on the phone. Is there a way to do determine which layout Im in programmatically so I could code this appropriately? I tried reading this solution:Android Developer:Communicating with Other Fragments

but no luck

Answer Source

A simple way to do this would be to check for the existence of a View that's unique to one of the layouts. In this case, since the FrameLayout with ID containerDetail is only in the tablet layout, if findViewById(R.id.containerDetail) returns null, then you're in the phone layout.

For example:

if (findViewById(R.id.containerDetail) == null) {
    // Phone layout
}
else {
    // Tablet layout
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download