导航抽屉无法识别自定义适配器布局

时间:2015-03-27 04:31:38

标签: android adapter drawer

有人可以指出此代码段的问题是什么

Custom adapter

public class NavigationAdapter extends ArrayAdapter<NavItem> {
private Context context;
private NavItem[] values;

public NavigationAdapter(Context context, int layoutResourceId,NavItem[] values) {
    super(context, layoutResourceId);
    this.context = context;
    this.values = values;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    final Holder holder;
    LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View convertView1 = convertView;
    if (convertView1 == null) {
        holder = new Holder();
        convertView1 = vi.inflate(R.layout.item_row, parent,false);
        holder.imageView = (ImageView) convertView1.findViewById(R.id.rowIcon);
        holder.textView = (TextView) convertView1.findViewById(R.id.rowText);
        convertView1.setTag(holder);
    } else {
        holder = (Holder) convertView1.getTag();
    }
    NavItem item = values[position];

    holder.imageView.setImageResource(item.icon);
    holder.textView.setText(item.name);

    return convertView1;
}

private class Holder {
    public TextView textView;
    public ImageView imageView;
}
}

custom listview layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:background="?android:attr/activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:padding ="10dp">

<ImageView
    android:id="@+id/rowIcon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/ic_action_settings"
    android:paddingRight="10dp"/>

<TextView
    android:id="@+id/rowText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toRightOf="@+id/rowIcon"
    android:paddingRight="10dp"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"/>

Main activity

NavItem settings = new NavItem();
settings.icon = R.drawable.ic_action_settings;
settings.name = "Settings";

NavItem send = new NavItem(R.drawable.ic_action_settings,"Sent");

NavItem[] values = new NavItem[]{
                settings,send
};

NavigationAdapter adapter = new NavigationAdapter(this, R.layout.item_row, values);
mDrawerListView.setAdapter(adapter);

当我打开抽屉时,它只显示一个空白页面。如果我将适配器更改为字符串的ArrayAdapter并使内置布局膨胀,那么它可以工作,但我想在文本旁边添加图像。

1 个答案:

答案 0 :(得分:0)

根据我的经验,我遇到过类似的问题。

我通过更改:

解决了这个问题
public class NavigationAdapter extends ArrayAdapter<NavItem> {

}

到:

public class NavigationAdapter extends BaseAdapter<NavItem> {

}

我已经从BaseAdapter类扩展了我的自定义适配器,它适用于我的情况。如果它也适合你,请试试这个