如何在Android中实现searchview过滤器?

时间:2018-08-03 08:38:09

标签: java android picasso searchview android-cardview

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

MainActivity Screen

MainActivity.java

 <div class="container">
    <div class="row">        
        <p>Some text heree</p>
       <img src="images/hand.jpg"class="img-responsive"/>      
        <p>Some text here </p>
        <button>CTA</button>
   </div>
</div> 

spacecraft.java(Data_Object)

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();

}

}

Connector.java

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;
}
}

DataParser.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;
}
}

Downloader.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;
}
}

CustomAdapter.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 {
}
}

PicassoClient.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);
 }
 } 

content_main

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);
    }
}
}

model.xml

   <?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>

这是用于显示产品说明的detailactivity

DetailActivity Screen

activity_detail

  <?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.java

<?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" />

Project Structure

Db Structure

5 个答案:

答案 0 :(得分:0)

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" />

答案 1 :(得分:0)

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; }

答案 2 :(得分:0)

        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

     }
    }     

答案 3 :(得分:0)

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();
        }
}
    }

答案 4 :(得分:0)

.exe