Android-адаптер скрытие строк - PullRequest
1 голос
/ 02 августа 2011

В arrayAdptor мы используем следующий код:

 final LayoutInflater inflater = activity.getLayoutInflater();
    row = (LinearLayoutCustom) inflater.inflate(R.layout.row, null);
    final TextView label = (TextView) row.findViewById(R.id.title);
    label.setText(position + "" + items[position]); 
    return row;

Теперь предположим, что какое-то значение равно нулю (например, в позиции 2, items [2] = null), поэтому я не хочу показывать его в строке. я хочу это скрыть если я использую

               row.setVisibility(View.GONE) 

оставляет в этой строке пустое место, которое мне не нужно. так что мне делать?

Ответы [ 5 ]

8 голосов
/ 30 ноября 2012

AFAIK, вы не можете вернуть нулевое представление из getView, но вы можете просто сделать представление невидимым и высотой 1. Хотя манипуляции с использованием getCount, вероятно, предпочтительнее.

view.setVisibility(View.INVISIBLE);
view.getLayoutParams().height = 1;
2 голосов
/ 02 августа 2011

Вам нужно, чтобы адаптер возвращал общее число ненулевых элементов с помощью getCount, а затем сохранял привязку позиции к вашей внутренней структуре данных.

Например.У вас есть список

1 - John
2 - null
3 - Bill
4 - Susan
5 - null

Когда вызывается getCount, он возвращает 3.

Затем, когда в позиции 1 вызывается getView, вы возвращаете элемент в list[1].getView в позиции 2 возвращает list[3] (так как это 2-й ненулевой) и т. Д.

Это единственный способ, который я нашел, чтобы сделать это.

1 голос
/ 05 ноября 2012

Вы можете использовать вид, который не имеет высоты для «скрытых» предметов, чтобы вам не приходилось выполнять всю работу по моделированию и составлению карт.Например, предположим, что у вас есть поле EditText «фильтра», которое при вводе данных сохраняет только совпадающие элементы:

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater   inflater = (LayoutInflater) MyActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    RelativeLayout view = (RelativeLayout) inflater.inflate(R.id.myListLayout, null, false);

    ...

    // if we didn't match filter be GONE and leave
    if (filterText.length() > 0 && myModelValueAtPosition.toLowerCase().indexOf(filterText) < 0){
        view = (RelativeLayout) inflater.inflate(R.layout.myListLayoutWithZeroHeight, null, false);
        view.setVisibility(View.GONE); // this doesn't really do anything useful; I'd hoped it would work by itself, but turns out the zero height layout is the key
        return view;
    }
    view.setVisibility(View.VISIBLE);

    ...
}
0 голосов
/ 08 января 2018

Это решение, которое я реализовал, вот пример кода для всех, кто его ищет:

class Shipment_Adapter extends ArrayAdapter<Shipment>{
     ....
     ArrayList<Integer> emptyPositions = new ArrayList<>();

     public Shipment_Adapter(Context context, int shipment_row, Shipment[] myShipments){
        super(context, R.layout.shipment_row,myShipments);

        //populate emptyPositions list
        for(int i = 0; i< myShipments.length; i++){
            if(myShipments[i]==null){
                emptyPositions.add(i);
            }
        }

        this.mShipment = myShipments;
        this.mContext = context;
    }

    //corrects size of List
    @Override
    public int getCount() {
        return (mShipment.length - emptyPositions.size());
    }

    //recursive function that checks if position is not empty until it isn't
    public int isEmpty(int positiontocheck){
         int newposition;
         if(emptyPositions.contains(positiontocheck)){
             //true? check that next one is free
            return isEmpty(positiontocheck+1);
         }else{
            newposition = positiontocheck;
         }

         return newposition;
     }
}

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

    //now just need to use isEmpty to get the next not empty position in 
    //case our real position is empty

    position= isEmpty(position);

    Shipment shipment = mShipment[position];

    ...//and so on

 }

надеюсь, это поможет!

0 голосов
/ 02 августа 2011

Здесь вам нужно написать логику в вашем getCount () , getItemId () и getItem () ,
Это создаст нетстрок, которые getCount возвращает

//How many items are in the data set represented by this Adapter
    public int getCount() {
            return //Should return the count of rows you need to display (here the count excluding null values)
        }

И

//This need to return data item associated with the specified position in the data set.
public Object getItem(int position) {
        return //Return the object need to display at position, need the logic to skip null value  
    }

Редактировать: Так в вашем getview

 public View getView(int position, View convertView, ViewGroup parent) { 
         ---- 
        getItem(position);//Object corresponding to position ,In your case it will not be null since you need to write the logic to skip null object at getItem
        ----
}
...