lumi
lumi

Reputation: 1204

Android layout with version configuration not working properly

I have a layout, activity_read in res/layout-v19 as:

<FrameLayout ...>
...
<include layout="@layout/main_toolbar" />

<View
    android:id="@+id/read_view"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="#f00"
    android:tag="V19"
    />
...

I have another activity_read in res/layout as:

<RelativeLayout ...>
...
<include layout="@layout/main_toolbar" />

<View
    android:id="@+id/read_view"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="#f00"
    android:tag="V1"
    />
...

I'm trying to load the activity_read layout in my Activity:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_read);
    View read = findViewById(R.id.read_view);
    Log.v(TAG, "SDK: " + read.getTag()); //Prints SDK: V1
}

I'm running this example on a Lollipop emulator, so as the documentation says, for platform version based resources, it should pick the layout in res/layout-v19. However, the activity_read layout from res/layout is always loaded, as demonstrated by the "SDK: V1" log.

I also tried seeing if I could load other resources based on platform levels, i.e. integers in values/numbers:

<integer name="test_num">1</integer>

and values-v19/numbers:

<integer name="test_num">19</integer>

Which worked fine:

Log.v(TAG, "NUMBER: " + getResources().getInteger(R.integer.test_num)); //Prints NUMBER: 19

I also tried moving it to res/layout-v21 which did actually work, but it should be working for layout-v1 to layout-v21 as well according to the documentation.

I've wasted quite a bit of time looking into this, so is the documentation wrong or am I missing something?

Thanks in advance.

Upvotes: 4

Views: 811

Answers (1)

bkurzius
bkurzius

Reputation: 4068

I had the same issue - I created a v19 version of a layout, but on Lollipop it loaded the non v19 layout instead. So I did an API check in the code and inflated the proper layout there:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        v = inflator.inflate(R.layout.item_showdetail_asset_kitkat, this);
    } else {
        v = inflator.inflate(R.layout.item_showdetail_asset, this);
    }

Not the ideal solution but it works...

So for the onCreate() in your question it would look like this:

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        setContentView(R.layout.activity_read_kitkatversion);
   }else{
        setContentView(R.layout.activity_read);
   }
   View read = findViewById(R.id.read_view);
   Log.v(TAG, "SDK: " + read.getTag());
}

Upvotes: 1

Related Questions