【问题标题】:How SearchView of my Action Bar can works on a ListView?我的 Action Bar 的 SearchView 如何在 ListView 上工作?
【发布时间】:2013-10-21 11:11:40
【问题描述】:

我无法使我的操作栏的 SearchView 在此代码中工作。真的不知道该怎么做,因为我是为 Android、java 和其他所有东西开发的新手。所以......想帮助某人能够在我的应用程序的数据库中搜索我的 ListView 中的至少一个 Android 搜索引擎。

谢谢!

package br.com.jandeilson.myproject;

import br.com.jandeilson.myproject.R;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;

public class ListarActivity extends Activity {

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.listar_activity_actions, menu);

        // Associate searchable configuration with the SearchView
        SearchManager searchManager =
               (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =
                (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getComponentName()));

        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_new:
        startActivity(new Intent(this, Inserir.class));
        return true;
        default:
        return super.onOptionsItemSelected(item);
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listar);
    }

    public void onResume(){
        super.onResume();

        SQLiteDatabase db = openOrCreateDatabase("objetos.db", Context.MODE_PRIVATE, null);

        // Tabela de objetos
        StringBuilder sqlClientes = new StringBuilder();
        sqlClientes.append("CREATE TABLE IF NOT EXISTS objetos (");
        sqlClientes.append("_id INTEGER PRIMARY KEY, ");
        sqlClientes.append("nomeobj VARCHAR(30)); ");
        db.execSQL(sqlClientes.toString());

        Cursor cursor = db.rawQuery("SELECT * FROM objetos", null);

        String[] from = {"nomeobj"};
        int[] to = {R.id.NomeObj};

        android.widget.SimpleCursorAdapter ad = new android.widget.SimpleCursorAdapter(getBaseContext(),
                R.layout.listar_model, cursor, from, to);

        ListView ltwDados = (ListView)findViewById(R.id.ltwDados);

        ltwDados.setAdapter(ad);


        ltwDados.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView adapter, View view,
                    int position, long id) {

                SQLiteCursor c = (SQLiteCursor) adapter.getAdapter().getItem(position);

                Intent it = new Intent(getBaseContext(), Editar.class);
                it.putExtra("id", c.getInt(0));
                startActivity(it);
            }
        });

        db.close();
    }
}

【问题讨论】:

    标签: java android sqlite android-actionbar searchview


    【解决方案1】:

    检查此链接 - Search Overview

    您的 sdk 文件夹中的示例:sdk/samples/android-15/SearchableDictionary/

    更新: 像这样:

    private void loadWords() throws IOException {
                Log.d(TAG, "Loading words...");
    
                ArrayList<String> list = new ArrayList<String>();
                list.add("one");
                list.add("two");
    
    
                for ( String str: list){
                    addWord( str, ""); // word, def.
                }
                Log.d(TAG, "DONE loading words.");
            }
    

    更新:

    public class CustomAutoCompleteTextView extends AutoCompleteTextView {
    
    
        //was the text just cleared?
        boolean justCleared = false;
    
    
        public Drawable imgClearIcon = getResources().getDrawable(android.R.drawable.ic_menu_close_clear_cancel);
    
        public CustomAutoCompleteTextView(Context context) {
            super(context);
    
            init();
        }
    
        /* Required methods, not used in this implementation */
        public CustomAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle)
        {
            super(context, attrs, defStyle);
            init();
        }
        /* Required methods, not used in this implementation */
        public CustomAutoCompleteTextView(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            init();
        }
    
    
        void init()
        {
            // Set the bounds of the button
            this.setCompoundDrawablesWithIntrinsicBounds(null, null, imgClearIcon, null);
    
            // button should be hidden on first draw
            clrButtonHandler();
    
            //if the clear button is pressed, clear it. Otherwise do nothing
            this.setOnTouchListener(new OnTouchListener()
            {
                @Override
                public boolean onTouch(View v, MotionEvent event)
                {
    
                    CustomAutoCompleteTextView et = CustomAutoCompleteTextView.this;
    
                    if (et.getCompoundDrawables()[2] == null)
                        return false;
    
                    if (event.getAction() != MotionEvent.ACTION_UP)
                        return false;
    
                    if (event.getX() > et.getWidth() - et.getPaddingRight() - imgClearIcon.getIntrinsicWidth())
                    {
                        et.setText("");
                        CustomAutoCompleteTextView.this.clrButtonHandler();
                        justCleared = true;
                    }
                    return false;
                }
            });
        }
    
        void clrButtonHandler()
        {
    
            if (this == null || this.getText().toString().equals("") || this.getText().toString().length() == 0)
            {
                //Log.d("CLRBUTTON", "=cleared");
                //remove clear button
                this.setCompoundDrawables(null, null, null, null);
            }
            else
            {
                //Log.d("CLRBUTTON", "=not_clear");
                //add clear button
                this.setCompoundDrawablesWithIntrinsicBounds(null, null, imgClearIcon, null);
            }
        }
    }
    

    ....

    public class AutoCompleteTextAdapter extends ArrayAdapter<String> implements Filterable {
        ArrayList<String> mSuggestions = null;
        ....
        @Override
    public Filter getFilter(){
        Filter myFilter = new Filter() {
    
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                FilterResults filterResults = new FilterResults();
                if ( charSequence != null ){
    
    
                    // Now assign the values and count to the FilterResults object
                    if ( mSuggestions != null ){
                        filterResults.values = mSuggestions.toArray();
                        filterResults.count = mSuggestions.size();
                    }
    
                    Log.e(TAG, "performFiltering: finish;");
    
                }
                return filterResults;
            }
    
            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                Log.d(TAG, "publishResults: " + charSequence);
                if ( filterResults != null && filterResults.count > 0 )
                    notifyDataSetChanged();
                else
                    notifyDataSetInvalidated();
    
    
    
    
            }
        };
        return myFilter;
    }
    
    public void updateList ( ArrayList<String> str ){
    
    
        mSuggestions = str;
    
    
        notifyDataSetChanged();
    }
    

    将此添加到您的自定义操作栏布局中:

        <br.com.jandeilson.forgob.CustomAutoCompleteTextView
        android:id="@+id/tv_actionbar_AutoComplete"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:ems="7"
        android:imeOptions="actionSearch"
        android:inputType="textAutoComplete|textAutoCorrect"
        android:drawableRight="@android:drawable/ic_menu_close_clear_cancel"
        android:hint="hint here"
    
        android:textCursorDrawable="@null"
    
        android:textColor="#FFFFFF">
    
        </br.com.jandeilson.forgob.CustomAutoCompleteTextView>
    

    把这个写在简历上:

    ArrayList <String> list = new ArrayList<String>( ) ;
    
            //List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
    
            list.addAll(new ArrayList<String>(Arrays.asList(cursor.getColumnNames()))); // not getColumnNames() need use here;
            adapter.updateList(  list );
    

    【讨论】:

    • 看过这个例子,但不知道如何应用到我的例子中。
    • 此示例也使用 DB,但从 txt 文件加载数据。查看类:DictionaryDatabase 和方法private void loadWords() 行:InputStream inputStream = resources.openRawResource(R.raw.definitions); 只需将其替换为您的列表即可;
    • 我按照你说的做了,但不幸的是无法在我的代码中应用这个例子。如果我提供我的源代码,你能帮助我吗?
    • 谢谢! :) 这是我的项目:skydrive.live.com/redir?resid=34A2904BAA33CF84!1565
    • 是的,我看到了。我不知道如何使用 google 示例获取动态数据,但是......您可以使用 AutoCompleteTextView,需要创建 CustomAutoCompleteTextView 并创建 AutoCompleteTextAdapter。并创建自定义操作栏;
    猜你喜欢
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多