当前位置: 代码迷 >> 综合 >> 简单DrawerLayout与ActionBar的结合使用
  详细解决方案

简单DrawerLayout与ActionBar的结合使用

热度:46   发布时间:2023-09-28 20:10:22.0

1. 布局

<android.support.v4.widget.DrawerLayout
    android:id="@+id/i_drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    //主界面<LinearLayout
        android:layout_width="match_parent"
        android:background="#f0f"
        android:layout_height="match_parent">

    </LinearLayout>
    //侧滑菜单<LinearLayout
        android:background="#00f"
        android:gravity="start"
        android:layout_gravity="left"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </LinearLayout>
</android.support.v4.widget.DrawerLayout>

2. 改为该界面继承Activity 

MainActivity extends Activity

3. 改变主题

<style name="AppTheme" parent="android:Theme.Material">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

4. 写主要逻辑代码

public class MainActivity extends Activity {DrawerLayout drawerLayout;
    ActionBarDrawerToggle drawerToggle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        drawerLayout= (DrawerLayout) findViewById(R.id.i_drawerLayout);
        drawerToggle=new ActionBarDrawerToggle(this,drawerLayout,0,0);
        drawerLayout.setDrawerListener(drawerToggle);
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }@Override
    protected void onPostCreate(Bundle savedInstanceState) {super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();
    }@Override
    public boolean onOptionsItemSelected(MenuItem item) {drawerToggle.onOptionsItemSelected(item);
        return super.onOptionsItemSelected(item);
    }@Override
    public void onConfigurationChanged(Configuration newConfig) {drawerToggle.onConfigurationChanged(newConfig);
        super.onConfigurationChanged(newConfig);
    }
}