setSupportActionBar (androidx.appcompat.widget.Toolbar) in AppCompatActivity cannot be applied

前端 未结 8 1466
半阙折子戏
半阙折子戏 2020-12-07 05:36

An error showing incompatible types Android widget toolbar cannot be converted in Java compiler while working on Android Studio.

    Toolbar toolbar = (Toolb         


        
相关标签:
8条回答
  • 2020-12-07 05:55

    Change your activity toolbar import to:

    import android.support.v7.widget.Toolbar;
    
    0 讨论(0)
  • 2020-12-07 06:01
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
    
        Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar); //No Problerm
    
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    

    we must import androidx.appcompat.widget.Toolbar; don't import android.widget.Toolbar;

    0 讨论(0)
  • 2020-12-07 06:07

    AndroidX is the new and improved support library

     import androidx.appcompat.widget.Toolbar;
    

    you can check more about from here here

    Androidx's toolbar is designed for backwards compatibility while

    android.widget.Toolbar

    is the current plattform type

    0 讨论(0)
  • 2020-12-07 06:08

    This error because your Toolbar created using android.widget.Toolbar . But you are using androidX. This also a same kind of error. java.lang.ClassCastException: androidx.appcompat.widget.Toolbar cannot be cast to android.widget.Toolbar

    To solve this kind of you can add these to lines in to your MainActivity.java file (to import).

    import androidx.appcompat.app.AppCompatActivity;

    import androidx.appcompat.widget.Toolbar;

    Make sure to remove or comment out this android.widget.Toolbar . Then again check for error like this. because sometime you may have to import more.

    0 讨论(0)
  • 2020-12-07 06:10

    simply delete

    import android.widget.Toolbar;
    

    and add

    import androidx.appcompat.widget.Toolbar;
    
    0 讨论(0)
  • 2020-12-07 06:11

    Try to replace this:

    import android.widget.Toolbar;
    

    With this:

    import androidx.appcompat.widget.Toolbar;
    

    By the way, if you are using androidx. Run it's migration process. The android support libraries will not be supported in the future. You can read about it here:

    AndroidX Migrating to AndroidX

    0 讨论(0)
提交回复
热议问题