I have a class:
public class MultiObjectSelectorView extends LinearLayout {
private List<String> items;
private List<String> default_items;
private List<String> display_items;
private EditText text_feild;
private ListView drop_down;
public MultiObjectSelectorView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.multiobjectselectorlayout, this, true);
drop_down = (ListView) findViewById(R.id.drop_down);
text_feild = (EditText) findViewById(R.id.MyTextView);
display_items = new ArrayList<String>();
final ListAdapter adapter = new ListAdapter(context,display_items);
drop_down.setAdapter(adapter);
text_feild.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before,int count) {
if(!s.toString().equals("")){
display_items = new ArrayList<String>();
String str = s.toString();
for(int i = 0;i<items.size();i++){
String[] splited = items.get(i).split("\\s+");
int isFound = 0;
for(int x = 0;x<splited.length;x++){
if(splited[x].startsWith(str)){
isFound = 1;
x = splited.length;
}
}
if(isFound == 1){
display_items.add(items.get(i));
}
}
}else{
display_items = new ArrayList<String>();
}
adapter.setListData(display_items);
adapter.notifyDataSetChanged();
}
public void afterTextChanged(Editable s) {
}
});
drop_down.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
}
});
}
public void SetList(String[] list){
items = new ArrayList<String>();
for(int i = 0;i<list.length;i++){
items.add(list[i]);
}
default_items = items;
}
public void SetList(String[] list,String[] list2){
items = new ArrayList<String>();
default_items = new ArrayList<String>();
for(int i = 0;i<list.length;i++){
items.add(list[i]);
}
for(int i = 0;i<list2.length;i++){
default_items.add(list2[i]);
}
}
public void SetList(String[] list,String[] list2,String[] list3){
items = new ArrayList<String>();
default_items = new ArrayList<String>();
for(int i = 0;i<list.length;i++){
items.add(list[i]);
}
for(int i = 0;i<list2.length;i++){
default_items.add(list2[i]);
}
for(int i = 0;i<list3.length;i++){
items.add(list3[i]);
}
}
private class ListAdapter extends ArrayAdapter<String> {
private final Context context;
private List<String> values;
public ListAdapter(Context context, List<String> values) {
super(context, R.layout.dropdownlayout, values);
this.context = context;
this.values = values;
}
public void setListData(List<String> values2){
values = values2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.dropdownlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.drop_down_text_view);
textView.setText(values.get(position));
return rowView;
}
#Override
public int getCount() {
return values.size();
}
#Override
public String getItem(int position) {
return values.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
}
The reason I don't use a MultiAutoCompleteTextView is that (1). I wanted the items in a drop down, (2). the drop downs not going to be used as an auto complete list it gives custom suggestions in a drop down view(they don't do anything yet, but eventually they'll add what is clicked on into a list).
The problem is that the listview, when expanded pushes down everything below the custom viewgroup. I would like it to overlay everything else.
also the layout file:
sion="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/MyTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/deit_restr_text"
android:ems="10" >
</EditText>
<ListView
android:id="#+id/drop_down"
android:layout_width="match_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>
Related
First, please bear with me as I am just a beginner in learning Android.
What I want is that when the user adds an item from another activity, the details will be shown from my listview in the MainActivity (I am using a regular expression for my search results). And when the user tries to search an item, I want the search results to show.
From my code below, only the added items are shown and the search results will not display.
Here is a snippet of my code from MainActivity.java
ArrayList<Student> studentArrayList = new ArrayList<>();
ArrayList<Student> findlist = new ArrayList<>();
CustomAdapter adapter, anotheradapter;
private Uri imageUri;
ListView lv;
AlertDialog.Builder show_builder;
AlertDialog dialog;
LinearLayout layout;
ImageView imageView;
TextView stud_lname, stud_fname, stud_course;
AdapterView.AdapterContextMenuInfo info;
//
EditText txtsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
anotheradapter = new CustomAdapter(this, findlist);//adapter for finding the list
adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
//
show_builder = new AlertDialog.Builder(this);
txtsearch.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) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
anotheradapter.notifyDataSetChanged();
}//end if
}
//update the listview
anotheradapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context context;
//data container
ArrayList<Student> list;
LayoutInflater inflater;
//contructor
public CustomAdapter(Context context, ArrayList<Student> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.iv = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLastname);
holder.fname= (TextView) convertView.findViewById(R.id.textFirstname);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//inflate
holder.iv.setImageURI(list.get(position).getUriImage());
holder.lname.setText(list.get(position).getStudlname());
holder.fname.setText(list.get(position).getStudfname());
holder.course.setText(list.get(position).getStudcourse());
return convertView;
}
//creating a static class
static class ViewHolder{
ImageView iv;
TextView lname, fname,course;
}
}
Student.java
public class Student {
Uri uriImage;
String studlname, studfname, studcourse;
//constructor
public Student(Uri uriImage, String studlname, String studfname, String studcourse) {
super();
this.uriImage = uriImage;
this.studlname = studlname;
this.studfname = studfname;
this.studcourse = studcourse;
}
//getters and setters
public Uri getUriImage() {
return uriImage;
}
public void setUriImage(Uri uriImage) {
this.uriImage = uriImage;
}
public String getStudlname() {
return studlname;
}
public void setStudlname(String studlname) {
this.studlname = studlname;
}
public String getStudfname() {
return studfname;
}
public void setStudfname(String studfname) {
this.studfname = studfname;
}
public String getStudcourse() {
return studcourse;
}
public void setStudcourse(String studcourse) {
this.studcourse = studcourse;
}
}
Update your code as below
ArrayList<Student> studentArrayList = new ArrayList<>();
ArrayList<Student> findlist = new ArrayList<>();
CustomAdapter adapter, anotheradapter;
private Uri imageUri;
ListView lv;
AlertDialog.Builder show_builder;
AlertDialog dialog;
LinearLayout layout;
ImageView imageView;
TextView stud_lname, stud_fname, stud_course;
AdapterView.AdapterContextMenuInfo info;
//
EditText txtsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
anotheradapter = new CustomAdapter(this, findlist);//adapter for finding the list
adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
//
show_builder = new AlertDialog.Builder(this);
txtsearch.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) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
anotheradapter.refreshList(findlist)
}//end if
}
//update the listview
anotheradapter.refreshList(findlist)
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
Add refresh List method in adapter
public class CustomAdapter extends BaseAdapter {
Context context;
//data container
ArrayList<Student> list;
LayoutInflater inflater;
//contructor
public CustomAdapter(Context context, ArrayList<Student> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
public void refreshList(ArrayList<Student> list){
this.list = list;
notifyDataSetChanged()
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.iv = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLastname);
holder.fname= (TextView) convertView.findViewById(R.id.textFirstname);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//inflate
holder.iv.setImageURI(list.get(position).getUriImage());
holder.lname.setText(list.get(position).getStudlname());
holder.fname.setText(list.get(position).getStudfname());
holder.course.setText(list.get(position).getStudcourse());
return convertView;
}
//creating a static class
static class ViewHolder{
ImageView iv;
TextView lname, fname,course;
}
}
You need to update your adapter initialization as below.
Update in the onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
// initialize the findlist to show all student list by default
findlist.addAll(studentArrayList);
anotheradapter = new CustomAdapter(this, findlist);
// ----- Remove these lines - as you don't need multiple adapters
//adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
//adapter.notifyDataSetChanged();
//lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
show_builder = new AlertDialog.Builder(this);
txtsearch.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) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
// Remove the below line as you don't need to update the list multipletimes
//anotheradapter.notifyDataSetChanged();
}
}
// Add these lines to show the list of all student when the searchbox is empty. This will reset the findList to initial state.
if (txtsearch.getText().length() == 0 && findlist.isEmpty()) {
findlist.addAll(studentArrayList);
}
anotheradapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
I'm creating an android app, in which I'm using recyclerView and the row of recyclerView is having editText.
This is my ReadingAdapter class
public class ReadingAdapter extends RecyclerView.Adapter<ReadingAdapter.ViewHolder> implements AdapterView.OnItemSelectedListener {
Context context;
String valOpenReading, valClosReading, valConsumption;
private List<ReadingData> readingList;
static String[] arrValOpenRead, arrValClosRead, arrValConsumption;
public ReadingAdapter(Context context, List<ReadingData> readingList) {
this.context = context;
this.readingList = readingList;
arrValOpenRead = new String[readingList.size()];
arrValClosRead = new String[readingList.size()];
arrValConsumption = new String[readingList.size()];
}
#Override
public ReadingAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.reading_sheet_layout, parent, false);
return new ReadingAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final ReadingAdapter.ViewHolder holder, final int position) {
ReadingData tempData = readingList.get(position);
holder.pdtName.setText(tempData.pdtName);
holder.keyId.setText("Key "+tempData.keyId);
holder.etClosRead.addTextChangedListener(new TextWatcher() {
boolean ignore = false;
#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) {
if (ignore)
return;
ignore = true;
valOpenReading = holder.etOpenRead.getText().toString();
arrValOpenRead[position] = valOpenReading;
valClosReading = s.toString().equals("") ? "0": s.toString();
arrValClosRead[position] = valClosReading;
if (!valOpenReading.equals("")) {
if (Integer.parseInt(valClosReading) < Integer.parseInt(valOpenReading)) {
Toast.makeText(context, "Check once! closing reading should be more than opening reading!", Toast.LENGTH_LONG).show();
valConsumption = "0";
holder.consumption.setText("");
} else {
valConsumption = (Integer.parseInt(valClosReading) - Integer.parseInt(valOpenReading))+"";
arrValConsumption[position] = valConsumption;
holder.consumption.setText(valConsumption);
}
} else
Toast.makeText(context, "Please fill the opening reading!", Toast.LENGTH_SHORT).show();
ignore = false;
}
});
}
#Override
public int getItemCount() {
return readingList.size();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView pdtName, keyId, consumption;
EditText etOpenRead, etClosRead;
public ViewHolder(View view) {
super(view);
pdtName = (TextView)view.findViewById(R.id.txt_list_pdt_supp);
keyId = (TextView)view.findViewById(R.id.key_set);
etOpenRead = (EditText)view.findViewById(R.id.open_val_set);
etClosRead = (EditText)view.findViewById(R.id.clos_val_set);
consumption = (TextView)view.findViewById(R.id.consumption_val);
}
}
}
This is my ReadingData.java
public class ReadingData {
String pdtName, keyId, openReading, closReading, consumption;
public ReadingData(String pdtName, String keyId) {
this.pdtName = pdtName;
this.keyId = keyId;
}
}
Here, if I enter value in the starting items of the recyclerView then as I scroll up the items to the bottom of the list, the last item will have that value.
Please ignore the quality of image as we can't upload above of 2MiB of snap.
Here the views are recycled as the list is scrolled. How to prevent the copying values to the other item in the list.
And that Toast is also repeated several times. How to stop this.
update:
By the suggetion of LQ Gioan through the SO question How ListView's recycling mechanism works , I got the logic how ListView actually works with recycling of views.
But I'm not sure whether the recyclerView also works same.
But here in my case, how can I implement this process. pls someone help me here.
RecyclerView reuse views, in fact it only generate the as many as views that is visible on the screen. so it's expected if you can see a value you set for other rows
The solution would be set all attributes of the view that you are changing to default or whatever the row should present from your data set
So put addTextChangedListener insode ViewHolder constructor(you can get position by calling getAdapterPosition()) for better performance and set the editText value inside onBindViewHolder method from your data set
Your Activity Code:
ListView listview = (ListView) findViewById(R.id.list_view);
listview.setItemsCanFocus(true);
Adapter adapter = new Adapter (YourActivity.this, YourArrayList);
listview .setAdapter(adapter);
Adapter class
public class Adapter extends BaseAdapter {
// Declare Variables \\
Context mContext;
LayoutInflater inflater;
Activity act;
String[] temp;
public Adapter(Context context, ArrayList<String> list) {
mContext = context;
inflater = LayoutInflater.from(mContext);
act = (Activity) context;
//-------Temp String Array-------\\
temp = new String[this.count];
for (int i = 0; i < this.count; i++) {
temp[i] = list.get(i);
}
//---------------------------\\
}
public class ViewHolder {
TextView optionTitle;
EditText optionText;
int ref;
}
#Override
public int getCount() {
return list.size;
}
#Override
public Object getItem(int position) {
return temp[position];
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.lv_items_add_ques_options_mcq, null);
holder.optionTitle = (TextView) view.findViewById(R.id.add_ques_opts_count_mcq_tv);
holder.optionText = (EditText) view.findViewById(R.id.add_ques_opts_title_mcq_et);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.ref = position;
holder.optionTitle.setText(getCharForNumber(position) + ":");
holder.optionText.setText(temp[position]);
holder.optionText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
temp[holder.ref] = arg0.toString().trim();
}
});
return view;
}
public void getList() {
StaticValues.arrayListOptions = new ArrayList<String>(Arrays.asList(temp));
StaticValues.arrayListOptionsCount = new ArrayList<String>();
for (int i = 0; i < count; i++) {
StaticValues.arrayListOptionsCount.add(String.valueOf(i+1));
Log.e("err_al", StaticValues.arrayListOptions.get(i));
Log.e("err_al", StaticValues.arrayListOptionsCount.get(i));
}
}
private String getCharForNumber(int i) {
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
if (i > 25) {
return null;
}
return Character.toString(alphabet[i]);
}}
I have an activity that retrieves data from a database that contains information (name, capital, population, flag image) for many countries. The main layout has an EditText to take the capital name as the input and a ListView. On launching the activity, all the countries are retrieved and shown briefly in the ListView. Then on typing in the EditText I want the ListView to show the countries with the matching capital name. But what I see is a blank ListView. Besides if the EditText is empty, I want the ListView to show all the countries as it showed in the beginning.
The main layout file is as below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_ad_id"
android:visibility="gone" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/adView"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp" >
<EditText
android:id="#+id/search_input_capital"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:layout_alignParentTop="true"
android:visibility="visible" >
<requestFocus />
</EditText>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#00000000"
android:divider="#android:color/transparent"
android:drawSelectorOnTop="false"
android:layout_below="#id/search_input_capital">
</ListView>
</RelativeLayout>
</RelativeLayout>
And the code for the activity ( CapitalActivity.java ) is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capital);
private ArrayList<Country> items;
private ArrayList<Country> items_all;
private ArrayList<Country> items_new;
private EfficientAdapter adapter;
private ListView listView;
EditText searchInput=(EditText)findViewById(R.id.search_input_capital);
items = new ArrayList<Country>();
items_new = new ArrayList<Country>();
listView = (ListView) findViewById(R.id.listView);
listView.setDividerHeight(10);
adapter = new EfficientAdapter(CapitalActivity.this);
listView.setAdapter(adapter);
setListItems("");
searchInput.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
String searchCapital = new String(s.toString()).trim();
items_new.clear();
for(Country myCountry : items_all) {
if( myCountry.getCapital() != null &&
myCountry.getCapital().trim().toLowerCase().contains(searchCapital)) {
items_new.add(myCountry);
}
}
items.clear();
items = (ArrayList<Country>) items_new.clone();
if(searchCapital.trim().isEmpty()){
items = items_all;
}
adapter.notifyDataSetChanged();
}
});
private void setListItems(String searchKey) {
items_all= DatabaseAccessor.getCountryList(CapitalActivity.this, type, typeValue, searchKey);
items=items_all;
adapter.notifyDataSetChanged();
}
Only the necessary code segment has been shown above. What should I do to achieve the target ?
EDIT1: I mostly omitted the EfficientAdapter implementation part in the code pasted above. However I am pasting that code too this time :
public class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.country_container, null);
holder = new ViewHolder();
holder.nameView = (TextView) convertView.findViewById(R.id.nameView);
holder.continentView = (TextView) convertView.findViewById(R.id.continentView);
holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
holder.detailsView = (TextView) convertView.findViewById(R.id.detailsView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
OnClickListener ocl = new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CapitalActivity.this, CountryLearningActivity.class);
intent.putExtra(Constants.KEY_COUNTRY, items);
intent.putExtra(Constants.KEY_INDEX, position);
startActivity(intent);
}
};
Country item = items.get(position);
holder.nameView.setText(item.getCountry());
if (type.equalsIgnoreCase(filters[0]) || type.equalsIgnoreCase(filters[1])
|| type.equalsIgnoreCase(filters[2])) {
holder.continentView.setText(item.getContinent());
} else if (type.equalsIgnoreCase(filters[3])) {
holder.continentView.setText(Html
.fromHtml("Area: " + formatter.format(Double.parseDouble(item.getArea())) + " km<sup>2</sup>"));
} else if (type.equalsIgnoreCase(filters[4])) {
holder.continentView.setText("Population : " + item.getPopulation());
}
holder.imageView.setImageResource(Utils.getResID(CapitalActivity.this, item.getFlag()));
holder.detailsView.setOnClickListener(ocl);
convertView.setOnClickListener(ocl);
return convertView;
}
class ViewHolder {
TextView nameView;
ImageView imageView;
TextView continentView;
TextView detailsView;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
}
just open teh same page from your current page for the below code
enter cod protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capital);
private ArrayList<Country> items;
private ArrayList<Country> items_all;
private ArrayList<Country> items_new;
private EfficientAdapter adapter;
private ListView listView;
EditText searchInput=(EditText)findViewById(R.id.search_input_capital);
items = new ArrayList<Country>();
items_new = new ArrayList<Country>();
listView = (ListView) findViewById(R.id.listView);
listView.setDividerHeight(10);
adapter = new EfficientAdapter(CapitalActivity.this);
listView.setAdapter(adapter);
setListItems("");
searchInput.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
String searchCapital = new String(s.toString()).trim();
items_new.clear();
for(Country myCountry : items_all) {
if( myCountry.getCapital() != null &&
myCountry.getCapital().trim().toLowerCase().contains(searchCapital)) {
items_new.add(myCountry);
}
}
items.clear();
items = (ArrayList<Country>) items_new.clone();
if(searchCapital.trim().isEmpty()){
items = items_all;
}
adapter.notifyDataSetChanged();
}
});
private void setListItems(String searchKey) {
items_all= DatabaseAccessor.getCountryList(CapitalActivity.this, type, typeValue, searchKey);
items=items_all;
adapter.notifyDataSetChanged();
}e here
I am trying to develop an android mobile application whereby i am required to display part of a listviews which has at least 100 items.
Now i,being the admin of a college,i has listed 100 subjects to be taught.(all to be listed in a listview.All of the subjects have a point and in order for a strudent to apply for this course he/she need to have exact of higher points.An indicative sample is below:
English:24
Spanish:16
MAths:28
Science:26
French:16
Management:22
Law:30
Asian Language:10
Now the student needs to enter his/her point and based(EXACT OR LOWER POINT)on that, he/she get the list of subjects he/she is eligible to apply for.
E.g Enter your points:24
the output in the listview should give the following:
French:16
Management:22
English:24
Asian Language:10
I tried this but am stuck and could not complete the codes:
Course.java
public class Course {
private String name;
private int points;
public Course(String name, int points) {
this.name = name;
this.points = points;
}
public String getName() {
return name;
}
public int getPoints() {
return points;
}
#Override
public String toString() {
return getName();
}
}
Course[] courses = new Course[]{
new Course("Medicine", 30),
new Course("Physics", 28),
new Course("Math", 24),
new Course("English", 20)
};
Button searchButton = (Button) findViewById(R.id.btn_search);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
List<Course> courseList = new ArrayList<Course>(Arrays.asList(courses));
// initialize the adapter with courseList... //
// this code inside the Button's onClick
int points = Integer.parseInt(editText.getText().toString());
for (Course c : courses) {
if (c.getPoints() <= points) {
adapter.add(c);
}
}
course.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_width="0dp"
android:layout_weight="1"
android:maxLines="1"
android:inputType="number"
android:layout_height="wrap_content"
android:hint="Enter your points:"
android:id="#+id/editText"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/btn_search"/>
</LinearLayout>
<ListView
android:id="#+id/courseNames"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
My solution as below -
MainActivity
public class MainActivity extends AppCompatActivity {
ListView myList;
EditText edtSearch;
Button btnSearch;
listAdapter adapter;
ArrayList<Course> alSearchCourses;
Course[] courses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.myList);
edtSearch = (EditText) findViewById(R.id.edtSearch);
btnSearch = (Button) findViewById(R.id.btnSearch);
courses = new Course[]{
new Course("Medicine", 30),
new Course("Physics", 28),
new Course("Math", 24),
new Course("English", 20)
};
adapter = new listAdapter(this, courses);
myList.setAdapter(adapter);
edtSearch.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) {
if (count == 0) {
adapter = new listAdapter(MainActivity.this, courses);
myList.setAdapter(adapter);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alSearchCourses = new ArrayList<>();
int points = Integer.parseInt(edtSearch.getText().toString());
for (int i = 0; i < courses.length; i++) {
Course c2 = courses[i];
if (c2.getPoints() <= points) {
alSearchCourses.add(c2);
}
}
Course searchCourses [] = new Course[alSearchCourses.size()];
searchCourses = alSearchCourses.toArray(searchCourses);
adapter = new listAdapter(MainActivity.this, searchCourses);
myList.setAdapter(adapter);
}
});
}
}
listAdapter
public class listAdapter extends BaseAdapter {
Context context;
Course[] courses;
LayoutInflater inflater;
public listAdapter(Context context, Course[] courses) {
this.context = context;
this.courses = courses;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return courses.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflater.inflate(R.layout.list_item_layout, null);
}
TextView txtCourse = (TextView) convertView.findViewById(R.id.txtCourse);
txtCourse.setText(courses[position].getName() + "-" + courses[position].getPoints());
return convertView;
}
}
Hope it helps :)
i wanted to add a search function to my customize list view. i actually search through internet for few hours, but i unable to follow all those complicated tutorial or demo, so i decided to post my problem here. Hope somebody can actually help me to solve this. here is my code
ListView lv;
EditText inputSearch;
CustomListView testingAdapter;
//at oncreate method
lv = (ListView) findViewById(R.id.lvEditSavingList);
inputSearch = (EditText) findViewById(R.id.inputSearch);
loadListViewData();
private void loadListViewData() {
// TODO Auto-generated method stub
UnderControlDb db = new UnderControlDb(getApplicationContext());
String[] info = db.MySavingShowData();
int counter = info.length;
Integer[] imageID = new Integer[counter];
for(int i=0;i<counter;i++){
imageID[i] = R.drawable.edit_notes_list;
}
testingAdapter = new CustomListView(MySaving.this, info, imageID);
lv.setAdapter(testingAdapter);
}
then this is my customize class
public class CustomListView extends ArrayAdapter<String>{
private final Activity context;
private final String[] data;
private final Integer[] imageId;
public CustomListView(Activity context,String[] data, Integer[] imageId) {
super(context, R.layout.my_saving_list, data);
this.context = context;
this.data = data;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.my_saving_list, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvSavingListView);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imgS);
txtTitle.setText(data[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
and my xml code
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<TextView
android:id="#+id/tvSavingListView"
android:layout_width="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textSize="16sp"
android:layout_height="30dp" />
<ImageView
android:id="#+id/imgS"
android:layout_width="25dp"
android:layout_height="25dp"/>
</TableRow>
</TableLayout>
I've wrote a small sample in order to show you how you can search data from your listView.
Find below the code, and do not hesitate to ask me any question for more clarification.
public class TestSearch extends Activity {
ListView lv;
EditText inputSearch;
CustomListView testingAdapter;
public class listContent{
public String info;
public int imageInfo;
public listContent(String info, int imageInfo) {
this.info = info;
this.imageInfo = imageInfo;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public int getImageInfo() {
return imageInfo;
}
public void setImageInfo(int imageInfo) {
this.imageInfo = imageInfo;
}
}
ArrayList<listContent> itemsContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_search);
itemsContent = new ArrayList<listContent>();
CustomListView testingAdapter;
lv = (ListView) findViewById(R.id.lvEditSavingList);
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(textWatcher);
loadListViewData();
}
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
testingAdapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
};
private void loadListViewData() {
// TODO Auto-generated method stub
itemsContent.add(new listContent("text", R.drawable.ic_launcher));
itemsContent.add(new listContent("hello", R.drawable.ic_launcher));
itemsContent.add(new listContent("dear", R.drawable.ic_launcher));
itemsContent.add(new listContent("test", R.drawable.ic_launcher));
itemsContent.add(new listContent("lol", R.drawable.ic_launcher));
testingAdapter = new CustomListView(TestSearch.this, itemsContent);
lv.setAdapter(testingAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.test_search, menu);
return true;
}
public class CustomListView extends BaseAdapter{
private final Context mContext;
private ArrayList<listContent> items;
ArrayList<listContent> filtereditems;
public CustomListView(Context context, ArrayList<listContent> items) {
this.mContext= context;
this.items = items;
this.filtereditems = new ArrayList<listContent>();
this.filtereditems.addAll(items);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View rowView= inflater.inflate(R.layout.my_saving_list, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvSavingListView);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imgS);
txtTitle.setText(items.get(position).getInfo());
imageView.setImageResource(items.get(position).getImageInfo());
return rowView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
items.clear();
if (charText.length() == 0) {
items.addAll(filtereditems);
}
else
{
for (listContent wp : filtereditems)
{
if(wp.getInfo().startsWith(charText))
{
items.add(wp);
}
}
}
notifyDataSetChanged();
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int arg0) {
return items.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
}
}