позиция неправильно изменяется с помощью списка Android

У меня возникла запутанная проблема с моим списком в Android. Я получаю свой список из базы данных, и эти результаты необходимо фильтровать на основе заданных критериев. Отображается список по умолчанию, затем список можно отфильтровать на основе конкретной нажатой кнопки. Вся эта фильтрация происходит правильно. Моя проблема начинается, когда я нажимаю на один из элементов в списке. Позиция не возвращается правильно (я проверяю это с помощью Toast.makeText(this," " + position, Toast.LENGTH_SHORT).show();)

Я разместил код, который, по моему мнению, может иметь отношение к проблеме. Любая помощь будет здорово!

@Override
public void onClick(View v) {
    switch(v.getId()){ 
    case R.id.search:
        Intent i = new Intent(v.getContext(), SearchScreen.class);
        startActivityForResult(i, 0);
        break;
    case R.id.directory:  

        break;  
    case R.id.todo:  
        Intent i1 = new Intent(v.getContext(), ToDoScreen.class);
        startActivityForResult(i1, 0);

        break;   
    case R.id.favorites:
        Intent i2 = new Intent(v.getContext(), FavsScreen.class);
        startActivityForResult(i2, 0);

        break;
    case R.id.coupon:
        Intent i3 = new Intent(v.getContext(), CouponScreen.class);
        startActivityForResult(i3, 0);

        break;
    case R.id.info:
        Intent i4 = new Intent(v.getContext(), InfoScreen.class);
        startActivityForResult(i4, 0);

        break;
    case R.id.creative:
        countybar.setVisibility(View.VISIBLE);
        business.setChamber(0);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.downtown:
        countybar.setVisibility(View.GONE);
        business.setChamber(1);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.chamber:
        countybar.setVisibility(View.VISIBLE);
        business.setChamber(2);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.all:
        business.setCounty(0);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.cayuga:
        business.setCounty(1);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.cortland:
        business.setCounty(2);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.herkimer:
        business.setCounty(3);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.jefferson:
        business.setCounty(4);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.lewis:
        business.setCounty(5);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.madison:
        business.setCounty(6);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.monroe:
        business.setCounty(7);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.oneida:
        business.setCounty(8);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.onondaga:
        business.setCounty(9);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.oswego:
        business.setCounty(10);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.seneca:
        business.setCounty(11);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.lawrence:
        business.setCounty(12);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.tompkins:
        business.setCounty(13);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;
    case R.id.yates:
        business.setCounty(14);
        category = business.filterCategoryString();
        adap.notifyDataSetChanged();

        break;



    }



}




@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    Toast.makeText(this, category.elementAt(position) + position + "  onListItemClick", Toast.LENGTH_SHORT).show();
    business.setCategory(category.elementAt(position));
}

public static class EfficientAdapter extends BaseAdapter implements Filterable {
private LayoutInflater mInflater;
private Context context;

public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
this.context = context;
}

/**
* Make a view to hold each row.
*
* @see android.widget.ListAdapter#getView(int, android.view.View,
*      android.view.ViewGroup)
*/
public View getView(final int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid
// unneccessary calls
// to findViewById() on each row.
    ViewHolder holder;

// When convertView is not null, we can reuse it directly, there is
// no need
// to reinflate it. We only inflate a new View when the convertView
// supplied
// by ListView is null.
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.list_items, null);

// Creates a ViewHolder and store references to the two children
// views
// we want to bind data to.
        holder = new ViewHolder();
        holder.textLine = (TextView) convertView.findViewById(R.id.textLine);
        holder.iconLine = (ImageView) convertView.findViewById(R.id.rightarrow);


        convertView.setOnClickListener(new OnClickListener() {
            private int pos = position;

            @Override
            public void onClick(View v) {
                Toast.makeText(context, category.elementAt(pos) + pos + "  On Click", Toast.LENGTH_SHORT).show();   
                business.setCategory(category.elementAt(pos));
                Intent intent = new Intent(v.getContext(), ListingScreen.class);
                context.startActivity(intent);
            }
        });


        convertView.setTag(holder);
    } else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
        holder = (ViewHolder) convertView.getTag();
    }

// Bind the data efficiently with the holder.
    holder.textLine.setText(category.elementAt(position));

    return convertView;
}

static class ViewHolder {
    TextView textLine;
    ImageView iconLine;
    Button buttonLine;
}

@Override
public android.widget.Filter getFilter() {
// TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
    return 0;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
    return category.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
    return category.elementAt(position);
}

person coder    schedule 21.07.2011    source источник


Ответы (1)


Воспользуйтесь формулой:

wantedPos = position - listView.getFirstVisiblePosition()

;)

person Nikola Despotoski    schedule 21.07.2011
comment
Проблема в том, что когда я нажимаю на элемент из списка, он отвечает на метод onClick в getView, на onItemClick, поэтому у меня нет доступа к объекту listView... - person coder; 25.07.2011
comment
Переопределить listView.setOnItemClickedListener(). Не в адаптере. - person Nikola Despotoski; 25.07.2011