【问题标题】:how to implement searchview filter in android?如何在android中实现searchview过滤器?
【发布时间】:2019-01-11 02:32:32
【问题描述】:

由于我是 android 新手,我不知道如何实现 searchview 过滤器。因为我使用 picasso 从服务器检索图像并通过 cardview 显示它。我的预期输出是当用户键入仅需要过滤特定 gridview 的汽车名称时。请有人帮助我使这个搜索视图可行。

MainActivity Screen

MainActivity.java

public class MainActivity extends AppCompatActivity {

static String urlAddress="server_url";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    //FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

    final GridView gv= (GridView) findViewById(R.id.gv);
    new Downloader(MainActivity.this,urlAddress,gv).execute();

}

}

spacecraft.java(Data_Object)

public class Spacecraft {

int id;
String name,propellant,description,imageUrl;


public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getPropellant() {
    return propellant;
}

public void setPropellant(String propellant) {
    this.propellant = propellant;
}

public String getImageUrl() {
    return imageUrl;
}

public void setImageUrl(String imageUrl) {
    this.imageUrl = imageUrl;
}
}

Connector.java

public class Connector {

public static HttpURLConnection connect(String urlAddress)
{
    try
    {
        URL url=new URL(urlAddress);
        HttpURLConnection con= (HttpURLConnection) url.openConnection();

        //PROPERTIES
        con.setRequestMethod("GET");
        con.setConnectTimeout(20000);
        con.setReadTimeout(20000);
        con.setDoInput(true);

        return con;

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}
}

DataParser.java

public class DataParser extends AsyncTask<Void,Void,Boolean> {

Context c;
String jsonData;
GridView gv;

ProgressDialog pd;
ArrayList<Spacecraft> spacecrafts=new ArrayList<>();

public DataParser(Context c, String jsonData, GridView gv) {
    this.c = c;
    this.jsonData = jsonData;
    this.gv = gv;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();

    pd=new ProgressDialog(c);
    pd.setTitle("Parse");
    pd.setMessage("Parsing..Please wait");
    pd.show();
}

@Override
protected Boolean doInBackground(Void... params) {
    return this.parseData();
}

@Override
protected void onPostExecute(Boolean parsed) {
    super.onPostExecute(parsed);

    pd.dismiss();

    if(parsed)
    {
        //BIND
        CustomAdapter adapter=new CustomAdapter(c,spacecrafts);
        gv.setAdapter(adapter);
    }else {
        Toast.makeText(c,"Unable To Parse",Toast.LENGTH_SHORT).show();
    }
}

private Boolean parseData()
{
    try
    {
        JSONArray ja=new JSONArray(jsonData);
        JSONObject jo;

        spacecrafts.clear();
        Spacecraft spacecraft;

        for (int i=0;i<ja.length();i++)
        {
            jo=ja.getJSONObject(i);

            int id=jo.getInt("id");
            String name=jo.getString("name");
            String prop=jo.getString("propellant");
            String desc=jo.getString("description");
            String imageUrl=jo.getString("imageurl");

            spacecraft=new Spacecraft();

            spacecraft.setId(id);
            spacecraft.setName(name);
            spacecraft.setPropellant(prop);
            spacecraft.setDescription(desc);
            spacecraft.setImageUrl(imageUrl);

            spacecrafts.add(spacecraft);

        }

        return true;

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

    return false;
}
}

Downloader.java

public class Downloader extends AsyncTask<Void,Void,String> {

Context c;
String urlAddress;
GridView gv;

ProgressDialog pd;

public Downloader(Context c, String urlAddress, GridView gv) {
    this.c = c;
    this.urlAddress = urlAddress;
    this.gv = gv;
}



@Override
protected void onPreExecute() {
    super.onPreExecute();

    pd=new ProgressDialog(c);
    pd.setTitle("Retrieve");
    pd.setMessage("Retrieving..Please wait");
    pd.show();

}

@Override
protected String doInBackground(Void... params) {
    return this.downloadData();
}

@Override
protected void onPostExecute(String jsonData) {
    super.onPostExecute(jsonData);

    pd.dismiss();

    if(jsonData==null)
    {
        Toast.makeText(c,"Unsuccessful,No Data Retrieved ",Toast.LENGTH_SHORT).show();
    }else {
        //PARSER
        DataParser parser=new DataParser(c,jsonData,gv);
        parser.execute();

    }

}

private String downloadData()
{
    HttpURLConnection con=Connector.connect(urlAddress);
    if(con==null)
    {
        return null;
    }

    try
    {
        InputStream is=new BufferedInputStream(con.getInputStream());
        BufferedReader br=new BufferedReader(new InputStreamReader(is));

        String line;
        StringBuffer jsonData=new StringBuffer();

        while ((line=br.readLine()) !=null)
        {
            jsonData.append(line+"\n");
        }

        br.close();
        is.close();

        return jsonData.toString();

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

    return null;
}

public class execute {
}
}

CustomAdapter.java

public class CustomAdapter extends BaseAdapter {

Context c;
ArrayList<Spacecraft> spacecrafts;

public CustomAdapter(Context c, ArrayList<Spacecraft> spacecrafts) {
    this.c = c;
    this.spacecrafts = spacecrafts;
}

@Override
public int getCount() {
    return spacecrafts.size();
}

@Override
public Object getItem(int position) {
    return spacecrafts.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView==null)
    {
        convertView= LayoutInflater.from(c).inflate(R.layout.model,parent,false);
    }

    TextView nameTxt= (TextView) convertView.findViewById(R.id.nameTxt);
    ImageView img= (ImageView) convertView.findViewById(R.id.spacecraftImage);

    final Spacecraft s= (Spacecraft) this.getItem(position);

    nameTxt.setText(s.getName());
    PicassoClient.downloadImage(c, s.getImageUrl(), img);



    convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openDetailACtivity(s.getName(),s.getPropellant(),s.getDescription(),s.getImageUrl());
        }
    });

    return convertView;
}

private void openDetailACtivity(String name,String propellant,String 
 description,String imageUrl)
  {
    Intent i=new Intent(c, DetailActivity.class);

    //PACK DATA
    i.putExtra("NAME_KEY",name);
    i.putExtra("PROPELLANT_KEY",propellant);
    i.putExtra("DESCRIPTION_KEY",description);
    i.putExtra("IMAGEURL_KEY",imageUrl);

    c.startActivity(i);
 }
 } 

PicassoClient.java

public class PicassoClient {

public static void downloadImage(Context c,String imageUrl,ImageView img)
{
    if(imageUrl!=null && imageUrl.length()>0)
    {

Picasso.with(c).load(imageUrl).placeholder(R.drawable.placeholder).into(img);
    }else {
        Picasso.with(c).load(R.drawable.placeholder).into(img);
    }
}
}

content_main

   <?xml version="1.0" encoding="utf-8"?>
    <SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/background_light" />

     <GridView
       android:id="@+id/gv"
     android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="49dp" />
  </RelativeLayout>

model.xml

  <?xml version="1.0" encoding="utf-8"?>
  <android.support.v7.widget.CardView 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal" android:layout_width="match_parent"
  xmlns:card_view="http://schemas.android.com/apk/res-auto"
  android:layout_margin="10dp"
  card_view:cardCornerRadius="5dp"
  card_view:cardElevation="5dp"
  android:layout_height="150dp">

 <LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:id="@+id/spacecraftImage"
        android:padding="10dp"
        android:src="@drawable/placeholder" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Name"
        android:id="@+id/nameTxt"
        android:padding="10dp"
        android:textColor="@color/colorAccent"
        android:layout_alignParentLeft="true"
         />

</LinearLayout>
</android.support.v7.widget.CardView>

这是显示产品描述的详细活动

DetailActivity Screen

activity_detail

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

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

<include layout="@layout/content_detail" />

DetailActivity.java

public class DetailActivity extends AppCompatActivity {

TextView nameTxt,propTxt,descTxt;

//Initialize webservice URL
ImageView img;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    nameTxt= (TextView) findViewById(R.id.nameTxtDetail);
    descTxt= (TextView) findViewById(R.id.descDetailTxt);
    propTxt= (TextView) findViewById(R.id.propellantTxtDetail);
    img= (ImageView) findViewById(R.id.spacecraftImageDetail);



    //RECEIVE
    Intent i=this.getIntent();
    final String name=i.getExtras().getString("NAME_KEY");
    String propellant=i.getExtras().getString("PROPELLANT_KEY");
    String desc=i.getExtras().getString("DESCRIPTION_KEY");
    String imageurl=i.getExtras().getString("IMAGEURL_KEY");

    //BIND
     nameTxt.setText(name);
     propTxt.setText(propellant);
     descTxt.setText(desc);
     PicassoClient.downloadImage(this,imageurl,img);
  }
  }

Project Structure

Db Structure

【问题讨论】:

    标签: java android picasso searchview android-cardview


    【解决方案1】:

    1:首先创建包含 searchView 项目的菜单,然后在 MainActivity 类中扩展该菜单

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_action_search"
        android:orderInCategory="100"
        android:title="@string/action_search"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView" />
    

    【讨论】:

    • 这个答案还不够,还需要java代码。
    • 我也在寻找java代码功能
    • 我相应地添加了所有内容,但没有任何效果也没有错误,请帮助我
    • 检查适配器类中列表的大小!列表项是否存在
    • 您是否将解析列表添加到 MainActivity 类中的静态列表中?正如我在第 2 步的 cmets 中提到的那样
    【解决方案2】:
    4:inflate it and then create instance of y0ur adapter class and then call these methods 
        @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.search_menu, menu);
                SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
                SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
                        .getActionView();
                searchView.setSearchableInfo(searchManager
                        .getSearchableInfo(getComponentName()));
                searchView.setMaxWidth(Integer.MAX_VALUE);
                // listening to search query text change
                searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                    @Override
                    public boolean onQueryTextSubmit(String query) {
                        // filter recycler view when query submitted
                        customAdapter.filter(query, "role");
                        return false; }
                    @Override
                    public boolean onQueryTextChange(String query) {
                        // filter recycler view when text is changed
                        customAdapter.filter(query, "role");
                        return false; }});
                return true; }
    

    【讨论】:

    • customAdapter.filter(或)customAdapter.flterResult??
    • 在您的适配器类中添加此函数,如步骤 3 中所述@Sandy
    • customadapter.filter()
    • 您检查了适配器类中的列表大小吗??
    • 怎么查??
    【解决方案3】:
            2:  Create static list in Your MainActivity Class
    
                public class MainActivity extends AppCompatActivity {
    
                static String urlAddress="server_url";
                  public static ArrayList<Spacecraft> list = new ArrayList<>();
    
    
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
                    setSupportActionBar(toolbar);
                    //FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    
                    final GridView gv= (GridView) findViewById(R.id.gv);
                    new Downloader(MainActivity.this,urlAddress,gv).execute();
        // add the parse datalist in this static list by list.addall() then pass this list to custom adapter
            CustomAdpater customAdapter = new CustomAdpater(this,list);
    // then set the adapetr to your gridview
    
         }
        }     
    

    【讨论】:

      【解决方案4】:
      3:In Your Custom adapter class create function
       public void filter(String charText,String role) {
      
        if (role .equals("role")) {
      
                  charText = charText.toLowerCase(Locale.getDefault());
      
                  MainActivity.list.clear();
                  if (charText.length() == 0) {
      // char text is equlas to zero then add non filter list 
                      MainActivity.list.addAll(spacecrafts);
      
                  } else {
                      for (SpaceCraft spaceCraft : spacecrafts) {
                          if (charText.length() != 0 && 
           spaceCraft.name.toLowerCase(Locale.getDefault()).contains(charText)) {
                             MainActivity.list.add(spaceCraft);
                          } 
                      }
                  }
                  notifyDataSetChanged();
              }
      }
          }
      

      【讨论】:

      • spaceCraft.name 表示什么??它显示错误,当我更改 getName() 而不是清除错误时。
      • 搞错了..其实是sapacecraft.getname()
      【解决方案5】:
      add this log in your getcount() method
      then in logcat check it
       public class CustomAdapter extends BaseAdapter {
      
      Context c;
      ArrayList<Spacecraft> spacecrafts;
      
      public CustomAdapter(Context c, ArrayList<Spacecraft> spacecrafts) {
          this.c = c;
          this.spacecrafts = spacecrafts;
      }
      
      @Override
      public int getCount() {
         Log.d("size", "checksize: " +  spacecrafts.size());
      
          return spacecrafts.size();
      }
      

      【讨论】:

      • 添加这个以检查您的列表大小@Sandy
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 2018-12-09
      • 2016-12-02
      • 2012-12-11
      相关资源
      最近更新 更多