首页 \ 问答 \ 使用RecyclerView的SearchView过滤器(SearchView filter with RecyclerView)

使用RecyclerView的SearchView过滤器(SearchView filter with RecyclerView)

我试图用Fragment中的建议(过滤器)实现SearchView,但我没有管理它。 我尝试了几乎所有的教程,但没有为我工作。 我将不胜感激任何帮助。 谢谢

XML ...

    <!--appBar layout-->
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize">

        <!--searchView layout-->
        <android.support.v7.widget.SearchView
            android:id="@+id/search_view"
            app:layout_scrollFlags="scroll|enterAlways"
            android:iconifiedByDefault="false"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:closeIcon="@drawable/ic_clear_white_18dp"
            app:searchIcon="@drawable/ic_search_white_24dp"
            app:queryHint="@string/search_contact"
            app:iconifiedByDefault="false"
            android:background="@color/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

       </android.support.design.widget.AppBarLayout>

        <!-- recycler view-->
        <android.support.v7.widget.RecyclerView
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

分段

@Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contact_list, container, false);

        searchView = (SearchView)view.findViewById(R.id.search_view);
        fabButton = (FloatingActionButton)view.findViewById(R.id.fab_button);

        //recycler view
        recyclerView = (RecyclerView)view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        contacts = SugarRecord.listAll(Contact.class);
        contactsAdapter = new ContactsAdapter(getActivity(), contacts);
        recyclerView.setAdapter(contactsAdapter);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // TODO: setFilter

                return true;
            }
        });

        return view;

适配器

public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ContactVH> {

    List<Contact> mContact;
    List<Contact> mContactFilter;

    Context mContext;

    public ContactsAdapter(Context context, List<Contact> contact) {
        this.mContact = contact;
        this.mContext = context;
    }

    @Override
    public ContactVH onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_contact, parent, false);
        ContactVH viewHolder = new ContactVH(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ContactVH holder, int position) {
        holder.name.setText(mContact.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return mContact.size();
    }

    class ContactVH extends RecyclerView.ViewHolder {
        @BindView(R.id.contact_name)
        TextView name;

        public ContactVH(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

    }

}

I have tried to implement a SearchView with suggestions (filter) in Fragment, but I have not managed it. I tried almost every tutorial but nothing worked for me. I would appreciate any help. Thank you

XML ...

    <!--appBar layout-->
    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBarLayout"
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize">

        <!--searchView layout-->
        <android.support.v7.widget.SearchView
            android:id="@+id/search_view"
            app:layout_scrollFlags="scroll|enterAlways"
            android:iconifiedByDefault="false"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:closeIcon="@drawable/ic_clear_white_18dp"
            app:searchIcon="@drawable/ic_search_white_24dp"
            app:queryHint="@string/search_contact"
            app:iconifiedByDefault="false"
            android:background="@color/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

       </android.support.design.widget.AppBarLayout>

        <!-- recycler view-->
        <android.support.v7.widget.RecyclerView
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

Fragment

@Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contact_list, container, false);

        searchView = (SearchView)view.findViewById(R.id.search_view);
        fabButton = (FloatingActionButton)view.findViewById(R.id.fab_button);

        //recycler view
        recyclerView = (RecyclerView)view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        contacts = SugarRecord.listAll(Contact.class);
        contactsAdapter = new ContactsAdapter(getActivity(), contacts);
        recyclerView.setAdapter(contactsAdapter);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // TODO: setFilter

                return true;
            }
        });

        return view;

Adapter

public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ContactVH> {

    List<Contact> mContact;
    List<Contact> mContactFilter;

    Context mContext;

    public ContactsAdapter(Context context, List<Contact> contact) {
        this.mContact = contact;
        this.mContext = context;
    }

    @Override
    public ContactVH onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_contact, parent, false);
        ContactVH viewHolder = new ContactVH(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ContactVH holder, int position) {
        holder.name.setText(mContact.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return mContact.size();
    }

    class ContactVH extends RecyclerView.ViewHolder {
        @BindView(R.id.contact_name)
        TextView name;

        public ContactVH(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

    }

}

原文:https://stackoverflow.com/questions/38098390
更新时间:2022-06-30 11:06

最满意答案

web2py在数据库事务中包装每个HTTP请求。 如果请求期间发生异常,则将回滚事务。 否则,在请求结束时,在返回响应之前,事务将被提交(因此将在那时提交所有插入/更新操作)。

如果在应用程序代码中显式调用db.commit() ,则事务将立即提交,而不是等到请求结束。 任何后续操作都将成为新交易的一部分。

在上述两种情况下,所有更新都将同时提交。 唯一的区别是,在第一种情况下,提交将在返回HTTP响应之前由框架发出(假设没有中间异常触发回滚),在第二种情况下,提交在运行后立即发生更新循环。

在选项2中,如果您在循环中移动了db.commit()调用,那么确实会一次提交一个更新,而不是一次提交所有更新。

另请注意,要更新记录,您无需先选择它,如果要将同一更新应用于多个记录,则无需一次更新一条记录,而是将更新应用于表示所有记录的DAL Set对象:

db(db.people.id > 0).update(name='Bob')

上面定义了db.people表中的一组记录(在本例中是所有记录),然后更新所有这些记录的“name”字段。 此操作不涉及从数据库中选择的任何记录。


web2py wraps each HTTP request in a database transaction. If there is an exception during the request, the transaction will be rolled back. Otherwise, at the end of the request, just before returning the response, the transaction is committed (so all insert/update operations will be committed at that time).

If you explicitly call db.commit() in the application code, then the transaction will be committed immediately rather than waiting until the end of the request. Any subsequent operations will be part of a new transaction.

In both cases above, all of the updates will be committed at the same time. The only difference is that in the first case, the commit will be issued by the framework right before returning the HTTP response (assuming there is no intervening exception that triggers a rollback), and in the second case, the commit happens immediately after running through the loop of updates.

In option 2, if you moved the db.commit() call inside the loop, then the updates would indeed be committed one at a time rather than all at once.

Also, note that to update a record, you do not need to first select it, and if you want to apply the same update to many records, you don't need to update one record at a time but would instead apply the update to a DAL Set object representing all the records:

db(db.people.id > 0).update(name='Bob')

The above defines a set of records in the db.people table (in this case, all the records) and then updates the "name" field of all of those records. This operation does not involve any records being selected from the database.

相关问答

更多
  • 在创建表格时,您可以添加一个基本上包含要插入一次默认数据的夹具文件。 这里给出一个例子: http : //thadeusb.com/weblog/2010/4/21/using_fixtures_in_web2py You can add a fixtures file, which basically contains default data to be inserted once, when the table is created. An example is given here: http:/ ...
  • 看起来你应该在cursor.execute之后将你的db.commit()移动到fetch函数中。 另一种可以使用“global”关键字和光标的方法。 或者,第三种方式,只需将光标作为函数的参数。 It seems like you should move your db.commit() into fetch function after cursor.execute. Another way you may use "global" keyword with cursor. Or, third way, ...
  • web2py DAL需要连接字符串,而不是pyodbc连接对象。 也许创建当前.pyc文件的人可以创建一个新文件来返回DAL对象而不是pyodbc对象。 另一方面,您可能会试图说服他们使用.pyc文件并没有真正增加安全性,因为有许多工具可用于反编译.pyc文件。 此外,一旦你有了pyodbc对象,你或许也可以从中提取连接字符串。 与试图隐藏连接字符串相比,有更好的方法来控制数据库访问和权限。 The web2py DAL requires a connection string, not a pyodbc ...
  • 我不认为你可以在这种情况下使用.update_or_insert方法,因为n_rec的值取决于是否找到记录。 相反,你可以做这样的事情: db.define_table('count_table', Field('user_id', 'integer', unique=True), Field('n_rec', 'integer', default=1)) def update_count(user_id): return db(db.count_table.user_id == ...
  • web2py在数据库事务中包装每个HTTP请求。 如果请求期间发生异常,则将回滚事务。 否则,在请求结束时,在返回响应之前,事务将被提交(因此将在那时提交所有插入/更新操作)。 如果在应用程序代码中显式调用db.commit() ,则事务将立即提交,而不是等到请求结束。 任何后续操作都将成为新交易的一部分。 在上述两种情况下,所有更新都将同时提交。 唯一的区别是,在第一种情况下,提交将在返回HTTP响应之前由框架发出(假设没有中间异常触发回滚),在第二种情况下,提交在运行后立即发生更新循环。 在选项2中,如 ...
  • 如果我正确理解你,你有一个名为'users'的预先存在的表。 如果是这种情况那么你就会遇到这样的事实:默认情况下,web2py希望为你处理数据库(定义关系,属性等)。 一个修复,如果您知道数据库的布局,首先要在web2py中定义模型,以便与表中的模型完全匹配; 运行一次以生成sql.log; 修改你的模型; 再次运行它。 另一种方法是关闭迁移,以便它不会尝试修改数据库结构。 这意味着您将失去非常有用的自动迁移,并且必须自己执行ALTER语句。 你选择哪一个我强烈建议你先快速阅读web2py手册第6章的迁移部 ...
  • 首先阅读文档的jQuery和Ajax章节。 特别是,请查看ajax函数 。 如果task元素是具有“name”属性的表单元素,则可以按如下方式调用ajax函数(假设表单元素的名称为“task”): ajax("{{=URL('default', 'insert_task')}}", ['task']); 如果task元素不是表单元素,则可以通过查询字符串将其传递给web2py: ajax("{{=URL('default', 'insert_task')}}" + '?task=' + encodeURI ...
  • db已经在您的模型中定义,这些模型自您传递了-M选项后即被执行。 没有必要再定义它! db is already defined in your models, which are executed since you passed the -M option. There's no need to define it again!
  • scheduler.queue_task执行插入操作,但它是与上一行中的插入相同的事务的一部分,因此两个插入将同时提交。 因此,在提交初始插入之前,不应该处理任务。 scheduler.queue_task does an insert, but it is part of the same transaction as the insert in the previous line, so both inserts will be committed at the same time. So, it sh ...
  • DAL能够在单个字段中保存JSON数据,但它不提供查询JSON数据的特定属性的机制,因为这需要RDBMS本身内的特殊功能,大多数数据库都不支持这种功能。 The DAL is able to save JSON data in individual fields, but it does not provide a mechanism for querying specific attributes of the JSON data, as that requires special functionali ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)