<1>、xml布局代码
<
android.support.v4.widget.DrawerLayout
xmlns:
android
=
"http://schemas.android.com/apk/res/android"
xmlns:
tools
=
"http://schemas.android.com/tools"
android
:layout_width=
"match_parent"
android
:layout_height=
"match_parent"
android
:id=
"@+id/dl"
>
<
FrameLayout
android
:id=
"@+id/fl"
android
:layout_width=
"match_parent"
android
:layout_height=
"match_parent"
>
</
FrameLayout
>
<
ListView
android
:layout_width=
"240dp"
android
:layout_height=
"match_parent"
android
:id=
"@+id/lv"
android
:background=
"#00ff00"
android
:layout_gravity=
"start"
android
:choiceMode=
"singleChoice"
></
ListView
>
</
android.support.v4.widget.DrawerLayout
>
<2>、MainActivity代码
public class
MainActivity
extends
AppCompatActivity {
private
List<String>
list
;
private
DrawerLayout
dl
;
@Override
protected void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.
activity_main
);
initDate();
dl
= (DrawerLayout) findViewById(R.id.
dl
);
FrameLayout fl= (FrameLayout) findViewById(R.id.
fl
);
final
ListView lv= (ListView) findViewById(R.id.
lv
);
lv.setAdapter(
new
MyAdapter());
lv.setOnItemClickListener(
new
AdapterView.OnItemClickListener() {
@Override
public void
onItemClick(AdapterView<?> parent, View view,
int
position,
long
id) {
//String string= (String) parent.getItemAtPosition(position);
ContentFragment contentFragment =
new
ContentFragment();
Bundle bundle=
new
Bundle();
bundle.putString(
"name"
,
list
.get(position));
contentFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.
fl
,contentFragment).commit();
dl
.closeDrawer(
lv
);
}
});
}
private void
initDate() {
list
=
new
ArrayList<>();
for
(
int
i=
0
;i<
5
;i++){
list
.add(
"item"
+i);
}
}
class
MyAdapter
extends
BaseAdapter{
@Override
public int
getCount() {
return
list
.size();
}
@Override
public
Object getItem(
int
position) {
return null
;
}
@Override
public long
getItemId(
int
position) {
return
0
;
}
@Override
public
View getView(
int
position, View convertView, ViewGroup parent) {
TextView tv =
new
TextView(MainActivity.
this
);
tv.setText(
list
.get(position));
tv.setTextSize(
25
);
return
tv;
}
}
}
<3>、Fragment类代码
public class
ContentFragment
extends
Fragment{
@Nullable
@Override
public
View onCreateView(LayoutInflater inflater,
@Nullable
ViewGroup container,
@Nullable
Bundle savedInstanceState) {
Bundle bundle = getArguments();
String name = bundle.getString(
"name"
);
TextView textView =
new
TextView(getActivity());
textView.setText(name);
return
textView;
}
}