2012-02-24 5 views
0

Я использую ListFragment с пользовательским адаптером.Android Listview сбрасывает изменения при прокрутке

У меня есть адаптер textview и скрыть imageview со стрелкой. Когда пользователь выбирает элемент, появляются стрелки и меняется цвет фона. Но, когда пользователь просматривает список, все изменения возвращаются к умолчанию.

Что я должен сделать, чтобы исправить изменения?

EDIT:

мой адаптер класс ..

public class PropriedadeAdapter extends BaseAdapter { 
private Context context; 
private List<Propriedades> prop; 

public PropriedadeAdapter(Context context, List<Propriedades> prop) { 
    this.context = context; 
    this.prop = prop; 
} 

public int getCount() { 
    return prop.size(); 
} 

public Object getItem(int position) { 
    return prop.get(position); 
} 

public long getItemId(int position) { 
    return position; 
} 

public View getView(int position, View convertView, ViewGroup parent) { 
    // Recupera o produto da posição atual 
    Propriedades p = prop.get(position); 

    // Layout XML 
    int arquivoLayout = R.layout.lista_prop; 
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View v = inflater.inflate(arquivoLayout, null); 

    // Atualiza o valor do Text para o nome do produto 
    TextView textNome = (TextView) v.findViewById(R.id.nome); 
    textNome.setText(p.getNome()); 

    return v; 
} 
} 

мой Fragment класс ..

public class frag_lista extends ListFragment{ 

ImageView ultimoItem = null; 

@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState); 
    ArrayList<Propriedades> props = new ArrayList<Propriedades>(); 
    for(int i = 0; i <50; i++) 
    { 
     Propriedades prop = new Propriedades(); 
     prop.setNome("FRUTA "+i); 
     props.add(prop); 
    } 
    setListAdapter(new PropriedadeAdapter(this.getActivity(),props)); 
} 


@Override 
public void onListItemClick(ListView l, View v, int position, long id) { 
    ImageView seta = (ImageView)v.findViewById(R.id.imgSeta); 
    seta.setVisibility(0); 
    LinearLayout linha = (LinearLayout)v.findViewById(R.id.linha); 
    linha.setBackgroundColor(Color.GRAY); 
    if(ultimoItem != null) 
    { 
     ultimoItem.setVisibility(4); 
    } 
    ultimoItem = seta; 
} 

} 

, что я должен сделать, чтобы persiste изменения метода onListItemClick ????

+0

Когда вы говорите «изменения возвращаются к умолчанию», это только для отображаемых представлений (т. Е. Видов, которые в настоящее время не отображаются при запуске прокрутки)? – Sly

+0

i.e. У моего списка есть 120 itens (по умолчанию state = bgcolor green и no arrow). Если я выберу первый (bgcolor = красный со стрелкой), то прокрутите до последнего, когда я вернусь к первому, все изменения вернутся в исходное состояние. – JannGabriel

+0

Я редактирую свой ответ – Sly

ответ

0

Согласно вашему мнению, я думаю, что вы не используете адаптер правильно.

Adapter предоставляет методы, которые автоматически вызывается ListView.

Вы должны сохранять выбранные индексы в памяти и восстанавливать состояние просмотра каждый раз, когда вызывается метод getView(...) (смещение от аргумента позиции).

Ищите учебник о ListView и адаптере.

EDIT:

Обратите внимание, что я не проверял код, но это может быть что-то вроде этого:

// TeddyBearFr: Class name typically starts with a capital letter! Frag_lista, not frag_lista 
public class frag_lista extends ListFragment{ 

    ImageView ultimoItem = null; 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
     ArrayList<Propriedades> props = new ArrayList<Propriedades>(); 
     for(int i = 0; i <50; i++) 
     { 
      Propriedades prop = new Propriedades(); 
      prop.setNome("FRUTA "+i); 
      props.add(prop); 
     } 
     setListAdapter(new PropriedadeAdapter(this.getActivity(),props)); 
    } 


    @Override 
    public void onListItemClick(ListView l, View v, int position, long id) { 

     // TeddyBearFr: notify the adapter 
     ((PropriedadeAdapter) this.getListAdapter()).onListItemClick(position); 

     // TeddyBearFr: your last item must be managed in the getView(...) method of the Adapter 
     //if(ultimoItem != null) 
     //{ 
     // ultimoItem.setVisibility(4); // TeddyBearFr: don't use integer like this, use Android constants! View.INVISIBLE 
     //} 
     //ultimoItem = seta; 
    } 

} 


public class PropriedadeAdapter extends BaseAdapter { 
    private final static String TAG = "PropriedadeAdapter"; 
    private Context context; 
    private List<Propriedades> prop; 
    private Set<Integer> mSelectedItemsPosition; 

    public PropriedadeAdapter(Context context, List<Propriedades> prop) { 
     this.context = context; 
     this.prop = prop; 
     // TeddyBearFr: set to store selected indexes 
     this.mSelectedItemsPosition = new HashSet<Integer>(); 
    } 

    public int getCount() { 
     return prop.size(); 
    } 

    public Object getItem(int position) { 
     return prop.get(position); 
    } 

    public long getItemId(int position) { 
     return position; 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     Log.d(TAG, "getView(position=" + position + ", convertView=" + convertView + ", parent=" + parent + ")"); 

     // Recupera o produto da posição atual 
     Propriedades p = prop.get(position); 

     // TeddyBearFr: use existing view if exist ; otherwise create a new one 
     View v; 
     if(convertView == null){ 
      // Layout XML 
      int arquivoLayout = R.layout.lista_prop; 
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      v = inflater.inflate(arquivoLayout, null); 
     } 
     else{ 
      v = convertView; 
     } 

     // Atualiza o valor do Text para o nome do produto 
     TextView textNome = (TextView) v.findViewById(R.id.nome); 
     textNome.setText(p.getNome()); 

     // TeddyBearFr: update view according its selection state 
     ImageView seta = (ImageView)v.findViewById(R.id.imgSeta); 
     boolean isViewSelected = this.mSelectedItemsPosition.contains(position); 
     int visibility = (isViewSelected ? VIEW.VISIBLE : VIEW.GONE); 
     seta.setVisibility(visibility); 

     LinearLayout linha = (LinearLayout)v.findViewById(R.id.linha); 
     linha.setBackgroundColor(isViewSelected ? Color.GRAY : Color.RED); 

     if(position == getCount()-1){ 
      // perform special processes on the last item of the list if needed 
     } 

     return v; 
    } 

    // TeddyBearFr: callback when click 
    public void onListItemClick(int position){ 
     Log.d(TAG, "onListItemClick(position=" + position + ")"); 

     // update selected index data 
     // Note that I haven't tested if it works. Because native integer "position" will be wrapped in Integer object, there's a chance that the Set compares the references on objects instead of their value 
     if(this.mSelectedItemsPosition.contains(position)){ 
      this.mSelectedItemsPosition.remove(position); 
     } 
     else{ 
      this.mSelectedItemsPosition.add(position); 
     } 

     // ask the list to be refreshed -> you'll see that getView() will be called only for each displayed view 
     this.notifyDataSetChanged(); 
    } 

} 
+0

Я отредактировал свой вопрос, не могли бы вы показать мне, что я делаю неправильно? – JannGabriel

0

convertView имеет два состояния, в которых он является недействительным и не равно нулю. Ваша проблема возникает из-за того, что eveytime yout getView() вызывает новый экземпляр раздувания макета, который инициализируется. Инициализация надувателя только тогда, когда convertView имеет значение NULL.

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

    Propriedades p = prop.get(position); 
    int arquivoLayout = R.layout.lista_prop; 

    View v; 

    if (convertView==null){ 
     v = inflater.inflate(arquivoLayout, null); 
    } 
    else { 
     v = convertView; 
    } 

    // Atualiza o valor do Text para o nome do produto 
    TextView textNome = (TextView) v.findViewById(R.id.nome); 
    textNome.setText(p.getNome()); 

    return v; 
} 

Кроме того, не забудьте объявить надув как поле.

LayoutInflater inflater = null; 

И инициализировать его в конструкторе.

public PropriedadeAdapter(Context context, List<Propriedades> prop) { 
    this.context = context; 
    this.prop = prop; 
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 
Смежные вопросы