1. 程式人生 > >Android中簡單實現DrawerLayout

Android中簡單實現DrawerLayout

<android.support.v4.widget.DrawerLayout xmlns:android=“http://schemas.android.com/apk/res/android
xmlns:app=“http://schemas.android.com/apk/res-auto
xmlns:tools=“http://schemas.android.com/tools
android:id="@+id/drawerLayout"
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=".MainActivity">

<fragment
    class="com.ww.wangwei.yuekao_lianxi.FragmentNav"
    android:layout_gravity="start"
    android:layout_width="360dp"
    android:layout_height="match_parent"></fragment>

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

java程式碼:

public class MainActivity extends AppCompatActivity {

private DrawerLayout drawerLayout;
private ActionBar actionBar;
private ActionBarDrawerToggle toggle;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //找控制元件
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);

    initAction();
 }

 private void initAction() {

    actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
    toggle.syncState();
    drawerLayout.addDrawerListener(toggle);

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (toggle.onOptionsItemSelected(item)){
        return true;
    }
    return super.onOptionsItemSelected(item);

}

新建一個Class,側拉頁面:
public class FragmentNav extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment,container,false);
    return view;

}