2015-10-14 110 views
1

我的問題很簡單:我有一個定義適配器,設置圖像在ListView:Android的ListView控件定義適配器

package com.tred.stars; 

import android.app.Activity; 
import android.content.ClipData; 
import android.content.Context; 
import android.graphics.Color; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.TextView; 
import android.widget.Toast; 

public class CustomListAdapter extends ArrayAdapter<String> { 

public static String selected_pers= "Graziana Grasso"; 
Activity context; 
String[] itemname; 
Integer[] imgid; 


public CustomListAdapter(Activity context, String[] itemname, Integer[] imgid) { 
    super(context, R.layout.mylist, itemname); 
    // TODO Auto-generated constructor stub 

    this.context=context; 
    this.itemname=itemname; 
    this.imgid=imgid; 

} 




public View getView(int position,View view,ViewGroup parent) { 

    String[] description ={ 
      "desc", 
      "desc", 
      "desc", 
      "desc", 
      "desc", 
      "desc", 
      "desc", 
      "desc" 
    }; 

    LayoutInflater inflater=context.getLayoutInflater(); 
    View rowView=inflater.inflate(R.layout.mylist, null, true); 

    TextView txtTitle = (TextView) rowView.findViewById(R.id.pers_name); 
    ImageView imageView = (ImageView) rowView.findViewById(R.id.pers_image); 
    TextView extratxt = (TextView) rowView.findViewById(R.id.pers_comment); 
    LinearLayout llrow = (LinearLayout) rowView.findViewById(R.id.row); 
    Toast.makeText(getContext(), selected_pers, Toast.LENGTH_SHORT).show(); 

    if (getItem(position).toString()==selected_pers){ 
     llrow.setBackgroundColor(Color.parseColor("#29A3CC")); 
    } 

    txtTitle.setText(itemname[position]); 
    imageView.setImageResource(imgid[position]); 
    extratxt.setText(description[position]); 
    return rowView; 

}; 

}

而且在我的活動我的適配器設置爲我的列表視圖:

DrawerListView = (ListView) findViewById(R.id.drawerLW); 
    CustomListAdapter adapter = new CustomListAdapter(this, itemname, imgid); 
    DrawerListView.setAdapter(adapter); 

但是當我運行在CustomListAdaper方法getView似乎不間斷的重演應用和可變selected_pers似乎是空的。

+0

哪條線路故障?像哪個selected_pers爲null – Keith

+0

getView將被多次調用。沒關係。 http://stackoverflow.com/questions/11648995/view-is-getting-inflated-everytime-in-getview-findviewbyid-is-done-many-ti – Raghunandan

+0

嘗試像這樣'itemname [position] .toString()== selected_pers' – pRaNaY

回答

1

改變這一行:

mInflater.inflate(R.layout.mylist, null, true); 

要:

mInflater.inflate(R.layout.mylist, parent, false); 

而且比較字符串時不能使用==。改變這一行:

if (getItem(position).toString()==selected_pers) 

要:

if (getItem(position).toString().equals(selected_pers)) 

而且,看看this example學習如何實現正確&高效的ListView。