如何在键入时仅显示匹配项目的列表视图,而不是一次显示所有(不匹配的)项目?

时间:2016-04-22 15:47:08

标签: java android listview android-arrayadapter searchview

列表加载所有字符串,匹配时显示匹配的项目。但是,我希望该列表仅在输入搜索时显示,并且列表仅包含搜索的项目。

package com.example.searchlistview;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

public class MainActivity extends Activity implements SearchView.OnQueryTextListener {

    private static final String TAG = "SearchViewFilterMode";

    private SearchView mSearchView;
    String data,temp,users;
    private ListView mListView;
    private ArrayAdapter<String> mAdapter;

    private final ArrayList<String> mstrings_arr=new ArrayList<String>(); 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);

        setContentView(R.layout.activity_main);

        mSearchView = (SearchView) findViewById(R.id.search_view);
        mListView = (ListView) findViewById(R.id.list_view);



        try
        {
            ThreadPolicy policy = new ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            HttpClient client=new DefaultHttpClient();                  
            HttpPost post=new HttpPost("http://192.162.1.126:1234/www/search_reg_users.php");

            HttpResponse res=client.execute(post);
            InputStream inp=res.getEntity().getContent();
            BufferedReader bf=new BufferedReader(new InputStreamReader(inp));

            //since this much code of Buffered reader alone wont get , complete data , therefore , we add the below code

            data="";
            temp="";

            while((temp=bf.readLine())!=null)
            {
                data=data+temp;
            }

            JSONArray array=new JSONArray(data);

            for(int i=0;i<array.length();i++)
            {
                JSONObject object=array.getJSONObject(i);

                users=object.getString("username"); 
                mstrings_arr.add(users);
                Toast.makeText(getApplicationContext(),users+" added to list",Toast.LENGTH_SHORT).show();

            }
        }

        catch(Exception e)
        {
            e.printStackTrace();
        }





        mListView.setAdapter(mAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                mstrings_arr));
        mListView.setTextFilterEnabled(true);
        setupSearchView();
    }

    private void setupSearchView() {
        mSearchView.setIconifiedByDefault(false);
        mSearchView.setOnQueryTextListener(this);
        mSearchView.setSubmitButtonEnabled(false);
        mSearchView.setQueryHint(getString(R.string.cheese_hunt_hint));
    }

    public boolean onQueryTextChange(String newText) {
        if (TextUtils.isEmpty(newText)) {
            mListView.clearTextFilter();
        } 

在上面的代码之后,我试过,只有在找到匹配项时才将listview的可见性设置为VISIBILE。它仅适用于一个搜索实例,如果找到匹配项,则返回整个列表。

我希望得到的内容如下:

  1. 在搜索框中输入搜索
  2. 如果该搜索与列表项中的任何项匹配
  3. 仅此列表显示仅限匹配项目
  4. 其他{

                mListView.setFilterText(newText.toString());
                mListView.setVisibility(View.VISIBLE);
            }
        return true;
    }
    
    public boolean onQueryTextSubmit(String query) {
        return false;
    }
    

    }

2 个答案:

答案 0 :(得分:2)

您需要使用addTextChangedListener来解决您的问题。我做过类似的事情。

addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable s) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start,
                                      int before, int count) {
                if (s.length() != 0) {
                }
            }
        });

答案 1 :(得分:0)

AutoCompleteTextView 达到了目的,最后

package com.example.searchlistview;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.text.Layout;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

//public class MainActivity extends Activity implements SearchView.OnQueryTextListener {
public class MainActivity extends Activity{

    private static final String TAG = "SearchViewFilterMode";

    private SearchView mSearchView;
    String data,temp,users;
    private ListView mListView;

    private final ArrayList<String> mstrings_arr=new ArrayList<String>(); 


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);

        setContentView(R.layout.activity_main);
        ArrayAdapter<String> mAdapter=new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,mstrings_arr);

        mSearchView = (SearchView) findViewById(R.id.search_view);
        mListView = (ListView) findViewById(R.id.list_view);



        try
        {
            ThreadPolicy policy = new ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            HttpClient client=new DefaultHttpClient();                  


            HttpPost post=new HttpPost("http://192.168.1.16:1234/www/search_reg_users.php");


            HttpResponse res=client.execute(post);
            InputStream inp=res.getEntity().getContent();
            BufferedReader bf=new BufferedReader(new InputStreamReader(inp));

            //since this much code of Buffered reader alone wont get , complete data , therefore , we add the below code

            data="";
            temp="";

            while((temp=bf.readLine())!=null)
            {
                data=data+temp;
            }

            JSONArray array=new JSONArray(data);

            for(int i=0;i<array.length();i++)
            {
                JSONObject object=array.getJSONObject(i);

                users=object.getString("username"); 
                mstrings_arr.add(users);
                Toast.makeText(getApplicationContext(),users+" added to list",Toast.LENGTH_SHORT).show();

            }
        }

        catch(Exception e)
        {
            e.printStackTrace();
        }


        //AutoCompleteSearchView

        AutoCompleteTextView actv= (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);  
        actv.setThreshold(1);//will start working from first character  
        actv.setAdapter(mAdapter);//setting the adapter data into the AutoCompleteTextView  
        actv.setTextColor(Color.RED);  

    }

XML ,同样是:

<AutoCompleteTextView  
    android:id="@+id/autoCompleteTextView1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignParentLeft="true"  
    android:layout_marginLeft="36dp"  
    android:layout_marginTop="17dp"  
    android:ems="10"  
    android:text="">  

    <requestFocus />  
</AutoCompleteTextView>