Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android how to use Toolbar in ListActivity?

I made a ListActivity:

 public class NoteListActivity extends ListActivity{
 }

and the following methods are no longer available:

    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

But I can use:

    setActionBar(toolbar);
    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setDisplayHomeAsUpEnabled(true);

Note that I used Support library in other activities in the same project. It means I have the correct gradle dependency added.

How do I use ListActivity and android.support.v7.widget.Toolbar ?

like image 490
masiboo Avatar asked Aug 04 '15 12:08

masiboo


2 Answers

You can't do that in ListActivity.

If you want to access getSupportActionBar(), you need to extend your class with AppCompatActivity.

My Suggestion : Don't use ListActivty as you want to use ToolBar. Create an Activity and then only have ListView within that Activity. It'll work just fine.

like image 187
Noman Rafique Avatar answered Sep 30 '22 02:09

Noman Rafique


     @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AppCompatCallback callback = new AppCompatCallback() {
        @Override
        public void onSupportActionModeStarted(ActionMode actionMode) {
        }

        @Override
        public void onSupportActionModeFinished(ActionMode actionMode) {
        }

        @Nullable
        @Override
        public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
            return null;
        }
    };

    AppCompatDelegate delegate = AppCompatDelegate.create(this, callback);

    delegate.onCreate(savedInstanceState);
    delegate.setContentView(R.layout.saved_report_activity);

    Toolbar toolbar= (Toolbar) findViewById(R.id.toolbar);
    delegate.setSupportActionBar(toolbar);
    delegate.getSupportActionBar().setDisplayShowHomeEnabled(true);

    toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NavUtils.navigateUpFromSameTask(SavedReportActivity.this);
        }
    });
like image 34
Neupane Taman Avatar answered Sep 30 '22 04:09

Neupane Taman