视图格式:
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout android:id="@+id/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:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.wzq.drawerlayoutdemo2.MainActivity"> <FrameLayout android:id="@+id/frameLayout" android:layout_width="match_parent" android:layout_height="match_parent"/> <!-- 和drawerLayout配合需要配这两个属性 android:layout_gravity="left" android:choiceMode="singleChoice" --> <ListView android:id="@+id/lv" android:background="@color/colorPrimary" android:layout_width="300dp" android:layout_gravity="left" android:choiceMode="singleChoice" android:layout_height="match_parent"/> </android.support.v4.widget.DrawerLayout>
代码在此:
主界面中的FrameLayout真视图是主显示界面
public class MFragment extends Fragment{ @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstancState) { TextView textView = new TextView(getActivity());
//Bundle是传递ListView和Fragment之间数据的Bundle arguments = getArguments();
String name = arguments.getString("name");
textView.setText(name);
return textView;
}}MainActivity中的代码:
public class MainActivity extends AppCompatActivity { private DrawerLayout drawerLayout; private FrameLayout frameLayout; private ListView lv; private ArrayList<String> lists; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); setListener(); } private void initView() { drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); frameLayout = (FrameLayout) findViewById(R.id.frameLayout); lv = (ListView) findViewById(R.id.lv); } private void initData() { lists = new ArrayList<>(); for (int i = 0; i < 5; i++) { lists.add("DrawerLayout"+i); } ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, lists); lv.setAdapter(stringArrayAdapter); } //Bundle是传递ListView和Fragment之间数据的 private void setListener() { lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { MFragment mFragment = new MFragment(); Bundle bundle = new Bundle(); bundle.putString("name", lists.get(i)); mFragment.setArguments(bundle); getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout,mFragment).commit(); //关闭drawer drawerLayout.closeDrawer(lv); } }); } }