2015-11-23 38 views
0

我有一個圖像列表視圖與動態列表項目長度,我只有3個圖像,但圖像只能在每個項目上設置如果狀態值爲OK,OFFLINE或PENDING,我怎麼能使用IF ELSE IF和ELSE設置在每個列表視圖中的項的3個圖像中的一個,下面我的代碼的示例:設置圖像ListView與If語句

Integer[] imageId = { 
      R.drawable.round_green, 
      R.drawable.round_red, 
      R.drawable.round_grey, 
     }; 

ContactsAdapter adapter = new ContactsAdapter(this, itemTitle, itemStatus, imageId); 
list.setAdapter(adapter); 
list.setOnItemClickListener(this);  

public View getView(int position, View convertView, ViewGroup parent) { 
      // TODO Auto-generated method stub 

      View row=convertView; 
      if(row==null) 
      { 
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      row = inflater.inflate(R.layout.activity_item, parent, false);  
      } 

      TextView tvTitle = (TextView) row.findViewById(R.id.Title); 
      TextView tvStatus = (TextView) row.findViewById(R.id.Status); 
      ImageView imageView = (ImageView) row.findViewById(R.id.imageView); 

      tvTitle.setText(Title.get(position)); 
      tvStatus.setText(Status.get(position)); 
      imageView.setImageResource(imgid[position]); //this must set either image A or B or C depending on value of text view status which can either be OK, OFFLINE or PENDING 

      return row; 
      } 
+0

如果你正在使用自定義列表查看然後提供getView()方法的代碼 – warlock

+0

編輯顯示getView()方法 – user5174952

+0

你在哪裏檢查狀態,我認爲這段代碼會把第一個圖像放在第一個位置第二個圖像在第二個位置等等 – warlock

回答

4

我可以使用IF ELSE IF和ELSE設置3個圖像中的一個在每個列表中 查看項目

我們可以不使用if-else階梯,使用HashMap

使用OK,離線或掛起的關鍵和drawable的ID爲值的HashMap:

Map<String, Integer> drawableMap = new HashMap<String, Integer>(); 
drawableMap.put("ok",R.drawable.round_green); 
drawableMap.put("pending",R.drawable. round_grey); 
drawableMap.put("offline",R.drawable. round_red); 

現在使用Status.get(position)關鍵檢索繪製ID:

imageView.setImageResource(drawableMap.get(Status.get(position).toLowerCase())); 
+0

同意這一個。您甚至可以使用開關子句檢查狀態並直接使用drawable。我不明白爲什麼你應該使用數組,當你傳遞最終的ID – JesusS

0

在適配器ContactsAdapter得在getView方法裏面並且使條件像

if(value.equal("OK")) 
{ 
//set your image... 
} 
else if(value.equal("OFFLINE")) 
{ 
//set your image... 
} 
else if(value.equals(PENDING)) 
{ 
//set your image... 
}