I write this code for search in recyclerview with edit text but, when I run the application and input a text that I need to search about it on the edit text in the first letter the recycler content not changed and when I input the second Letter the RecyclerView become empty.
how can I filter the recycler? what is the wrong in my code ?
xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FamilyActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="#+id/search"
android:layout_width="294dp"
android:layout_height="70dp"
android:layout_marginTop="-20dp"
android:hint="Search ..."
android:drawableLeft="#drawable/ic_search_black_24dp"
/>
<Button
android:id="#+id/add"
android:layout_width="54dp"
android:layout_height="match_parent"
android:layout_marginLeft="35dp"
android:drawableTop="#drawable/ic_person_add_black_24dp"
android:onClick="add_new_family"
tools:ignore="OnClick" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="50dp"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
code in main activity:
public class FamilyActivity extends AppCompatActivity {
RecyclerView recyclerView;
FamilyAdapter familyAdapter;
Button add_family;
EditText search;
List<Family> familyList;
String patientID = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_family);
add_family=(Button)findViewById(R.id.add);
search =(EditText)findViewById(R.id.search);
familyList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Bundle extras = getIntent().getExtras();
if (extras != null) {
patientID = extras.getString("ID");
}
loadFamilyList();
//adding some items to our list
//creating recyclerView adapter
FamilyAdapter adapter = new FamilyAdapter(this, familyList);
//setting adapter to recyclerView
recyclerView.setAdapter(adapter);
addTextListener();
}
public void addTextListener(){
search.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final List<Family> filteredList = new ArrayList<>();
for (int i = 0; i < familyList.size(); i++) {
final String text = familyList.get(i).toString().toLowerCase();
if (text.contains(query)) {
filteredList.add(familyList.get(i));
}
}
recyclerView.setLayoutManager(new LinearLayoutManager(FamilyActivity.this));
FamilyAdapter fadapter = new FamilyAdapter(FamilyActivity.this,filteredList);
recyclerView.setAdapter(fadapter);
fadapter.notifyDataSetChanged(); // data set changed
}
});
}
code in adapter:
public class FamilyAdapter extends RecyclerView.Adapter<FamilyAdapter.FamilyViewHolder> {
private Context context;
private List<Family> familyList;
private List<Family> familyListFull;
public FamilyAdapter(Context context, List<Family> familyList) {
this.context = context;
this.familyList = familyList;
familyListFull=new ArrayList<>(familyList);
}
#NonNull
#Override
public FamilyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_layout, null);
return new FamilyViewHolder(view);
}
#Override
public void onBindViewHolder(FamilyViewHolder familyViewHolder, final int position) {
Family family = familyList.get(position);
familyViewHolder.textViewTitle.setText(family.getName());
familyViewHolder.familyLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on : " + familyList.get(position));
String name = familyList.get(position).getName();
String num = familyList.get(position).getNum();
Intent intent = new Intent(context, Chatting.class);
intent.putExtra("num", num);
intent.putExtra("name", name);
context.startActivity(intent);
}
});
familyViewHolder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context );
builder.setTitle("Delete");
builder.setMessage("Are you sure you want to delete this one ")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
RemoveFamilyMember(position);
}
}).setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
builder.setCancelable(true);
}
});
AlertDialog alert=builder.create();
alert.show();
}
});
}
you can try something like this I think this might work, I haven't tested it but I think that making a new adapter everytime that the edittext has something in it is a bad idea. and if you get to the point back to where the query is equal to "" empty string then you should make the fileterd list back into the whole list which I didn't put in there
public class FamilyActivity extends AppCompatActivity {
RecyclerView recyclerView;
FamilyAdapter familyAdapter;
Button add_family;
EditText search;
List<Family> familyList;
List<Family> filteredList;
String patientID = "";
FamilyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_family);
add_family=(Button)findViewById(R.id.add);
search =(EditText)findViewById(R.id.search);
familyList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
Bundle extras = getIntent().getExtras();
if (extras != null) {
patientID = extras.getString("ID");
}
loadFamilyList();
filteredList = new ArrayList<>(familyList);
//adding some items to our list
//creating recyclerView adapter
adapter = new FamilyAdapter(this, filteredList);
//setting adapter to recyclerView
recyclerView.setAdapter(adapter);
addTextListener();
}
public void addTextListener(){
search.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
filteredList = new ArrayList<>();
for (int i = 0; i < familyList.size(); i++) {
final String text = familyList.get(i).toString().toLowerCase();
if (text.contains(query)) {
filteredList.add(familyList.get(i));
}
}
recyclerView.removeAllViews();;
adapter.notifyDataSetChanged(); // data set changed
}
});
}
editTextSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
private void filter(String text) {
ArrayList<Model> newList = new ArrayList<>();
for (Model item : mModelList) {
if (item.getTitle().contains(text)){
newList.add(item);
}
}
yourAdapter.setFilter(newList);
}
Related
I am using com.github.mancj:MaterialSearchBar:+ dependency in my app to search data in my SQLite database. It does load suggestions based on the data i have in the database but when a user clicks on one of the suggestion and confirms it by clicking the search icon in the keyboard nothing gets displayed, the adapter is not being called to display the result. below is my search activity
recyclerView = findViewById(R.id.hyme_list);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
materialSearchBar = findViewById(R.id.searchBar);
database = new Database(this);
materialSearchBar.setHint("Search here");
materialSearchBar.setCardViewElevation(10);
loadSuggestList();
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
List<String> sugest = new ArrayList<>();
for (String search: suggestList) {
if (search.toUpperCase().contains(materialSearchBar.getText().toUpperCase()))
sugest.add(search);
}
materialSearchBar.setLastSuggestions(sugest);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
if (!enabled){
searchAdapter = new SearchAdapter(getBaseContext(),database.getSongs());
recyclerView.setAdapter(searchAdapter);
}
}
#Override
public void onSearchConfirmed(CharSequence text) {
startSearch(text.toString());
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
searchAdapter = new SearchAdapter(this,database.getSongs());
recyclerView.setAdapter(searchAdapter);
}
private void startSearch(String text) {
searchAdapter = new SearchAdapter(this,database.getSongByName(text));
recyclerView.setAdapter(searchAdapter);
}
private void loadSuggestList() {
suggestList = database.getTitle();
materialSearchBar.setLastSuggestions(suggestList);
}
I am trying to implement a search filter on complex object data in recyclerview when I type in the Edit text first-time it works properly, but whenever I try to delete characters by pressing back-space in order to modify our search- I am repeatedly failing in this regard.
I can only search once !!
etSearch = (EditText) findViewById(R.id.edittext);
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
myAdapter.filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
now the filter code
public void filter(CharSequence sequence) {
ArrayList<user> temp = new ArrayList<>();
if (!TextUtils.isEmpty(sequence)) {
for (user s : arr) {
Log.d("users ",s.getName());
if (s.getName().toLowerCase().contains(sequence)) {
temp.add(s);
}
}
} else {
temp.addAll(arrcopy);
}
arr.clear();
arr.addAll(temp);
notifyDataSetChanged();
temp.clear();
}
Whats the issue, I cannot search more than once-any help is appreciated
Here is my Adapter class
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder>
{
Context cxt;
ArrayList<user> arr;
ArrayList<user> arrcopy;
DatabaseReference dref;
MyAdapter myAdapter;
public MyAdapter(Context context, ArrayList<user> arrayList)
{
cxt = context;
arr = arrayList;
arrcopy=new ArrayList<>(arr);
Log.d("Very start arr",arr.toString());
notifyDataSetChanged();
dref = FirebaseDatabase.getInstance().getReference("users");
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(cxt).inflate(R.layout.item_chatroom,viewGroup,false);
myAdapter = new MyAdapter(cxt, arr);
Log.d("Inside MyHolder arr",arr.toString());
return new MyHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyHolder myHolder,final int i) {
final String name = arr.get(i).getUsername();
String pic=arr.get(i).getPic();
final String mail=arr.get(i).getEmail();
myHolder.name.setText(name);
Glide.with(myHolder.profile.getContext())
.load(pic)
.into(myHolder.profile);
myHolder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(cxt,MainActivity.class);
intent.putExtra("Id",arr.get(i).getId());
intent.putExtra("Name",arr.get(i).getUsername());
cxt.startActivity(intent);
}
});
myHolder.info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final SweetAlertDialog pDialog = new SweetAlertDialog(cxt, SweetAlertDialog.SUCCESS_TYPE);
pDialog.setTitleText("User Information e-mail ID");
pDialog.setContentText("Name: "+name+"\n\n E-mail: "+mail);
pDialog.setConfirmText("Ok");
pDialog.show();
}
});
}
#Override
public int getItemCount() {
return arr.size();
}
class MyHolder extends RecyclerView.ViewHolder
{
TextView name;
ImageView profile,info;
public MyHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.txv);
profile=itemView.findViewById(R.id.profile);
info=itemView.findViewById(R.id.profileinfo);
}
}
public void filter(CharSequence sequence) {
ArrayList<user> temp = new ArrayList<>();
if (!TextUtils.isEmpty(sequence)) {
for (user s : arr) {
if (s.getName().toLowerCase().contains(sequence)) {
temp.add(s);
}
}
} else {
temp.addAll(arrcopy);
}
arr.clear();
arr.addAll(temp);
notifyDataSetChanged();
temp.clear();
}
}
I assume the arrcopy is the copy of arr like:
ArrayList<User> arrcopy = new ArrayList<>(arr);
If you modify arr, it also change the content of arrcopy. And when no result matches, the arr is empty, so is the arrcopy.
else {
temp.addAll(arrcopy);
}
arr.clear();
arr.addAll(temp);
Now temp is empty, the arr data you set for adapter is empty, so issues happens.
Please try:
In MyAdapter:
Context cxt;
ArrayList<user> arr;
public MyAdapter(Context context) {
cxt = context;
dref = FirebaseDatabase.getInstance().getReference("users");
}
public void setData(ArrayList<User> arrayList) {
arr = arrayList;
notifyDataSetChanged();
}
Also put the filter() in your activity/fragment:
protected void onCreate(final Bundle savedInstanceState) {
etSearch = (EditText) findViewById(R.id.edittext);
etSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
etSearch.requestFocus();
}
});
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
filter(etSearch.getText().toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
etSearch.clearFocus();
mAdapter = new MyAdapter(this);
mAdapter.setData(arrayList);
mRecyclerView.setAdapter(mAdapter);
...
}
public void filter(String input) {
if (!TextUtils.isEmpty(input)) {
ArrayList<User> temp = new ArrayList<>();
for (user s : arr) {
if (s.getName().toLowerCase().contains(input)) {
temp.add(s);
}
}
mAdapter.setData(temp);
} else {
mAdapter.setData(arr);
}
mAdapter.notifyDataSetChanged();
}
Implement Filterable in your MyAdapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder>
implements Filterable {
// change MyObject to user class
//replace myObjects with arr and reservedList with arrcopy
Context cxt;
ArrayList<MyObject> myObjects;
ArrayList<MyObject> reservedList;
DatabaseReference dref;
public MyAdapter(Context context, ArrayList<MyObject> arrayList){
cxt = context;
myObjects = arrayList;
reservedList = arrayList
Log.d("Very start arr",myObjects.toString());
// notifyDataSetChanged();
dref = FirebaseDatabase.getInstance().getReference("users");
}
//...
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString().toLowerCase();
if (!charString.isEmpty()) {
List<MyObject> filteredList = new ArrayList<>();
for (MyObject row : reservedList) {
if (row.getName().toLowerCase().contains(charString)){
filteredList.add(row);
}
}
myObjects = filteredList;
} else {
myObjects = reservedList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = myObjects;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
myObjects = (ArrayList<MyObject>) filterResults.values;
notifyDataSetChanged();
}
};
}
and from your activity
etSearch = (EditText) findViewById(R.id.edittext);
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
myAdapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
});
I want to search data with search bar data I have received from firebase database into recyclerview...
I am trying to search data through edit text and search from received from database text . But failed can u please tell me how can I do it here is my code. I have tried more than 4 hours but :(
eco.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="#+id/button"
android:text="search!"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ScrollView
android:id="#+id/textViewWrapper"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView tools:context="Controller.MainActivity"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/recycler_view"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.RecyclerView>
</ScrollView>
</LinearLayout>
recyclerview_item.xml
android:id="#+id/list_item_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="cursive"
android:textColor="#000000"
/>
Eco.java
public class Eco extends AppCompatActivity {
private RecyclerView recyclerView;
EditText editText;
ScrollView textViewWrapper;
Button button;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eco);
textView = (TextView) findViewById(R.id.list_item_text);
editText = (EditText) findViewById(R.id.editText);
textViewWrapper = (ScrollView) findViewById(R.id.textViewWrapper);
button = (Button) findViewById(R.id.button);
//textView.setText(R.string.longText);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
new Eco.GetDataFromFirebase().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// Read from the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("F");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
/*for (DataSnapshot alert: dataSnapshot.getChildren()) {
System.out.println(alert.getValue());
}*/
// This method is called once with the initial value and again
// whenever data at this location is updated.
ArrayList<String> values = (ArrayList<String>) dataSnapshot.getValue();
recyclerView.setAdapter(new RecyclerViewAdapter(values));
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
System.out.println("Failed to read value." + error.toException());
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String criteria = editText.getText().toString();
String fullText = textView.getText().toString();
if (fullText.contains(criteria)) {
int indexOfCriteria = fullText.indexOf(criteria);
int lineNumber = textView.getLayout().getLineForOffset(indexOfCriteria);
String highlighted = "<font color='red'>"+criteria+"</font>";
fullText = fullText.replace(criteria, highlighted);
textView.setText(Html.fromHtml(fullText));
textViewWrapper.scrollTo(0, textView.getLayout().getLineTop(lineNumber));
}
}
});
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.length() == 0) {
String fullText = textView.getText().toString();
fullText = fullText.replace("<font color='red'>", "");
fullText = fullText.replace("</font>", "");
textView.setText(fullText);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
private class GetDataFromFirebase extends AsyncTask<Void,Void,Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... voids) {
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
}
I am doing one application. In that i need to search the recycler item and once the user selects item from recycler then it should be set as a tag to that edit text. I did this from this https://android-arsenal.com/details/1/3581, but its not working properly. Can any help me how can i achieve the searching the items from recycler view and set it as a edit tag for that selected item.
This is the screen for reference.
I am doing like this
public class ActivityTagFriends extends BaseActivity implements TagsEditText.TagsEditListener, View.OnClickListener {
TextView tv_cancel, tv_title, tv_Done;
RecyclerView rv_TagFriends;
private TagsEditText mTagsEditText;
private List<String> list = new ArrayList<String>();
TagFriendsAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tag_friends);
tv_cancel = (TextView) findViewById(R.id.tvCancel);
tv_cancel.setText("Cancel");
tv_cancel.setTextColor(getResources().getColor(R.color.red));
tv_title = (TextView) findViewById(R.id.tvTitle);
tv_title.setText("Tag Friends");
tv_title.setTextColor(getResources().getColor(R.color.black));
tv_Done = (TextView) findViewById(R.id.tvDone);
tv_Done.setText("Done");
tv_Done.setTextColor(getResources().getColor(R.color.red));
rv_TagFriends= (RecyclerView) findViewById(R.id.rv_TagFriends);
mTagsEditText = (TagsEditText) findViewById(R.id.tagsEditText);
mTagsEditText.setHint("Search");
mTagsEditText.setTagsListener(this);
mTagsEditText.setTagsWithSpacesEnabled(true);
mTagsEditText.setAdapter(new ArrayAdapter<>(this,
R.layout.tag_friends_row, R.id.tv_TagName,list));
mTagsEditText.setThreshold(1);
rv_TagFriends.setHasFixedSize(true);
rv_TagFriends.setLayoutManager(new LinearLayoutManager(this));
countryList(); // in this method, Create a list of items.
// call the adapter with argument list of items and context.
// mAdapter = new TagFriendsAdapter(list,this);
// rv_TagFriends.setAdapter(mAdapter);
addTextListener();
}
// this method is used to create list of items.
public void countryList(){
list.add("Afghanistan");
list.add("Albania");
list.add("Algeria");
list.add("Bangladesh");
list.add("Belarus");
list.add("Canada");
list.add("Cape Verde");
list.add("Central African Republic");
list.add("Denmark");
list.add("Dominican Republic");
list.add("Egypt");
list.add("France");
list.add("Germany");
list.add("Hong Kong");
list.add("India");
list.add("Iceland");
}
public void addTextListener(){
mTagsEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase();
final List<String> filteredList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
final String text = list.get(i).toLowerCase();
if (text.contains(query)) {
filteredList.add(list.get(i));
}
}
rv_TagFriends.setLayoutManager(new LinearLayoutManager(ActivityTagFriends.this));
mAdapter = new TagFriendsAdapter(filteredList, ActivityTagFriends.this);
rv_TagFriends.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
// data set changed
}
});
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
// mTagsEditText.showDropDown();
// data set changed
}
}
#Override
public void onClick(View v) {
}
#Override
public void onTagsChanged(Collection<String> tags) {
}
#Override
public void onEditingFinished() {
}
}
Thanks in advance.
Okay I got your problem use this code
Your activity layout(activity_main.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:TagsEditText="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="mabbas007.myapplication.MainActivity">
<mabbas007.tagsedittext.TagsEditText
android:id="#+id/tagsEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
TagsEditText:allowSpaceInTag="true"
TagsEditText:tagsBackground="#drawable/square_default"
TagsEditText:tagsCloseImageRight="#drawable/tag_close" />
<TextView
android:background="#android:color/darker_gray"
android:padding="10dp"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Suggestion"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/rv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
adapter layout(adapter_item.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:padding="10dp"
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<View
android:layout_width="match_parent"
android:background="#color/colorAccent"
android:layout_height="1dp"/>
</LinearLayout>
Activity code
public class MainActivity extends AppCompatActivity
implements TagsEditText.TagsEditListener {
RecyclerView rv_TagFriends;
private TagsEditText mTagsEditText;
private List<String> list = new ArrayList<String>();
TagFriendsAdapter mAdapter;
ArrayList<String > tags;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tags=new ArrayList<>();
rv_TagFriends= (RecyclerView) findViewById(R.id.rv);
mTagsEditText = (TagsEditText) findViewById(R.id.tagsEditText);
mTagsEditText.setHint("Search");
mTagsEditText.setTagsListener(this);
mTagsEditText.setTagsWithSpacesEnabled(true);
//mTagsEditText.setAdapter(mAdapter);
mTagsEditText.setThreshold(1);
rv_TagFriends.setHasFixedSize(true);
rv_TagFriends.setLayoutManager(new LinearLayoutManager(this));
countryList(); // in this method, Create a list of items.
// call the adapter with argument list of items and context.
// mAdapter = new TagFriendsAdapter(list,this);
// rv_TagFriends.setAdapter(mAdapter);
addTextListener();
}
// this method is used to create list of items.
public void countryList(){
list.add("Afghanistan");
list.add("Albania");
list.add("Algeria");
list.add("Bangladesh");
list.add("Belarus");
list.add("Canada");
list.add("Cape Verde");
list.add("Central African Republic");
list.add("Denmark");
list.add("Dominican Republic");
list.add("Egypt");
list.add("France");
list.add("Germany");
list.add("Hong Kong");
list.add("India");
list.add("Iceland");
}
public void addTextListener(){
mTagsEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence query, int start, int before, int count) {
query = query.toString().toLowerCase().trim();
if (query.toString().equals(""))
return;
if (tags.size()!=0)
query=query.toString().substring(query.toString().indexOf(tags.get(tags.size()-1).toLowerCase())+tags.get(tags.size()-1).toString().length()).trim();
if (query.toString().equals("")){
final List<String> filteredList = new ArrayList<>();
rv_TagFriends.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mAdapter = new TagFriendsAdapter(filteredList, MainActivity.this);
rv_TagFriends.setAdapter(mAdapter);
}else {
final List<String> filteredList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
final String text = list.get(i).toLowerCase();
if (text.contains(query)) {
filteredList.add(list.get(i));
}
}
rv_TagFriends.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mAdapter = new TagFriendsAdapter(filteredList, MainActivity.this);
rv_TagFriends.setAdapter(mAdapter);
}
}
});
}
#Override
public void onTagsChanged(Collection<String> tags) {
}
#Override
public void onEditingFinished() {
}
public class TagFriendsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private List<String > data;
private MainActivity mainActivity;
public TagFriendsAdapter(List<String> data , MainActivity mainActivity) {
this.data = data;
this.mainActivity=mainActivity;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_item, parent, false));
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
((MyViewHolder)holder).text.setText(data.get(position)+"");
((MyViewHolder)holder).text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mainActivity.add(data.get(position)+"");
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView text;
public MyViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text);
}
}
}
public void add(String s){
for (int i = 0; i < tags.size(); i++) {
if (s.equals(tags.get(i)))
return;
}
tags.add(s);
String [] tag=tags.toArray(new String [0]);
mTagsEditText.setTags(tag);
}
}
I want to create a control in android where user can input through keyboard or enter through drop down list(spinner).
Actually the values I hard code in array in spinner is not exhaustive, so user should have the option to input through virtual keyboard also.
So Either user can enter through keyboard or select from list?
How can i achieve this in android?
You can build your own view:
public class ServerPreference extends DialogPreference {
private String value;
private EditText editText;
private Spinner spinner;
private final int server_list_id;
ArrayList<String> servers;
public ServerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setPersistent(false);
setDialogLayoutResource(R.layout.server_preference_layout);
servers = new ArrayList<String>();
Resources r = context.getResources();
if (MySettings.KEY_ASR_SERVER_HOST.equals(getKey())) {
server_list_id = R.array.asrServers;
} else if (MySettings.KEY_LOG_SERVER_HOST.equals(getKey())) {
server_list_id = R.array.logServers;
} else {
server_list_id = R.array.servicesServers;
}
Collections.addAll(servers, r.getStringArray(server_list_id));
}
#Override
protected void onBindDialogView(View view) {
editText = (EditText)view.findViewById(R.id.server_preference_text);
spinner = (Spinner)view.findViewById(R.id.server_preference_spinner);
SharedPreferences pref = getSharedPreferences();
value = pref.getString(getKey(), "");
editText.setText(value);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
view.getContext(), server_list_id, android.R.layout.simple_spinner_item );
adapter.setDropDownViewResource( android.R.layout.simple_dropdown_item_1line );
spinner.setAdapter( adapter );
updateSpinner();
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if ( position != 0 ) {
value = servers.get(position);
editText.setText(value);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
editText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
updateSpinner();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
super.onBindDialogView(view);
}
void updateSpinner() {
value = editText.getText().toString();
int index = servers.indexOf(value);
if ( index == -1 )
index = 0;
spinner.setSelection(index);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
if ( positiveResult ) {
SharedPreferences.Editor editor = getEditor();
editor.putString(getKey(),value);
editor.commit();
}
super.onDialogClosed(positiveResult);
}
public String getValue() {
return value;
}
void setValue(String value) {
this.value = value;
}
}
Layout of custom view:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:id="#+id/server_preference_text" android:inputType="text">
<requestFocus></requestFocus>
</EditText>
<Spinner android:layout_height="wrap_content" android:id="#+id/server_preference_spinner" android:layout_width="match_parent"></Spinner>
</LinearLayout>
When you want to use this view, just define in XML file:
<xxx.xxxxxx.xxxxx.settings.debug.ServerPreference
android:title="ASR/VVS Server"
android:persistent="true"
android:positiveButtonText="OK"
android:dialogTitle="ASR/VVS Server"
android:key="SERVER_NAME"
android:negativeButtonText="Cancel"
android:entryValues="#array/asrServers"
android:entries="#array/asrServers"/>