主界面
在这里插入代码片package com.example.dell.myapplication1207cela;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//显示标题栏左边
//actionBar是4.0 getAction
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.left,new LeftFrgemet())
.commit();
drawer = findViewById(R.id.drawer);
toggle = new ActionBarDrawerToggle(this, drawer, R.string.option, R.string.close);
toggle.syncState();
drawer.addDrawerListener(toggle);
drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
@Override
public void onDrawerSlide(@NonNull View view, float v) {
Log.i("TEST","onDrawerSilde:"+ v);
}
@Override
public void onDrawerOpened(@NonNull View view) {
Log.i("TEST","onDrawerOPend");
}
@Override
public void onDrawerClosed(@NonNull View view) {
Log.i("TEST", "onDrawerClosed");
}
@Override
public void onDrawerStateChanged(int i) {
Log.i("TEST", "onDrawerStateChanged: " + i);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//先交给toggle处理
if (toggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
//关闭侧拉菜单
public void closeDrawer() {
drawer.closeDrawer(Gravity.START);
}
}
fragment
在这里插入代码片package com.example.dell.myapplication1207cela;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class LeftFrgemet extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.left, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "点击了侧边菜单", Toast.LENGTH_SHORT).show();
//关闭Left Drawer
((MainActivity) getActivity()).closeDrawer();
}
});
}
}