2

我很难让我的操作栏的 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();
    }
}
4

1 回答 1

1

检查此链接 -搜索概述

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 );
于 2013-10-22T05:44:41.127 回答