I am trying to add a dynamic view inside my LinearLayout and trying to implement something like to catch every spinner value corresponding to time. Can anyone over here can guide me that how it can be done. I am trying it but it's not working as there can be infinite rows with spinners based on the click on the "ADD FILED" button. I need to collect value from each spinner and need to create an array then.
Here is my code :
public class MainActivity extends Activity {
private LinearLayout parentLinearLayout;
private EditText mEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
parentLinearLayout=(LinearLayout) findViewById(R.id.parent_linear_layout);
}
public void onAddField(View v) {
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView=inflater.inflate(R.layout.container_item, null);
final EditText text1 = (EditText) rowView.findViewById(R.id.number_edit_text);
final EditText text2 = (EditText) rowView.findViewById(R.id.number_edit_text2);
final EditText text3 = (EditText) rowView.findViewById(R.id.number_edit_text3);
text1.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) {
if (s.length() > 0) {
text3.setText(text1.getText().toString());
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
text2.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) {
if (s.length() > 0) {
int val = Integer.parseInt(text1.getText().toString());
int val2 = Integer.parseInt(text2.getText().toString());
if(val2>val)
{
}else{
int finalval=val-val2;
text3.setText(""+finalval);
}
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
text3.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) {
if (s.length() > 0) {
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount());
}
public void onDelete(View v) {
parentLinearLayout.removeView((View) v.getParent());
}
public void onGetField(View v){
int count = parentLinearLayout.getChildCount();
for (int i = 0; i < count; i++) {
final View row = parentLinearLayout.getChildAt(i);
EditText textOut = (EditText) row.findViewById(R.id.number_edit_text);
String data = textOut.getText().toString();
Toast.makeText(this,""+data,Toast.LENGTH_LONG).show();
}
}
}
Dynamic view XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<EditText
android:id="#+id/number_edit_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".2"
android:inputType="phone"/>
<EditText
android:id="#+id/number_edit_text2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".2"
android:inputType="phone"/>
<EditText
android:id="#+id/number_edit_text3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".2"
android:inputType="phone"/>
<Spinner
android:id="#+id/type_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".3"
android:entries="#array/types"
android:gravity="right" />
<Button
android:id="#+id/delete_button"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight=".1"
android:background="#android:drawable/ic_delete"
android:onClick="onDelete"/>
</LinearLayout>
Main XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/parent_linear_layout"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
<Button
android:id="#+id/add_field_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#555"
android:layout_gravity="center"
android:onClick="onAddField"
android:textColor="#FFF"
android:text="Add Field"
android:paddingLeft="5dp"/>
<Button
android:id="#+id/get_field_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#555"
android:layout_gravity="center"
android:onClick="onGetField"
android:textColor="#FFF"
android:text="Get Field"
android:paddingLeft="5dp"/>
</LinearLayout>
Please let me know your valuable suggestions on this. I have been stuck since the last day.
Here is the attached image and in the image you can see that the 3rd edit text is empty which I need to fill by using text watcher on 1st two edit-text like 2(first edit-text)-1(second edit-text) = 1 (on thrid edit-text).
Regards
Below is the second approach using Recyclerview:
MainActivity:
public class MainActivity extends AppCompatActivity {
int position=0;
List<Container_Add_model> main_modelList = new ArrayList<>();
RecyclerView recyclerView_container;
TextView Tv_add_container;
Container_Add_Adapter rvAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView_container = findViewById(R.id.recyclerView_container);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView_container.setLayoutManager(layoutManager);
Tv_add_container = findViewById(R.id.Tv_add_container);
rvAdapter = new Container_Add_Adapter(MainActivity.this, main_modelList,this, new Container_Add_Adapter.Onclick() {
#Override
public void onEvent(Container_Add_model model, int pos) {
}
});
recyclerView_container.setAdapter(rvAdapter);
Tv_add_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
rvAdapter.addClick();
}
});
}
Adapter Class :
public class Container_Add_Adapter extends RecyclerView.Adapter<Container_Add_Adapter.RvViewHolder> {
Activity context;
List<Container_Add_model> models;
Onclick onclick;
View view;
EditTextAdded editTextAdded;
private int container_number_pending, container_number_taken, container_number_given;
public Container_Add_Adapter(Activity context, List<Container_Add_model> models,EditTextAdded editTextAdded, Onclick onclick) {
this.context = context;
this.models = models;
this.editTextAdded = editTextAdded;
this.onclick = onclick;
}
#Override
public Container_Add_Adapter.RvViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.from(parent.getContext()).inflate(R.layout.container_item, parent, false);
RvViewHolder rvViewHolder = new RvViewHolder(view);
return rvViewHolder;
}
#Override
public void onBindViewHolder(final Container_Add_Adapter.RvViewHolder holder, final int position) {
final Container_Add_model model = models.get(position);
holder.Edttxt_given_container.setText(models.get(position).container_given+"");
holder.Edttxt_given_container.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) {
if (s.length() > 0) {
// models.get(position).container_given = Integer.valueOf(s.toString());
}
}
});
holder.Edttxt_taken_container.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) {
if (s.length() != 0) {
if (!holder.Edttxt_given_container.getText().toString().isEmpty()) {
container_number_given = Integer.parseInt(holder.Edttxt_given_container.getText().toString());
int number = container_number_given + container_number_pending;
int input_num = Integer.parseInt(s.toString());
if (number >= input_num) {
container_number_taken = Integer.parseInt(holder.Edttxt_taken_container.getText().toString());
int final_num = number - container_number_taken;
holder.Edttxt_Pending_container.setText("" + final_num);
} else {
holder.Edttxt_taken_container.setText("");
}
} else {
holder.Edttxt_taken_container.setText("");
}
} else {
if (!holder.Edttxt_given_container.getText().toString().isEmpty()) {
container_number_given = Integer.parseInt(holder.Edttxt_given_container.getText().toString());
if (container_number_given > 0) {
int finalnum = container_number_given + container_number_pending;
holder.Edttxt_Pending_container.setText("" + finalnum);
} else {
holder.Edttxt_Pending_container.setText("" + container_number_pending);
}
} else {
holder.Edttxt_Pending_container.setText("" + container_number_pending);
}
}
}
});
holder.Iv_delete_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
models.remove(position);
notifyItemChanged(position);
notifyItemRangeChanged (position, models.size());
}
});
}
public void addClick(){
Container_Add_model container_main_model = new Container_Add_model();
container_main_model.setContainer_given(0);
container_main_model.setContainer_pending(0);
container_main_model.setContainer_taken(0);
container_main_model.setContainer_id(models.size());
container_main_model.setContainer_name("");
models.add(container_main_model);
//notifyDataSetChanged(models);
notifyItemInserted(models.size() + 1);
}
#Override
public int getItemCount() {
return models.size();
}
public interface Onclick {
void onEvent(Container_Add_model model, int pos);
}
public class RvViewHolder extends RecyclerView.ViewHolder {
TextView Tv_container_type;
EditText Edttxt_given_container, Edttxt_taken_container, Edttxt_Pending_container;
LinearLayout llItem;
ImageView Iv_delete_container;
public RvViewHolder(View itemView) {
super(itemView);
Tv_container_type = itemView.findViewById(R.id.Tv_container_type);
Iv_delete_container = itemView.findViewById(R.id.Iv_delete_container);
Edttxt_given_container = itemView.findViewById(R.id.Edttxt_given_container);
Edttxt_Pending_container = itemView.findViewById(R.id.Edttxt_Pending_container);
Edttxt_taken_container = itemView.findViewById(R.id.Edttxt_taken_container);
}
}
}
Here is what you were missing :
public class MainActivity extends Activity {
private LinearLayout parentLinearLayout;
private ArrayList<> mList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
parentLinearLayout=(LinearLayout) findViewById(R.id.parent_linear_layout);
}
public void onAddField(View v) {
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView=inflater.inflate(R.layout.container_item, null);
final EditText text1 = (EditText) rowView.findViewById(R.id.number_edit_text);
final EditText text2 = (EditText) rowView.findViewById(R.id.number_edit_text2);
final EditText text3 = (EditText) rowView.findViewById(R.id.number_edit_text3);
final Spinner mSpinner = (Spinner) rowView.findViewById(R.id.type_spinner);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedDiv = parent.getItemAtPosition(position).toString();
Toast.makeText(MainActivity.this, ""+selectedDiv, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// can leave this empty
}
});
text1.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) {
if (s.length() > 0) {
text3.setText(text1.getText().toString());
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
text2.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) {
if (s.length() > 0) {
int val = Integer.parseInt(text1.getText().toString());
int val2 = Integer.parseInt(text2.getText().toString());
if(val2>val)
{
}else{
int finalval=val-val2;
text3.setText(""+finalval);
}
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
text3.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) {
if (s.length() > 0) {
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount());
}
public void onDelete(View v) {
parentLinearLayout.removeView((View) v.getParent());
}
public void onGetField(View v){
mList = new ArrayList<>();
int count = parentLinearLayout.getChildCount();
for (int i = 0; i < count; i++) {
final View row = parentLinearLayout.getChildAt(i);
EditText textOut = (EditText) row.findViewById(R.id.number_edit_text);
EditText textOut2 = (EditText) row.findViewById(R.id.number_edit_text2);
EditText textOut3 = (EditText) row.findViewById(R.id.number_edit_text3);
Spinner spinner = (Spinner)row.findViewById(R.id.type_spinner);
mList.add(new DataList( textOut.getText().toString(),
textOut2.getText().toString()
, textOut3.getText().toString(),spinner.getSelectedItem().toString()
));
}
}
}
Datalist Model :
public class DataList {
public String given;
public String taken;
public String pending;
public String spinnerItemSelected;
public DataList(String given, String taken, String pending, String spinnerItemSelected) {
this.given = given;
this.taken = taken;
this.pending = pending;
this.spinnerItemSelected = spinnerItemSelected;
}
}
Convert your String array to ArrayList and pass it to Adapter and use below code or change below code with your String[].
You need to implement Filterable to your Adapter class and Override getFilter()
public class ListFilterActivity extends ListActivity {
private List<String> list = new ArrayList<String>();
List<String> mOriginalValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MyAdapter adapter = new MyAdapter(this, getModel());
setListAdapter(adapter);
EditText filterEditText = (EditText) findViewById(R.id.filterText);
// Add Text Change Listener to EditText
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private List<String> getModel() {
list.add("Linux");
list.add("Windows7");
list.add("Suse");
list.add("Eclipse");
list.add("Ubuntu");
list.add("Solaris");
list.add("Android");
list.add("iPhone");
list.add("Windows XP");
return list;
}
}
// Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
List<String> arrayList;
List<String> mOriginalValues; // Original Values
LayoutInflater inflater;
public MyAdapter(Context context, List<String> arrayList) {
this.arrayList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView textView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row, null);
holder.textView = (TextView) convertView
.findViewById(R.id.textview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(arrayList.get(position));
return convertView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
arrayList = (List<String>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
List<String> FilteredArrList = new ArrayList<String>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<String>(arrayList); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
String data = mOriginalValues.get(i);
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(data);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}
Related
When I add spinner in a recycler view (spinner dropdown contains edit texts) dynamically with button as the counter, spinner old dropdown values set to zero).value refreshes always when count increase.
public class MainActivity extends AppCompatActivity {
private Button btn;
private RecyclerView recyclerView;
private CustomAdapter customAdapter;
public ArrayList<EditModel> editModelArrayList;
int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
btn = (Button) findViewById(R.id.btn);
Button btnadd = (Button) findViewById(R.id.button);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count= (int) (count+1);
arrayadd();
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,NextActivity.class);
startActivity(intent);
}
});
}
private void arrayadd() {
int position=0;
// customAdapter.notifyDataSetChanged();;
editModelArrayList = populateList();
customAdapter = new CustomAdapter(this,editModelArrayList);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
}
private ArrayList<EditModel> populateList()
{
ArrayList<EditModel> list = new ArrayList<>();
for(int i = 0; i < (count); i++){
EditModel editModel = new EditModel();
editModel.setEditTextValue("");;
editModel.setEditttt("");
editModel.setChequedate("");
editModel.setChequeamount("");
list.add(editModel);
}
return list;
}
}
Custom adapter class
public CustomAdapter(Context ctx, ArrayList<EditModel> editModelArrayList){
inflater = LayoutInflater.from(ctx);
this.editModelArrayList = editModelArrayList;
}
#Override
public CustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, final int position) {
holder.editText.setText(editModelArrayList.get(position).getEditTextValue());
holder.editTexts.setText(editModelArrayList.get(position).getEditttt());
holder.edchequedate.setText(editModelArrayList.get(position).getChequedate());
holder.edchequeamount.setText(editModelArrayList.get(position).getChequeamount());
Log.d("print","yes");
}
#Override
public int getItemCount() {
return editModelArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
protected EditText editText;
protected EditText editTexts;
protected EditText edchequedate;
protected EditText edchequeamount;
/* protected EditText editTexts;
protected EditText editTexts;*/
public MyViewHolder(final View itemView) {
super(itemView);
final MaterialSpinner mts;
mts=itemView.findViewById(R.id.et_amounts);
mts.setItems("Cheque","DD","MO");
mts.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener() {
#Override
public void onItemSelected(MaterialSpinner view, int position, long id, Object item) {
L11 = (CardView) itemView.findViewById(R.id.L11);
L22 = (CardView) itemView.findViewById(R.id.L22);
L33 = (CardView) itemView.findViewById(R.id.L33);
System.out.println("itemj"+item);
if (position==0){
L11.setVisibility(View.VISIBLE);
L22.setVisibility(View.GONE);
L33.setVisibility(View.GONE);
}
else
if(position==1){
// L22.setVisibility(View.VISIBLE);
L11.setVisibility(View.GONE);
L22.setVisibility(View.VISIBLE);
L33.setVisibility(View.GONE);
}
else if (position==2){
L33.setVisibility(View.VISIBLE);
L11.setVisibility(View.GONE);
L22.setVisibility(View.GONE);
}
}
});
editText = (EditText) itemView.findViewById(R.id.editidaaaaaa);
editTexts = (EditText) itemView.findViewById(R.id.editids);
edchequedate = (EditText) itemView.findViewById(R.id.edt_chqdate);
edchequeamount = (EditText) itemView.findViewById(R.id.edt_chequeamnt);
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) {
editModelArrayList.get(getAdapterPosition()).setEditTextValue(editText.getText().toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
editTexts.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) {
editModelArrayList.get(getAdapterPosition()).setEditttt(editTexts.getText().toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
edchequedate.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) {
editModelArrayList.get(getAdapterPosition()).setChequedate(edchequedate.getText().toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
edchequeamount.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) {
editModelArrayList.get(getAdapterPosition()).setChequeamount(edchequeamount.getText().toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
}
}
This happens because the recyclerview gets a new adapter and list every increment. Move out your initialization of the adapter and list. Then in every increment add something to the list then call notifyDataSetChanged
int count=0;
private Button btn;
private RecyclerView recyclerView;
private CustomAdapter customAdapter;
public ArrayList<EditModel> editModelArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customAdapter = new CustomAdapter(this, editModelArrayList);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
btn = (Button) findViewById(R.id.btn);
Button btnadd = (Button) findViewById(R.id.button);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count= (int) (count+1);
arrayadd();
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, NextActivity.class);
startActivity(intent);
}
});
}
private void arrayadd() {
// Only add the difference of the count and the length
// the loop will only occur once since count increment is 1
for(int i = 0; i < (editModelArrayList.size() - count); i++){
EditModel editModel = new EditModel();
editModel.setEditTextValue("");;
editModel.setEditttt("");
editModel.setChequedate("");
editModel.setChequeamount("");
editModelArrayList.add(editModel);
}
customAdapter.notifyDataSetChanged();
}
I have a custom ArrayAdapter which is a horizontal LinearLayout containing 02 EditText fields and 01 TextView.....all are set to take/show numberDecimals.
All I want is that whenever a number is input in any of the EditText fields, the product of the two numbers (EditText 1 & EditText 2) is shown in TextView.
I've tried both OnFocusChangedListener and TextChangedListener but the TextView doesnt get updated during live entries. It doesnt show anything.
I'm new to programming, so cant find any other solution for that.
Thanks in advance!
Below is the Adapter code:
TextView labelView;
EditText ratioView;
EditText rateView;
TextView avgView;
public FibresAdapter(Activity context, ArrayList<Fibres> fibresList) {
super(context, 0, fibresList);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
final Fibres currentFibre = getItem(position);
labelView = (TextView) convertView.findViewById(R.id.label);
labelView.setText(currentFibre.fibreLabel);
ratioView = (EditText) convertView.findViewById(ratio);
rateView = (EditText) convertView.findViewById(R.id.rate);
avgView = (TextView) convertView.findViewById(R.id.avg);
ratioView.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 (s.toString().length() > 0) {
currentFibre.fibreRatio = Double.parseDouble(s.toString());
avgView.setText("Testing");
} else {
currentFibre.fibreRatio = 0;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
rateView.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 (s.toString().length() > 0) {
currentFibre.fibreRate = Double.parseDouble(s.toString());
avgView.setText("Testing");
} else {
currentFibre.fibreRate = 0;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
return convertView;
}
Below is the code for Activity:
double totalAvg;
double totalRatio;
TextView totalAvgView;
TextView totalRatioView;
static ArrayList<Fibres> fibres;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fibres_list);
fibres = new ArrayList<>();
int x = 0;
while (x < Fibres.fibCatArray.length) {
fibres.add(new Fibres(Fibres.fibCatArray[x]));
x++;
}
ListView listView = (ListView) findViewById(R.id.list);
FibresAdapter adapter = new FibresAdapter(this, fibres);
listView.setAdapter(adapter);
totalRatioView = (TextView) findViewById(R.id.total_ratio);
totalAvgView = (TextView) findViewById(R.id.total_avg);
}
public void displayTotals() {
totalRatio = 0;
totalAvg = 0;
for (Fibres materials : fibres) {
totalRatio += materials.fibreRatio;
totalAvg += (materials.fibreRatio / 100 * materials.fibreRate);
}
totalRatioView.setText(totalRatio + "");
totalAvgView.setText(totalAvg + "");
}
public boolean validateData() {
if (totalRatio != 100) {
Toast.makeText(this, "Total should be 100%!", Toast.LENGTH_SHORT).show();
return false;
}
for (Fibres materials : fibres) {
if (materials.fibreRatio > 1 && materials.fibreRate <= 0) {
Toast.makeText(this, "Enter both Ratio & Rate!", Toast.LENGTH_SHORT).show();
return false;
}
}
return true;
}
In your adapter add addTextChangedListener to both EditText and use textView.setText() inside that. Something like this.
editText1.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) {
if(s.length() != 0)
textView.setText("");
}
});
I have a listview with edittext in each row using a textwatcher to show a toast of content input.
The textwatcher works fine for all the rows except the first row. The toast after input of text fires up consistently after you input text instead of showing only once.
The other rows respond well to the desired behaviour by displaying the toast once every time you change input. The default values for the inputs is 0.
Here is my code inside getView() of my adapter:
//tvItems is my edittext variable reference
TextWatcher tt = new TextWatcher() {
public void afterTextChanged(Editable s) {
//tvItems.setSelection(s.length());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
tvItems.removeTextChangedListener(tt);
if (tvItems.getText().toString().trim().length() == 1) {
//to check if input is greater than 0 so we can proceed
if (Integer.valueOf(tvItems.getText().toString().trim()) > 0) {
//displays toast
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
tvItems.removeTextChangedListener(tt);
}
}
tvItems.addTextChangedListener(tt);
}
};
tvItems.addTextChangedListener(tt);
Any suggestions will be welcomed.
As requested, my full adapter code:
public class ProductListAdapter extends BaseAdapter implements Filterable {
List<ProductModel> mStringFilterList;
ValueFilter valueFilter;
int item_number = 0;
TextWatcher tt = null;
private Activity activity;
private LayoutInflater inflater;
private List<ProductModel> modelItems;
private OnAddRemoveListener myaddInterface;
TextView tvTitle;
Button minusIcon, addIcon;
public ProductListAdapter(Activity activity, List<ProductModel> modelItems, OnAddRemoveListener myaddInterface) {
this.activity = activity;
this.modelItems = modelItems;
mStringFilterList = modelItems;
this.myaddInterface = myaddInterface;
}
#Override
public int getCount() {
return modelItems.size();
}
#Override
public Object getItem(int location) {
return modelItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}/*
#Override
public boolean isEnabled(int position) {
return false;
}*/
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.product_item_row, null);
final ProductModel m = modelItems.get(position);
tvTitle = (TextView) convertView.findViewById(R.id.tv2);
TextView tprice = (TextView) convertView.findViewById(R.id.tv3);
boolean ignoreNextTextChange = true;
final EditText tvItems = (EditText) convertView.findViewById(R.id.num);
tvItems.setText("0");
minusIcon = (Button) convertView.findViewById(R.id.minus);
addIcon = (Button) convertView.findViewById(R.id.add);
//add items
addIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("add button", "clicked");
int new_item_number = 1 + Integer.parseInt(tvItems.getText().toString());
tvItems.setText("" + new_item_number);
(myaddInterface).onItemadded(String.valueOf(m.getPrice()), new_item_number, position);
}
});
minusIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("minus button", "clicked");
int new_item_number = Integer.parseInt(tvItems.getText().toString());
if (new_item_number > 0) {
(myaddInterface).onItemremoved(String.valueOf(m.getPrice()), position);
tvItems.setText("" + (new_item_number - 1));
} else if (tvItems.getText().toString().equals("0")) {
tvItems.setText("0");
}
}
});
tvTitle.setText(m.getname());
tprice.setText("(" + m.getPrice() + ")");
public void afterTextChanged(Editable s) {
if (tvItems.getText().toString().trim().length() == 1) {
//to check if input is greater than 0 so we can proceed
if (Integer.valueOf(tvItems.getText().toString().trim()) > 0) {
//displays toast
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
tvItems.addTextChangedListener(tt);
return convertView;
}
//code for search filter, not associated with the question
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<ProductModel> filterList = new ArrayList<>();
for (int i = 0; i < mStringFilterList.size(); i++)
if ((mStringFilterList.get(i).getname().toUpperCase())
.contains(constraint.toString().toUpperCase()) || (mStringFilterList.get(i).getproductDesc().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ProductModel m = new ProductModel(mStringFilterList.get(i)
.getProduct_id(), mStringFilterList.get(i)
.getname(), mStringFilterList.get(i)
.getPrice(), mStringFilterList.get(i)
.getimage_url(), mStringFilterList.get(i)
.getproductDesc());
filterList.add(m);
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
//show no results
}
/* }else if((mStringFilterList.get(i).getproductDesc().toUpperCase())
.contains(constraint.toString().toUpperCase())){}*/
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
modelItems = (List<ProductModel>) results.values;
notifyDataSetChanged();
}
}
}
set the listener object to edittext,(i.e) tt ,like this
editText.addTextChangedListener(tt);
Can you try this instead:
TextWatcher tt = new TextWatcher() {
public void afterTextChanged(Editable s) {
if (tvItems.getText().toString().trim().length() == 1) {
//to check if input is greater than 0 so we can proceed
if (Integer.valueOf(tvItems.getText().toString().trim()) > 0) {
//displays toast
Toast.makeText(activity, s, Toast.LENGTH_SHORT).show();
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
I'm trying to create a listView with 2 editText on each row, that are using TextWatcher interface for recognizing if we changes the current text on the editText
My problem is that my adapter is very very laggy and slow. how can i handle this issue ?
here is my adapter:
public class AccountListInfoAdapter2 extends BaseAdapter {
private Activity mContext;
private ArrayList<ModelClass> accounts;
private DisplayImageOptions options;
private LayoutInflater inflater;
private prevClass mainActivityFragment;
private ViewHolder holder;
public AccountListInfoAdapter2(Activity activity, ArrayList<ModelClass> mAccountListData, prevClass mainActivityFragment) {
this.mContext = activity;
this.accounts = mAccountListData;
this.mainActivityFragment = mainActivityFragment;
inflater = LayoutInflater.from(mContext);
}
#Override
public int getCount() {
if (accounts == null) {
return 0;
} else
return accounts.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
view = inflater.inflate(R.layout.account_info_row, parent, false);
holder = new ViewHolder();
assert view != null;
setViews(view);
view.setTag(holder);
holder.emailAddress.setText(accounts.get(position).getEmail());
holder.fullName.setText(accounts.get(position).getFullName());
holder.fullName.setId(position);
holder.emailAddress.setId(position);
//Check if full name has been changed
holder.fullName.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 (s.length() != count) {
if (!accounts.get(position).getFullName().equals(s.toString())) {
accounts.get(position).setFullName(s.toString());
}
}
}
#Override
public void afterTextChanged(Editable s) {
if (!accounts.get(position).getFullName().equals(s.toString())) {
accounts.get(position).setFullName(s.toString());
}
}
});
//Check if email name has been changed
holder.emailAddress.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(s.length() != count) {
if (!accounts.get(position).getEmail().equals(s.toString())){
accounts.get(position).getEmail(s.toString());
}
}
}
#Override
public void afterTextChanged(Editable s) {
if (!accounts.get(position).getEmail().equals(s.toString())) {
accounts.get(position).getEmail(s.toString());
}
}
});
return view;
}
public static class ViewHolder {
TextView emailAddress;
EditText fullName;
}
public void setViews(View view){
holder.emailAddress = (EditText) view.findViewById(R.id.accountInfoProfileEmailAddress);
holder.fullName = (EditText) view.findViewById(R.id.accountInfoFullName);
}
}
holder.fullName.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 (s.length() != count)
{
if (!accounts.get(position).getFullName().equals(s.toString())) {
//accounts.get(position).setFullName(s.toString());
((MainActivity)context).changeListViewItem(position , s.toString);
}
}
}
#Override
public void afterTextChanged(Editable s) {
if (!accounts.get(position).getFullName().equals(s.toString())) {
//accounts.get(position).setFullName(s.toString());
((MainActivity)context).changeListViewItem(position , s.toString);
}
}
});
Add this function on main activity
public void changeListViewItem(int position , String text)
{
Log.e("" , ""+position);
Log.e("" , ""+text);
refreshAdapter();
}
1.addTextChangedListener can be add repeat.
U can try to add a log in onTextChanged.
Watch how many times it logs when u type a char.
When u use addTextChangedListener, add a tag.
2.U should try to use ViewHolder to help u.
I am using a custom list view which contains two Buttons Yes or No. When I clicked on No button, a layout containing an edit text will be displayed. There are more than 15 items in the list view. When I tried to type and save the value in the edittext of the 1st item using TextWatcher(), then the value is save for both 5th and 1st position ie, the same value is saving in both 1st and 5th position.
The code I am using is:
holder.subQuestionAnswer.addTextChangedListener( new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
questionsModel.get(position).getQuestion_subquestion().get(0).setAnswer(holder.subQuestionAnswer.getText()
.toString());
Log.e("value", "no_active<>"+position+"<>"+questionsModel.get(position).getQuestion_subquestion().get(0).getAnswer().toString());
}
});
}
How can i avoid this?
It is because of recycling of view. Please check the following adapter. Use the logic according to your needs.
public class MultiSelectionProductAdapter extends ArrayAdapter<ProductListBean> {
private Context context;
private ArrayList<ProductListBean> productList;
private ArrayList<ProductListBean> mOriginalValues;
private LayoutInflater li;
public MultiSelectionProductAdapter(Context ctx, int simpleListItem1,
ArrayList<ProductListBean> data) {
super(ctx, simpleListItem1, data);
this.context = ctx;
this.productList = data;
li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return productList.size();
}
#Override
public ProductListBean getItem(int position) {
return productList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = li.inflate(R.layout.component_inventory_prod_list, null);
holder = new ViewHolder();
holder.tvProductName = (TextView) convertView.findViewById(R.id.tvProductName);
holder.tvProdShortCode = (TextView) convertView.findViewById(R.id.tvShortName);
holder.tvLastOrderedQty = (TextView) convertView.findViewById(R.id.tvLastOrderedQty);
holder.etQty = (EditText) convertView.findViewById(R.id.etQty);
holder.parentRL = (LinearLayout) convertView.findViewById(R.id.parentRL);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ProductListBean tempBean = productList.get(position);
holder.etQty.setId(position);
final String productName = tempBean.getProductName();
final String productCode = tempBean.getProductCode();
final String productShortCode = tempBean.getProductShortCode();
if (mSelectedProd != null && mSelectedProd.contains(productCode)) {
final int indexOfProd = mSelectedProd.indexOf(productCode);
holder.etQty.setText(mSelectedProducts.get(indexOfProd).getEnteredQty());
}
holder.tvProductName.setText(productName);
holder.tvProdShortCode.setText(productShortCode);
holder.tvLastOrderedQty.setText(tempBean.getLastOrderedQty());
holder.etQty.setText(tempBean.getEnteredQty());
holder.parentRL.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
holder.etQty.requestFocus();
}
});
holder.etQty.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
final int pos = holder.etQty.getId();
final String qty = holder.etQty.getText().toString();
if (qty.length() > 0) {
if (String.valueOf(qty.charAt(0)).equals("0")) {
holder.etQty.setError("Invalid Quantity");
holder.etQty.setText("");
} else {
productList.get(pos).setEnteredQty(holder.etQty.getText().toString());
}
} else {
productList.get(pos).setEnteredQty("");
}
}
});
return convertView;
}
static class ViewHolder {
TextView tvProductName, tvProdShortCode, tvLastOrderedQty;
EditText etQty;
LinearLayout parentRL;
}