android搜索框功能实现

这里实现的是搜索框时时查询,代码中是在数据库中使用的模糊查询;

整个布局使用的是线性布局,搜索框又是一个线性布局(里面包含一个相对布局和一个TextView,相对布局里面有一个EditText和ImageVIew),下面是一个ListView;

搜索框其实就是一个EditText,背景是用shape自己画出来的;上面放一个“删除”的图片;

 

在Activity中给EditText设置一个监听,当输入文字的时候获取输入的内容然后查询数据库,将查询到的数据展示到ListView中;

 

线来看下布局:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="43dp"
        android:background="@color/colorPrimaryDark"
        android:gravity="center"
        android:orientation="horizontal">

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <EditText
                android:id="@+id/edittext"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="8dp"
                android:background="@drawable/searchbox_bj"
                android:hint="请输入搜索内容"
                android:maxLength="10"
                android:paddingLeft="15dp"
                android:singleLine="true"
                android:textSize="12sp" />

            <ImageView
                android:id="@+id/imageview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerInParent="true"
                android:paddingRight="20dp"
                android:src="@drawable/delete"
                android:visibility="gone" />

        </RelativeLayout>

        <TextView
            android:id="@+id/textview"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:text="搜索"
            android:textColor="#ffffff"
            android:textSize="20sp" />
    </LinearLayout>

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"></ListView>
</LinearLayout>


CharSequence s, int start, int before, int count(CharSequence s, int start, int before, int count)方法中做判断,s是EditText中的文本内容;

 

 

 

判断如果s长度为0隐藏“删除”图片,否则显示“删除图片”,显示ListView,查询数据库获得Cursor获得CursorAdapter将内容展示到ListView中;

 

public class MainActivity extends Activity {

    private EditText mEditText;
    private ImageView mImageView;
    private ListView mListView;
    private TextView mTextView;
    Context context;
    Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        
        initView();
    }

    private void initView() {
        mTextView = (TextView) findViewById(R.id.textview);
        mEditText = (EditText) findViewById(R.id.edittext);
        mImageView = (ImageView) findViewById(R.id.imageview);
        mListView = (ListView) findViewById(R.id.listview);

        //设置删除图片的点击事件
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //把EditText内容设置为空
                mEditText.setText("");
                //把ListView隐藏
                mListView.setVisibility(View.GONE);
            }
        });

        //EditText添加监听
        mEditText.addTextChangedListener(new TextWatcher() {
            
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}//文本改变之前执行

            @Override
            //文本改变的时候执行
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //如果长度为0
                if (s.length() == 0) {
                    //隐藏“删除”图片
                    mImageView.setVisibility(View.GONE);
                } else {//长度不为0
                    //显示“删除图片”
                    mImageView.setVisibility(View.VISIBLE);
                    //显示ListView
                    showListView();
                }
            }

            public void afterTextChanged(Editable s) { }//文本改变之后执行
        });

        mTextView.setOnClickListener(new View.OnClickListener() {
            
            public void onClick(View v) {
                //如果输入框内容为空,提示请输入搜索内容
                if(TextUtils.isEmpty(mEditText.getText().toString().trim())){
                    ToastUtils.showToast(context,"请输入您要搜索的内容");
                }else {
                    //判断cursor是否为空
                    if (cursor != null) {
                        int columnCount = cursor.getCount();
                        if (columnCount == 0) {
                            ToastUtils.showToast(context, "对不起,没有你要搜索的内容");
                        }
                    }
                }

            }
        });
    }

    private void showListView() {
        mListView.setVisibility(View.VISIBLE);
        //获得输入的内容
        String str = mEditText.getText().toString().trim();
        //获取数据库对象
        MyOpenHelper myOpenHelper = new MyOpenHelper(getApplicationContext());
        SQLiteDatabase db = myOpenHelper.getReadableDatabase();
        //得到cursor
        cursor = db.rawQuery("select * from lol where name like '%" + str + "%'", null);
        MyListViewCursorAdapter adapter = new MyListViewCursorAdapter(context, cursor);

        mListView.setAdapter(adapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //把cursor移动到指定行
                cursor.moveToPosition(position);
                String name = cursor.getString(cursor.getColumnIndex("name"));
                ToastUtils.showToast(context, name);
            }
        });
    }
}


源码下载地址

 

 

 

 

 

  

 

 

 

 

想要加一个searchView搜索框,在搜索框中输入数据会实时更新listview,试了好多次还是没反应。。。代码如下: ``` package my.AddressList; import java.util.ArrayList; import java.util.List; import java.util.Map; import my.AddressList.listViewAdapter.onItemChangesListener; import android.app.Activity; import android.app.AlertDialog; import android.app.AliasActivity; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SearchView; import android.widget.Toast; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Center extends Activity{ private SearchView mSearchView; private ListView mListView; private Button btn1; private List<Message> messages=new ArrayList(); private List<String> messagename=new ArrayList<String>(); listViewAdapter adapter1,adapter2; SQLiteDatabase db; DataBase dbHelper = new DataBase(this,"StoreMessage",null,2); @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.center); Intent itlogin=super.getIntent(); Intent itcenter=super.getIntent(); Intent itbackadd=super.getIntent(); Intent itcenterM=super.getIntent(); Intent itmtcen=super.getIntent(); btn1=(Button)this.findViewById(R.id.add); mSearchView=(SearchView)this.findViewById(R.id.searchView); mListView=(ListView)this.findViewById(R.id.listview); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent itadd = new Intent(Center.this,addMessage.class); startActivity(itadd); } }); db = dbHelper.getWritableDatabase(); Cursor cursor = db.query("StoreMessage",null,null,null,null,null,null); if (cursor.moveToFirst()){ do{ String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); String relation = cursor.getString(cursor.getColumnIndex("relation")); String fs = cursor.getString(cursor.getColumnIndex("fs")); String address = cursor.getString(cursor.getColumnIndex("address")); String remarks = cursor.getString(cursor.getColumnIndex("remarks")); Message messagesInfo= new Message(name,phone,relation,fs,address,remarks); messages.add(messagesInfo);//加入到list中 }while (cursor.moveToNext()); } adapter1=new listViewAdapter(Center.this,R.layout.listview,messages); mListView.setAdapter(adapter1); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Message message_check = messages.get(i); String checkName =message_check.getName(), checkPhone =message_check.getPhone(), checkRelation =message_check.getRelation(), checkfs =message_check.getfs(), checkAddress = message_check.getAddress(), checkRemarks= message_check.getRemarks(); AlertDialog.Builder builder = new AlertDialog.Builder(Center.this); builder.setMessage( " 姓 名:" + checkName + "\n" + " 联 系 方 式 : " + checkPhone + "\n" + " 关系 : " + checkRelation + "\n" + " 公司 /学校 " + checkfs + "\n" + " 地 址 :" + checkAddress + "\n" + " 备 注 :" + checkRemarks + "\n"); builder.setTitle(" 查看联系人"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); builder.show(); } }); mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) { DeleteDialog(i); return true; } }); //打电话 adapter1.setOnItemCallClickListener(new listViewAdapter.onItemCallListener() { @Override public void onCallClick(int i) { Message message_check = messages.get(i); String phoneNumber = message_check.getPhone(); Intent intent = new Intent(); intent.setAction(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phoneNumber)); startActivity(intent); } }); //编辑 adapter1.setOnItemChangesClickListener(new onItemChangesListener(){ @Override public void onChangesClick(int i) { Message message_check =messages.get(i); String checkName =message_check.getName(), checkPhone = message_check.getPhone(), checkRelation = message_check.getRelation(), checkfs= message_check.getfs(), checkAddress = message_check.getAddress(), checkRemarks= message_check.getRemarks(); Intent itmodify = new Intent(Center.this,Modify.class); itmodify.putExtra("extra_name",checkName); itmodify.putExtra("extra_phone",checkPhone); itmodify.putExtra("extra_relation",checkRelation); itmodify.putExtra("extra_fs",checkfs); itmodify.putExtra("extra_address",checkAddress); itmodify.putExtra("extra_remarks",checkRemarks); itmodify.putExtra("extra_i",i); startActivity(itmodify); Toast.makeText(Center.this,"编辑",Toast.LENGTH_SHORT).show(); } }); } private void DeleteDialog(final int positon){ AlertDialog.Builder builder = new AlertDialog.Builder(Center.this); builder.setMessage("删除联系人"); builder.setTitle("提示"); builder.setPositiveButton("删除", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Message message_check = messages.get(positon); String checkName = message_check.getName(), checkPhone = message_check.getPhone(), checkRelation = message_check.getRelation(), checkfs= message_check.getfs(), checkAddress = message_check.getAddress(), checkRemarks= message_check.getRemarks(); messages.remove(positon); adapter1.notifyDataSetChanged(); //更新listView db.delete("StoreMessage","name = ? and phone= ? and relation = ? and fs= ? and address = ? and remarks = ?", new String[]{checkName,checkPhone,checkRelation,checkfs,checkAddress,checkRemarks}); Toast.makeText(Center.this,"删除成功!",Toast.LENGTH_SHORT).show(); } }); builder.setNeutralButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); builder.show(); mListView.setTextFilterEnabled(true); mSearchView.setSubmitButtonEnabled(true);//有搜索框 mSearchView.setQueryHint("搜索"); mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){ @Override public boolean onQueryTextChange(String newText) { return false; // TODO Auto-generated method stub } @Override public boolean onQueryTextSubmit(String query) { // TODO Auto-generated method stub Toast.makeText(Center.this,"您的选择是:"+query,Toast.LENGTH_SHORT).show(); return false; } }); } } ```
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页