基本上,爲了將圖片包含到列表視圖中,您需要有一個自定義適配器。
爲了做到這一點,創建可擴展適配器類(或在此實例中ArrayAdapter):
public class ParticipantAdapter extends ArrayAdapter<Participant> {
private final Context context;
private final List<Participant> values;
private final String urlToProfilePics;
public ParticipantAdapter(Context context, int resource,
List<Participant> objects) {
super(context, resource, objects);
this.context = context;
this.values = objects;
}
public ParticipantAdapter(Context context, int resource) {
super(context, resource);
this.context = context;
this.values = new ArrayList<Participant>();
// Obtain the external cache directory
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View participantView;
participantView = inflater.inflate(R.layout.participant_item, parent, false);
TextView textView = (TextView) participantView.findViewById(R.id.participantName);
textView.setText(getItem(position).getName());
ImageView imageView = (ImageView) participantView.findViewById(R.id.participantImage);
//you can add varibles to the class that represents your items and use it like so to determine the image displayed
int someContext = getItem(position).someContextOfTheCurrentItem;
switch(someContext) {
case DOG:
imageView.setImageResource(R.drawable.dog);
break;
case CAT:
imageView.setImageResource(R.drawable.cat);
break;
}
//here are some other things you can do on the image based on the context of your item
if(!getItem(position).someBoolean) {
imageView.setImageAlpha(80);
int lightGrey = context.getResources().getColor(R.color.light_grey);
textView.setTextColor(lightGrey);
} else {
int black = context.getResources().getColor(R.color.black);
textView.setTextColor(black);
}
return participantView;
}
public List<Participant> getValues() {
return this.values;
}
心的getView
方法。它所做的是採用包含圖像的佈局XML文件,並根據每個項目的上下文對其進行處理。
在這個例子中,我有一個名爲Participant
一個單獨的類,它包含一個整數,上我的getView
方法做測試一個布爾值,並根據他們的價值觀,我可以改變什麼返回View
將代表。
這是我在這個例子中使用的佈局的XML文件(它只是一個圖片和一個文本視圖,其右側):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/participantImage"
android:layout_width="52dp"
android:layout_height="52dp"
android:contentDescription="@string/contentDescriptionParticipantImage"
android:maxWidth="@dimen/tom_max_width_participant_image"
android:src="@drawable/profile_placeholder" />
<TextView
android:id="@+id/participantName"
android:layout_width="match_parent"
android:layout_height="52dp"
android:padding="@dimen/tom_small_text_padding"
android:text="TextView"
android:textColorHint="@color/black"
android:textSize="@dimen/tom_participant_item_text_size" />
儘量讓你自定義適配器。 – 2014-09-30 10:19:01