我正在使用AndroidHive: Material Design中的模板,并决定在每个导航抽屉行上添加一些图标。 我已经修改了模型NavDrawerItem,添加了图标的getter和setter。
// Constructor
public NavDrawerItem(boolean showNotify, String title, int icon) {
this.showNotify = showNotify;
this.title = title;
this.icon = icon;
}
public String getTitle() {
return title;
}
public int getIcon(){
return icon;
}
public void setTitle(String title) {
this.title = title;
}
public void setIcon(int icon){
this.icon = icon;
}
它的适配器(NavigationDrawerAdapter)也被修改,添加了图标支持
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
holder.icon.setImageResource(current.getIcon());
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
icon = (ImageView) itemView.findViewById(R.id.icon_drawer);
}
}
我知道这个抽屉是在FragmentDrawer.java的onCreate方法上添加的
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
icons = getActivity().getResources().getIntArray(R.array.nav_drawer_icon);
}
这是我在string.xml中的数组
<string-array name="nav_drawer_labels">
<item>@string/nav_item_home</item>
<item>@string/nav_item_data_visualization</item>
<item>@string/nav_item_pending_item</item>
<item>@string/nav_item_my_profile</item>
<item>@string/nav_item_about_us</item>
</string-array>
<string-array name="nav_drawer_icon">
<item>@drawable/ic_home</item>
<item>@drawable/ic_data_visualization</item>
<item>@drawable/ic_pending_item</item>
<item>@drawable/ic_profile_drawer</item>
<item>@drawable/ic_about</item>
</string-array>
我的导航抽屉项目是使用FragmentDrawer.java中的这段代码从资源填充的
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
System.out.println(titles[i]);
navItem.setIcon(icons[i]);
System.out.println(icons[i]);
data.add(navItem);
}
return data;
}
我的问题是从资源中填充图标,在System.out.println(icons [i])上面的代码中;总是给我0值。我想这就是为什么我不能设置导航抽屉图标的imageResource。
任何帮助将不胜感激。谢谢。
答案 0 :(得分:1)
问题在于:
icons = getActivity().getResources().getIntArray(R.array.nav_drawer_icon);
要从数组中读取资源ID,您可以使用以下代码:
icons = new int[titles.length];
TypedArray iconsArray = getResources().obtainTypedArray(R.array.nav_drawer_icon);
for (int i = 0; i < icons.length; i++)
icons[i] = iconsArray.getResourceId(i, -1);
iconsArray.recycle();
但可能最好的行动是使用NavigationView。