2016-05-05 2 views
0

Я извлекаю данные из массива JSON и отображаю его на RecyclerView. Я хочу реализовать панель поиска, искать и отображать элементы из этого RecyclerView.Как добавить searchBar в RecyclerView с картами

MyRecyclerAdapter.java

public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.CustomViewHolder> { 
private List<FeedItem> feedItemList; 
private Context mContext; 

public MyRecyclerAdapter(Context context, List<FeedItem> feedItemList) { 
    this.feedItemList = feedItemList; 
    this.mContext = context; 
} 

@Override 
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { 
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, null); 

    CustomViewHolder viewHolder = new CustomViewHolder(view); 
    return viewHolder; 
} 

@Override 
public void onBindViewHolder(CustomViewHolder customViewHolder, int i) { 
    FeedItem feedItem = feedItemList.get(i); 



    //Setting text view title 
    customViewHolder.textView.setText(Html.fromHtml(feedItem.getTitle())); 
    customViewHolder.contactTV.setText(Html.fromHtml(feedItem.getContact())); 
    customViewHolder.emailTV.setText(Html.fromHtml(feedItem.getEmail())); 
    customViewHolder.eventname.setText(Html.fromHtml(feedItem.getEventname())); 
    customViewHolder.collegename.setText(Html.fromHtml(feedItem.getCollegename())); 

    //Handle click event on both title and image click 
    customViewHolder.textView.setOnClickListener(clickListener); 

    customViewHolder.textView.setTag(customViewHolder); 

    // Set the view to fade in 
    //setFadeAnimation(customViewHolder.itemView); 

} 

/*private void setFadeAnimation(View view) { 
    AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f); 
    anim.setDuration(800); 
    view.startAnimation(anim); 
}*/ 

View.OnClickListener clickListener = new View.OnClickListener() { 
    @Override 
    public void onClick(View view) { 
     CustomViewHolder holder = (CustomViewHolder) view.getTag(); 
     int position = holder.getPosition(); 

     FeedItem feedItem = feedItemList.get(position); 
     Toast.makeText(mContext, feedItem.getTitle(), Toast.LENGTH_SHORT).show(); 
    } 
}; 

@Override 
public int getItemCount() { 
    return (null != feedItemList ? feedItemList.size() : 0); 
} 
public class CustomViewHolder extends RecyclerView.ViewHolder 
{ 
    protected TextView textView ,contactTV, emailTV, collegename, eventname; 
    protected ImageView callIcon, mailIcon, eventIcon; 

    public CustomViewHolder(View view) 
    { 
     super(view); 
     this.textView = (TextView) view.findViewById(R.id.title); 
     this.contactTV = (TextView) view.findViewById(R.id.contactTV); 
     this.emailTV = (TextView) view.findViewById(R.id.emailTV); 
     this.eventname = (TextView) view.findViewById(R.id.eventname); 
     this.collegename = (TextView) view.findViewById(R.id.collegename); 

     this.callIcon = (ImageView) view.findViewById(R.id.callIcon); 
     this.mailIcon = (ImageView) view.findViewById(R.id.mailIcon); 
     this.eventIcon = (ImageView) view.findViewById(R.id.eventIcon); 
    } 
} 
} 

AdminActivity.java

public class AdminActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener { 

private static final String TAG = "userList"; 
private List<FeedItem> feedsList; 
private RecyclerView mRecyclerView; 
private MyRecyclerAdapter adapter; 
private ProgressBar progressBar; 
private TextView ParticipantsCounts; 
int count=0; 
private int number; 

private SwipeRefreshLayout swipeRefreshLayout; 

private final String url="http://bmcctroika.hol.es/get-data.php";; 

private int offSet = 0; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    ActionBar actionBar = getSupportActionBar(); 
    actionBar.setDisplayHomeAsUpEnabled(true); 
    actionBar.setDisplayShowHomeEnabled(true); 


    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_admin); 
    // Initialize recycler view 
    mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); 
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); 

    progressBar = (ProgressBar) findViewById(R.id.progress_bar); 
    progressBar.setVisibility(View.VISIBLE); 

    ParticipantsCounts= (TextView) findViewById(R.id.ParticipantsCount); 

    // Downloading data from below url 
    new AsyncHttpTask().execute(url); 
    new AsyncHttpRecordTask().execute(url); 
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout); 

    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { 
     @Override 
     public void onRefresh() { 
      refreshitems(); 
     } 
    }); 
} 

private void refreshitems() 
{ 
    new AsyncHttpTask().execute(url); 
    new AsyncHttpRecordTask().execute(url); 
} 

@Override 
public void onRefresh() 
{ 
    new AsyncHttpTask().execute(url); 
    new AsyncHttpRecordTask().execute(url); 
} 

public class AsyncHttpTask extends AsyncTask<String, Void, Integer> { 

    @Override 
    protected void onPreExecute() { 
     setProgressBarIndeterminateVisibility(true); 
    } 

    @Override 
    protected Integer doInBackground(String... params) { 
     Integer result = 0; 
     HttpURLConnection urlConnection; 
     try { 
      URL url = new URL(params[0]); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      int statusCode = urlConnection.getResponseCode(); 

      // 200 represents HTTP OK 
      if (statusCode == 200) 
      { 
       BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 
       StringBuilder response = new StringBuilder(); 
       String line; 
       while ((line = r.readLine()) != null) 
       { 
        response.append(line); 
       } 
       parseResult(response.toString()); 
       result = 1; // Successful 

      } else { 
       result = 0; //"Failed to fetch data!"; 
      } 
     } catch (Exception e) { 
      Log.d(TAG, e.getLocalizedMessage()); 
     } 
     return result; //"Failed to fetch data!"; 
    } 

    @Override 
    protected void onPostExecute(Integer result) 
    { 
     // Download complete. 
     progressBar.setVisibility(View.GONE); 
     if (result == 1) 
     { 
      adapter = new MyRecyclerAdapter(AdminActivity.this, feedsList); 
      mRecyclerView.setAdapter(adapter); 
     } else 
     { 
      Toast.makeText(AdminActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show(); 
     } 
     swipeRefreshLayout.setRefreshing(false); 
    } 
} 

private void parseResult(String result) 
{ 
    try 
    { 
     JSONObject response = new JSONObject(result); 
     JSONArray posts = response.optJSONArray("result"); 
     feedsList = new ArrayList<>(); 
     for (int i = 0; i < posts.length(); i++) 
     { 
      JSONObject post = posts.optJSONObject(i); 
      FeedItem item = new FeedItem(); 
      item.setTitle(post.optString("fullname")); 
      item.setContact(post.optString("contactno")); 
      item.setEmail(post.optString("emailaddress")); 
      item.setEventname(post.optString("eventname")); 
      item.setCollegename(post.optString("collegename")); 
      feedsList.add(item); 
     } 
     //ParticipantsCounts.setText(String.valueOf(posts.length())); 
    } 
    catch (JSONException e) 
    { 
     e.printStackTrace(); 
    } 
} 
public class AsyncHttpRecordTask extends AsyncTask<String, Void, Integer> { 


    @Override 
    protected Integer doInBackground(String... params) { 
     Integer result = 0; 
     HttpURLConnection urlConnection; 
     try { 
      URL url = new URL(params[0]); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      int statusCode = urlConnection.getResponseCode(); 

      // 200 represents HTTP OK 
      if (statusCode == 200) 
      { 
       BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 
       StringBuilder response = new StringBuilder(); 
       String line; 
       while ((line = r.readLine()) != null) 
       { 
        response.append(line); 
       } 
       parseResultnum(response.toString()); 
       result = 1; // Successful 

      } else { 
       result = 0; //"Failed to fetch data!"; 
      } 
     } catch (Exception e) { 
      Log.d(TAG, e.getLocalizedMessage()); 
     } 
     return result; //"Failed to fetch data!"; 
    } 
} 

private void parseResultnum(String result) 
{ 
    try 
    { 
     JSONObject response = new JSONObject(result); 
     JSONArray posts = response.optJSONArray("result"); 
     ParticipantsCounts.setText("No. of Participants : "+String.valueOf(posts.length())); 
    } 
    catch (JSONException e) 
    { 
     e.printStackTrace(); 
    } 
} 
} 

ответ

0

Вы можете легко добавить SearchView к вашему ActionBar как пункт меню с ActionView (example). Затем на основе SearchView.OnQueryTextListener вы сможете применить поисковый запрос к вашему адаптеру. Что именно блокирует вас на этом пути?

+0

Я не знаю, как реализовать его на recyclerview , поэтому, если вы можете добавить решение для этого в качестве ответа, было бы здорово, спасибо. –

+0

Пожалуйста, проверьте [это] (http://stackoverflow.com/a/29792313/1565731) ответ и дайте мне знать, если у вас все еще есть вопросы –

0

Попробуйте этот код

1) MainActivity.class

public class MainActivity extends AppCompatActivity { 

    private static final String TAG = "userList"; 
    private RecyclerView mRecyclerView; 
    private MyRecyclerAdapter adapter; 
    private TextView ParticipantsCounts; 
    private ArrayList<HashMap<String, String>> list; 
    private HashMap<String, String> listsub; 
    private Context context; 
    private SwipeRefreshLayout swipeRefreshLayout; 

    private final String urlmain = "http://bmcctroika.hol.es/get-data.php"; 
    private ProgressDialog pDialog; 
    private Integer result = 0; 
    private HttpURLConnection urlConnection; 
    private URL url; 
    private int statusCode; 
    private StringBuilder response; 
    private BufferedReader r; 
    private String line; 
    private JSONArray posts; 
    private SearchView search; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 
     context = MainActivity.this; 

     search = (SearchView) findViewById(R.id.search); 

     // Initialize recycler view 
     mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view); 
     ParticipantsCounts = (TextView) findViewById(R.id.ParticipantsCount); 

     // Downloading data from below url 
     new AsyncHttpTask().execute(urlmain); 

     swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout); 
     swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { 
      @Override 
      public void onRefresh() { 
       refreshitems(); 
       swipeRefreshLayout.setRefreshing(false); 
      } 
     }); 
    } 

    private void refreshitems() { 

     new AsyncHttpTask().execute(urlmain); 
    } 

    public class AsyncHttpTask extends AsyncTask<String, Void, Integer> { 

     @Override 
     protected void onPreExecute() { 

      pDialog = new ProgressDialog(context); 
      pDialog.setMessage("Please wait"); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(false); 
      pDialog.show(); 
     } 

     @Override 
     protected Integer doInBackground(String... params) { 

      data1(params); 

      return result; //"Failed to fetch data!"; 
     } 

     @Override 
     protected void onPostExecute(Integer result) { 

      pDialog.dismiss(); 

      // Download complete. 
      if (result == 1) { 

       ParticipantsCounts.setText("No. of Participants : " + String.valueOf(posts.length())); 

       if (list.size() > 0) { 
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mRecyclerView.getContext())); 
        adapter = new MyRecyclerAdapter(mRecyclerView.getContext(), list); 
        mRecyclerView.setAdapter(adapter); 

        search.setOnQueryTextListener(listener); 

       } else { 
        Toast.makeText(context, "No list found!", Toast.LENGTH_SHORT).show(); 

       } 
      } else { 
       Toast.makeText(context, "Failed to fetch data!", Toast.LENGTH_SHORT).show(); 
      } 
     } 
    } 

    SearchView.OnQueryTextListener listener = new SearchView.OnQueryTextListener() { 
     @Override 
     public boolean onQueryTextSubmit(String query) { 
      return false; 
     } 

     @Override 
     public boolean onQueryTextChange(String query) { 
      query = query.toLowerCase(); 

      final ArrayList<HashMap<String, String>> filteredList = new ArrayList<>(); 

      for (int i = 0; i < list.size(); i++) { 

       final String text = list.get(i).toString().toLowerCase(); 
       if (text.contains(query)) { 

        filteredList.add(list.get(i)); 
       } 
      } 

      mRecyclerView.setLayoutManager(new LinearLayoutManager(mRecyclerView.getContext())); 
      adapter = new MyRecyclerAdapter(mRecyclerView.getContext(), filteredList); 
      mRecyclerView.setAdapter(adapter); 
      adapter.notifyDataSetChanged(); 
      return true; 
     } 
    }; 


    private void data1(String... params) { 

     try { 
      url = new URL(params[0]); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      statusCode = urlConnection.getResponseCode(); 

      // 200 represents HTTP OK 
      if (statusCode == 200) { 
       r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 
       response = new StringBuilder(); 

       while ((line = r.readLine()) != null) { 
        response.append(line); 
       } 

       parseResult(response.toString()); 
       result = 1; // Successful 

      } else { 
       result = 0; //"Failed to fetch data!"; 
      } 
     } catch (Exception e) { 
      Log.d(TAG, e.getLocalizedMessage()); 
     } 
    } 


    private void parseResult(String result) { 
     try { 
      JSONObject response = new JSONObject(result); 
      posts = response.optJSONArray("result"); 
      list = new ArrayList<>(); 
      Log.e("posts", "posts" + posts.length()); 
      for (int i = 0; i < posts.length(); i++) { 
       JSONObject post = posts.optJSONObject(i); 
       listsub = new HashMap<>(); 
       listsub.put("fullname", post.optString("fullname")); 
       listsub.put("contactno", post.optString("contactno")); 
       listsub.put("emailaddress", post.optString("emailaddress")); 
       listsub.put("eventname", post.optString("eventname")); 
       listsub.put("collegename", post.optString("collegename")); 
       list.add(listsub); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

2) activity_main.xml

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


    <SearchView 
     android:id="@+id/search" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_vertical" 
     android:layout_marginTop="10dp" 
     android:background="@android:color/holo_blue_dark" 
     android:hint="Search here" 
     android:paddingLeft="20dp" 
     android:paddingRight="20dp" 
     android:textColor="@android:color/black" 
     android:textColorHint="@android:color/black" 
     android:textSize="15dp" /> 

    <android.support.v4.widget.SwipeRefreshLayout 
     android:id="@+id/swipe_refresh_layout" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:orientation="vertical" 
      android:layout_margin="10dp"> 

      <TextView 
       android:id="@+id/ParticipantsCount" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:textColor="@android:color/black" 
       android:textSize="15dp" /> 

      <android.support.v7.widget.RecyclerView 
       android:id="@+id/recycler_view" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content"> 

      </android.support.v7.widget.RecyclerView> 
     </LinearLayout> 
    </android.support.v4.widget.SwipeRefreshLayout> 
</LinearLayout> 

3) MyRecyclerAdapter.class

public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ViewHolder> { 

    private ArrayList<HashMap<String, String>> list; 
    private HashMap<String, String> listsub; 
    private Context mContext; 
    View view; 

    public static class ViewHolder extends RecyclerView.ViewHolder { 
     public final View mView; 

     public TextView textView, contactTV, emailTV, collegename, eventname; 


     public ViewHolder(View view) { 
      super(view); 

      mView = view; 

      this.textView = (TextView) view.findViewById(R.id.title); 
      this.contactTV = (TextView) view.findViewById(R.id.contactTV); 
      this.emailTV = (TextView) view.findViewById(R.id.emailTV); 
      this.eventname = (TextView) view.findViewById(R.id.eventname); 
      this.collegename = (TextView) view.findViewById(R.id.collegename); 

     } 
    } 

    public MyRecyclerAdapter(Context context, ArrayList<HashMap<String, String>> feedItemList) { 
     list = feedItemList; 
     this.mContext = context; 
    } 

    @Override 
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 

     view = LayoutInflater.from(parent.getContext()) 
       .inflate(R.layout.list_row, parent, false); 

     return new ViewHolder(view); 
    } 

    @Override 
    public void onBindViewHolder(final ViewHolder holder, final int postion) { 


     listsub = list.get(postion); 

     //Setting text view title 
     holder.textView.setText(listsub.get("fullname")); 
     holder.contactTV.setText(listsub.get("contactno")); 
     holder.emailTV.setText(listsub.get("emailaddress")); 
     holder.eventname.setText(listsub.get("eventname")); 
     holder.collegename.setText(listsub.get("collegename")); 

    } 


    @Override 
    public int getItemCount() { 
     return list.size(); 
    } 

} 

4) list_row .xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_margin="10dp"> 


    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/title" 
     android:textSize="13dp" 
     android:textColor="@android:color/black" /> 

     <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/contactTV" 
     android:textSize="13dp" 
     android:textColor="@android:color/black" /> 

    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/emailTV" 
     android:textSize="13dp" 
     android:textColor="@android:color/black" /> 

    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/eventname" 
     android:textSize="13dp" 
     android:textColor="@android:color/black" /> 

    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/collegename" 
     android:textSize="13dp" 
     android:textColor="@android:color/black" /> 

    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="1dp" 
     android:background="@android:color/black" /> 

</LinearLayout> 
0

Это именно то, что вы ищете, это полный пример с поиском и recyclerview

private RecyclerView mRecyclerView; 
private ExampleAdapter mAdapter; 
private List<ExampleModel> mModels; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    final View view = inflater.inflate(R.layout.fragment_main, container, false); 

    mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); 

    return view; 
} 

@Override 
public void onViewCreated(View view, Bundle savedInstanceState) { 
    super.onViewCreated(view, savedInstanceState); 
    setHasOptionsMenu(true); 

    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); 

    mModels = new ArrayList<>(); 

    for (String movie : MOVIES) { 
     mModels.add(new ExampleModel(movie)); 
    } 

    mAdapter = new ExampleAdapter(getActivity(), mModels); 
    mRecyclerView.setAdapter(mAdapter); 
} 

Для более увидеть это Searchable-RecyclerView-Demo

Смежные вопросы