为了真正清楚地构造它,我为一个面向对象的实现做了几行额外的代码,该实现从一个 s 数组生成所有内容NavigationItem
- 一个包含文本字段、图标和菜单项片段的普通 Java 类:
在 MainActivity 我的 Navigation 简单地由数组定义:
NavigationAdapter navigationMenuAdapter;
NavigationItem[] navigationMenuItems = {
new NavigationItem(R.string.menu_home, R.drawable.ic_menu_home, new MainFragment()),
new NavigationItem(R.string.menu_statistics, R.drawable.ic_statistics, new StatisticsFragment()),
new NavigationItem(R.string.menu_settings, R.drawable.ic_settings, new SettingsFragment()),
};
protected void onCreate(Bundle savedInstanceState) {
...
navigationMenuAdapter = new NavigationAdapter(this, navigationMenuItems);
mDrawerList.setAdapter(navigationMenuAdapter);
}
...
private void selectItem(int position) {
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, navigationMenuItems[position].fragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(navigationMenuItems[position].stringTitle);
mDrawerLayout.closeDrawer(mDrawerList);
}
NavigationItem
班级:
public class NavigationItem
{
/**
*
* @param stringTitle The id of the string resource of the text of the item.
* @param drawableIcon The id of the drawable resource of icon of the item.
* @param fragment The Fragment to be loaded upon selecting the item.
*/
public NavigationItem(int stringTitle, int drawableIcon, Fragment fragment)
{
this.stringTitle = stringTitle;
this.drawableIcon = drawableIcon;
this.fragment = fragment;
}
/**
* The id of the string resource of the text of the item.
*/
public int stringTitle;
/**
* The id of the drawable resource of icon of the item.
*/
public int drawableIcon;
/**
* The Fragment to be loaded upon selecting the item.
*/
public Fragment fragment;
}
和导航适配器:
public class NavigationAdapter extends BaseAdapter {
private Context context;
private NavigationItem[] navigationItems;
public NavigationAdapter(Context context, NavigationItem[] items) {
this.context = context;
navigationItems = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_navigation, parent, false);
} else {
row = convertView;
}
TextView tvTitle = (TextView) row.findViewById(R.id.textView);
ImageView ivIcon = (ImageView) row.findViewById(R.id.imageView);
tvTitle.setText(navigationItems[position].stringTitle);
ivIcon.setImageResource(navigationItems[position].drawableIcon);
return row;
}
}
它使用一个非常基本的 xml 布局,list_item_navigation
只包含一个ImageView
和一个TextView
。