我有一個工作導航抽屜,使用ArrayAdapter
,如documentation所示。我想爲每個導航抽屜項目設置ImageView
圖標,所以我需要創建一個自定義適配器來使用,但我不確定如何操作。我下面的內容運行時不會崩潰應用程序,但導航抽屜會打開並且沒有任何內容。你能幫我解決嗎?提前致謝!導航抽屜的自定義適配器
什麼我迄今自定義適配器來完成:
public class CustomAdapter extends ArrayAdapter
{
private final Context context;
public CustomAdapter(Context context)
{
super(context, R.layout.drawer_list_item);
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.drawer_list_item, parent, false);
TextView textViewHome = (TextView) v.findViewById(R.id.drawerHomeTextView);
ImageView imageViewHome = (ImageView) v.findViewById(R.id.drawerHomeImage);
TextView textViewList = (TextView) v.findViewById(R.id.drawerListTextView);
ImageView imageViewList = (ImageView) v.findViewById(R.id.drawerListImage);
return v;
}
}
在MainActivity
設置抽屜:
mDrawerList = (ListView) findViewById(R.id.leftDrawer);
mDrawerList.setAdapter(new CustomAdapter(this));
的ListView
使用:
<ListView android:id="@+id/leftDrawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
drawer_list_item.xml
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<RelativeLayout
android:id="@+id/drawerRelativeLayoutHome"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/drawerHomeImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:paddingStart="4dp"
android:paddingEnd="4dp"
android:paddingLeft="4dp"
android:src="@drawable/ic_menu_home"/>
<TextView
android:id="@+id/drawerHomeTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/drawerHomeImage"
android:layout_toEndOf="@+id/drawerHomeImage"
android:background="@drawable/background_activated"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:paddingTop="12dp"
android:paddingBottom="12dp"
android:text="Home"
android:textSize="20sp"/>
</RelativeLayout>
<RelativeLayout
android:id="@+id/drawerRelativeLayoutList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/drawerRelativeLayoutHome">
<!-- same as above, but ic_menu_archive as drawable, and "List" as text -->
</RelativeLayout>
</RelativeLayout>