Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use android support library correctly

I'm working my way through Professional Android 4 Application Development. Chapter 4 modifies the To Do List app to use fragments, but I'm trying to test on a Gingerbread device. There's mention in the book of using support libraries to allow using Android v3 or v4 features on a lower version device, but it's not covered very well.

I'm running into a problem specifically with:

    // Get references to the Fragments
    android.app.FragmentManager fm = getFragmentManager();
    ToDoListFragment    todoListFragment = (ToDoListFragment) fm.findFragmentById( R.id.ToDoListFragment );

I've got these imports at the top: import android.support.v4.app.FragmentManager; import android.support.v4.app.ListFragment;

But lint warns on the "ToDoListFragment todoListFragment = (ToDoListFragment)" line: cannot cast from Fragment to ToDoListFragment

In my ToDoListFragment class, I have:

    import android.support.v4.app.ListFragment;

    public class ToDoListFragment extends ListFragment {
    }

This is almost verbatim from the book, except for the change to use support library.

I'm not clear on how to get this code to work correctly using the v4 support library. I apologize in advance if this isn't enough info. I'm still learning this, and I'm more familiar with C/C++ than Java. If I don't use the support library, the code builds just fine and will run on an Ice Cream Sandwich device, but I'd like to get it working on lower level devices, too.

like image 201
WarnerYoung Avatar asked Nov 06 '12 19:11

WarnerYoung


People also ask

What is the use of Android support library?

The features of the Android Support Library include: Backward-compatible versions of framework components. These compatibility libraries allow you to use features and components available on newer versions of the Android platform even when your app is running on an older platform version.

Should you use legacy Android support libraries?

We recommend using the AndroidX libraries in all new projects. You should also consider migrating existing projects to AndroidX as well. So all Android apps should now aim to use AndroidX, instead of the old support library.


1 Answers

You should use getSupportFragmentManager() instead of getFragmentManager()

android.support.v4.app.FragmentManager fm = getSupportFragmentManager()
like image 105
Alexander Kulyakhtin Avatar answered Oct 04 '22 04:10

Alexander Kulyakhtin