Skip to main content

Featured post

Simple RecyclerView example with filter option in Android

Hi Guys, Maybe you all are expert in terms of using RecyclerView in android. This blog is simple example for using filter option with RecyclerView adapter. As for now you will instantiate RecyclerView and set the adapter to RecyclerView as following way. RecyclerView list = (RecyclerView) findViewById(R.id.list); list.setLayoutManager(new LinearLayoutManager(this)); list.setHasFixedSize(true); ArrayList&ltNumber&gt numbers = new ArrayList&lt&gt(); String ONEs[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN"}; String TENs[] = {"ZERO", "TEN", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY", "HUNDRED"}; String HUNDREDS[] = {"ZERO", "HUNDRED", "TWO HUND

Simple RecyclerView example with filter option in Android

Hi Guys, Maybe you all are expert in terms of using RecyclerView in android. This blog is simple example for using filter option with RecyclerView adapter.



As for now you will instantiate RecyclerView and set the adapter to RecyclerView as following way.
RecyclerView list = (RecyclerView) findViewById(R.id.list);
list.setLayoutManager(new LinearLayoutManager(this));
list.setHasFixedSize(true);
ArrayList<Number> numbers = new ArrayList<>();
String ONEs[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN"};
String TENs[] = {"ZERO", "TEN", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY",  "SEVENTY", "EIGHTY", "NINETY", "HUNDRED"};
String HUNDREDS[] = {"ZERO", "HUNDRED", "TWO HUNDRED", "THREE HUNDRED", "FOUR HUNDRED", "FIVE HUNDRED", "SIX HUNDRED", "SEVEN HUNDRED", "EIGHT HUNDRED", "NINE HUNDRED", "THOUSAND"};
for (int i = 0; i <= 10; i++) {
    Number number = new Number();
    number.setONEs(i+"");
    number.setTENs(i * 10+"");
    number.setHUNDREDs(i * 100+"");
    number.setTextONEs(ONEs[i]);
    number.setTextTENs(TENs[i]);
    number.setTextHUNDREDs(HUNDREDS[i]);
    this.numbers.add(number);
}
adapter = new NumbersAdapter(this.numbers);
list.setAdapter(adapter);
And also you will create your options menu and inflate SearchView as following way.
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        final MenuItem item = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
        searchView.setOnQueryTextListener(this);
        return true;
    }
So by above code your activity/fragment will implement SearchView.OnQueryTextListener. So you will have onQueryTextChange method from this listener. Just change this method like following to start filtering with this adapter.
    @Override
    public boolean onQueryTextChange(String newText) {
        final List<Number> filteredModelList = filter(numbers, newText);
        Log.v("App", newText + ", " + numbers.size() + ", " + filteredModelList.size());
        adapter.animateTo(filteredModelList);
        list.scrollToPosition(0);
        return true;
    }
The filter method from above code will return the filtered list as following.
    private List<Number> filter(List<Number> numbers, String query) {
        query = query.toLowerCase();

        ArrayList<Number> filteredCompanyList = new ArrayList<>();
        for (Number client : numbers) {
            final String textOne = client.getTextONEs().toLowerCase();
            final String textTen = client.getTextTENs().toLowerCase();
            final String textHundred = client.getTextHUNDREDs().toLowerCase();
            final String TENs = client.getTENs();
            final String ONEs = client.getONEs();
            final String HUNDREDs = client.getHUNDREDs();
            if (textOne.contains(query) || TENs.contains(query) || ONEs.contains(query) || HUNDREDs.contains(query) || textTen.contains(query) || textHundred.contains(query)) {
                filteredCompanyList.add(client);
            }
        }
        return filteredCompanyList;
    }
And your adapter will have the following related methods to perform this filter with animation.
    public void animateTo(List<Number> models) {
        applyAndAnimateRemovals(models);
        applyAndAnimateAdditions(models);
        applyAndAnimateMovedItems(models);
    }

    private void applyAndAnimateRemovals(List<Number> newModels) {
        for (int i = numbers.size() - 1; i >= 0; i--) {
            final Number model = numbers.get(i);
            if (!newModels.contains(model)) {
                removeItem(i);
            }
        }
    }

    private void applyAndAnimateAdditions(List<Number> newModels) {
        for (int i = 0, count = newModels.size(); i < count; i++) {
            final Number model = newModels.get(i);
            if (!numbers.contains(model)) {
                addItem(i, model);
            }
        }
    }

    private void applyAndAnimateMovedItems(List<Number> newModels) {
        for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
            final Number model = newModels.get(toPosition);
            final int fromPosition = numbers.indexOf(model);
            if (fromPosition >= 0 && fromPosition != toPosition) {
                moveItem(fromPosition, toPosition);
            }
        }
    }

    public Number removeItem(int position) {
        final Number model = numbers.remove(position);
        notifyItemRemoved(position);
        return model;
    }

    public void addItem(int position, Number model) {
        numbers.add(position, model);
        notifyItemInserted(position);
    }

    public void moveItem(int fromPosition, int toPosition) {
        final Number model = numbers.remove(fromPosition);
        numbers.add(toPosition, model);
        notifyItemMoved(fromPosition, toPosition);
    }


I hope this post is useful to you. kindly share your feedback as comment here.


Simple RecyclerView example in Android

Simple recyclerview example with checkbox in Android

Dynamically change ListView to GridView and Vice Versa using RecyclerView

Source code on GitHub



Thank You



Comments

  1. This comment has been removed by the author.

    ReplyDelete

  2. Very nice job... Thanks for sharing this amazing and educative blog post! ExcelR Digital Marketing Classes In Pune

    ReplyDelete
  3. Awesome post! This is helpful post. This article is clear and with lots of useful information
    Social Media Services AGency in India

    ReplyDelete
  4. Ogen Infosystem is one of the best Website Designing and PPC Company in Delhi, India. Here you will well experience web designers and developers to provide a great website for your business. Our PPC Experts generate leads to your business products at an affordable price.
    Website Designing Company in Delhi

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Thanks for the Valuable information.Really useful information. Thank you so much for sharing. It will help everyone.

    Full Stack Training in Delhi
    FOR MORE INFO:

    ReplyDelete
  7. Informative blog post,
    Digital Marketing Training in KPHB with 100% Internships & Job Assistance.

    ReplyDelete
  8. Really an awesome article. Informative and knowledgeable content. Keep sharing more stuff like this. Thank you.
    Online Data Science Training in Hyderabad
    Online Data Science Course in Hyderabad

    ReplyDelete
  9. Very nice post. best digital marketing courses in coimbatore, digital marketing training in coimbatore,digital marketing course in coimbatore,best digital marketing course in coimbatore,best digital marketing institute in coimbatore,digital marketing training institute in coimbatore,digital marketing course fees in coimbatore,seo course in coimbatore,digital marketing institute in coimbatore,best digital marketing training in coimbatore,digital marketing classes in coimbatore,digital marketing course training in coimbatore,digital marketing training course in coimbatore, digital marketing training centres in coimbatore
    digital marketing training institute in coimbatore

    ReplyDelete
  10. Oh wow I came here from a random link from another website. This is so informative content. There are many things to learn. I really appreciate your efforts. All concepts are so brief.
    Online personalized medical bag

    ReplyDelete
  11. Outstanding blog thanks for sharing such wonderful blog with us ,after long time came across such knowledgeable blog. keep sharing such informative blog with us.
    Learn more digital marketing course in Coimbatore

    ReplyDelete
  12. Thanks for the Valuable information.Really useful information
    fullstacktrainingcenter

    ReplyDelete

Post a Comment

Popular posts from this blog

Simple example of OCRReader in Android.

Hi Friends, Maybe you all heard/used text scanning using camera feature or extracting text from Image. But this sample made it very easy for you. You can made it in very simple line of code. You can download the source code from OCRSample and import the library as a module into your project. Example usage : MainActivity.java public class MainActivity extends AppCompatActivity { private TextView textView; private final int CAMERA_SCAN_TEXT = 0; private final int LOAD_IMAGE_RESULTS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSele

Simple example of using Spinner in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Spinner in Android. In Kotlin we don't need to declare and initialize Spinner. We can simply access the id of Spinner from xml. Ex : import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import android.widget.Toast.LENGTH_LONG import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //String array. val myStrings = arrayOf("One", "Two", "Three", "Four", "Five") //Adapter for spinner mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_i

Set limit for fraction in decimal numbers in EditText

            Already we know that we can set which type of input the edittext should accept from user using android:inputType="numberDecimal" But there is no predefined function to set the limit for the edittext to How many digit it should accept after the decimal point from user . We can achieve this by using TextWatcher . Full code example. Following program creates a Decimal Filter. DecimalFilter.java import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import android.widget.EditText; public class DecimalFilter implements TextWatcher { int count= -1 ; EditText et; Activity activity; public DecimalFilter(EditText edittext, Activity activity) { et = edittext; this.activity = activity; } public void afterTextChanged(Editable s) { if (s.length() > 0) { String str = et.getText().toString(); et.setOnKeyListener(new OnKeyL