【问题标题】:filtered listview onListItemClick returns Item at original position过滤后的列表视图 onListItemClick 在原始位置返回项目
【发布时间】:2016-02-11 10:41:51
【问题描述】:

我有一个列表视图,其中包含从自定义 BaseAdaptor 填充的自定义行。单击任何行时,我会打开一个带有片段的新活动。在我将过滤器功能添加到此列表之前,一切正常。当我搜索列表然后单击一个项目时,它不会打开与过滤结果关联的活动。它会在原始列表中的该位置打开一个与项目相关的活动。

例如。 - 原始列表:AA、BA、CC、DA、ED、FF

搜索:“A”过滤结果:AA、BA、DA

但是当我点击项目 DA 时,它会打开 CC 活动。非常烦人。我在适配器上调用了 notifyDataSetChanged()。

主要活动

public class MainActivity_list extends FragmentActivity
    implements HeadlinesFragment.OnHeadlineSelectedListener {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create an instance of ExampleFragment
        HeadlinesFragment firstFragment = new HeadlinesFragment();

        // In case this activity was started with special instructions from an Intent,
        // pass the Intent's extras to the fragment as arguments
        firstFragment.setArguments(getIntent().getExtras());

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, firstFragment).commit();
    }
}

public void onArticleSelected(int position) {
    // The user selected the headline of an article from the HeadlinesFragment

    // Capture the article fragment from the activity layout
    ArticleFragment articleFrag = (ArticleFragment)
            getSupportFragmentManager().findFragmentById(R.id.article_fragment);

    if (articleFrag != null) {
        // If article frag is available, we're in two-pane layout...

        // Call a method in the ArticleFragment to update its content
        articleFrag.updateArticleView(position);

    } else {
        // If the frag is not available, we're in the one-pane layout and must swap frags...

        // Create fragment and give it an argument for the selected article
        ArticleFragment newFragment = new ArticleFragment();
        Bundle args = new Bundle();
        args.putInt(ArticleFragment.ARG_POSITION, position);
        newFragment.setArguments(args);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();
    }
}

在标题片段中

// The container Activity must implement this interface so the frag can deliver messages
public interface OnHeadlineSelectedListener {
    /** Called by HeadlinesFragment when a list item is selected */
    public void onArticleSelected(int position);
}


@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Notify the parent activity of selected item
    mCallback.onArticleSelected(position);

    // Set the item as checked to be highlighted when in two-pane layout

}

自定义适配器

public class CustomAdapter extends BaseAdapter implements Filterable {

Context context;
ArrayList<RowItem> rowItem;

ArrayList<RowItem> mStringFilterList;
ValueFilter valueFilter;




CustomAdapter(Context context, ArrayList<RowItem> rowItem) {
    this.context = context;
    this.rowItem = rowItem;
    mStringFilterList = rowItem;

}

@Override
public int getCount() {

    return rowItem.size();
}

@Override
public Object getItem(int position) {

    return rowItem.get(position);
}

@Override
public long getItemId(int position) {

    return rowItem.indexOf(getItem(position));
}

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

    if (convertView == null) {
        LayoutInflater mInflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        convertView = mInflater.inflate(R.layout.mylist, null);
    }

    ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
    TextView txtTitle = (TextView) convertView.findViewById(R.id.item);

    RowItem row_pos = rowItem.get(position);
    // setting the image resource and title

    txtTitle.setText(row_pos.getTitle());

    Picasso
            .with(context)

            .load(Ipsum.url[position])
            .fit() // will explain later

            .centerCrop()
            .into(imgIcon);



    return convertView;

}

@Override
public Filter getFilter() {
    if (valueFilter == null) {
        valueFilter = new ValueFilter();
    }
    return valueFilter;
}

private class ValueFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();

        if (constraint != null && constraint.length() > 0) {
            ArrayList<RowItem> filterList = new ArrayList<RowItem>();
            for (int i = 0; i < mStringFilterList.size(); i++) {
                if ( (mStringFilterList.get(i).getTitle().toUpperCase() )
                        .contains(constraint.toString().toUpperCase())) {

                    RowItem rowItem = new RowItem(mStringFilterList.get(i)
                            .getTitle());

                    filterList.add(rowItem);
                }
            }
            results.count = filterList.size();
            results.values = filterList;
        } else {
            results.count = mStringFilterList.size();
            results.values = mStringFilterList;
        }
        return results;

    }

    @Override
    protected void publishResults(CharSequence constraint,
                                  FilterResults results) {
        rowItem = (ArrayList<RowItem>) results.values;
        notifyDataSetChanged();
    }

}

【问题讨论】:

  • 回调在哪里实现?
  • 我用回调添加所有主要活动

标签: android listview filter


【解决方案1】:

问题是过滤数据集中的位置指向原始数据集中的不同对象。如果您不想更改主要逻辑,您可以做的是更改您的 onArticleSelected 以将实例 RowItem 而不是 position 作为参数并更改您的 onListItemClick 喜欢

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Notify the parent activity of selected item
    mCallback.onArticleSelected((RowItem)l.getItemAtPostion(position));

    // Set the item as checked to be highlighted when in two-pane layout

}

这将检索传递正确的对象到您的活动

【讨论】:

  • 这段代码让我可以在主要活动中更改“RowItem”中的“int”,但在这一行中更改“position” args.putInt(ArticleFragment.ARG_POSITION, position);给我错误
  • RowItem 可以打包吗?如果不检查使其可打包,然后使用 args.putParcelable
  • 我不明白你的意思(对不起)。我不认为它可以打包
  • Parcelable 是 Android 为您提供通过 Intent/bundle 传递对象的一种特殊方式。
  • 您可以阅读更多关于它的信息here。 AndroidStudio 有一个插件可以自动完成。你可能想看看
【解决方案2】:

对于那些使用 public void onItemClick(AdapterView parent, View view, int position, long id)

 private void setUpAdapter()
  {
    adapter2 = new CustomAdapter2(kafani, getApplicationContext());
    listView.setAdapter(adapter2);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    Log.e("C pozicija ",""+ position) ;
    Log.e("C id",""+id) ;

  //  Kaf kafana = (Kaf) listView.getItemAtPosition(position); 

    Kaf kafana = (Kaf) kafani.get((int) id); // where kafani is ORIGINAL LIST, so I use the id
    String pozicija = String.valueOf(id);  

    // String pozicija = String.valueOf(position); 

    Intent myIntent = new Intent(IndiecZaKaf.this, KafDetails.class);
    myIntent.putExtra("parent", "A");
    myIntent.putExtra("pozicija", pozicija);
    myIntent.putExtra("imek",kafana.getImek());
    myIntent.putExtra("adresa",kafana.getAdresa());
    myIntent.putExtra("tel",kafana.getTelBroj());

    startActivity(myIntent);
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-16
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多