how to retrieve value from all EditText in ListView - android

i have a structure like this in my ListView
TextView EditText
TextView EditText
TextView EditText
Btton
when i click on ok button. how to retrieve value from each EditText and print Sum of it on dialog box...any idea....?

Assuming your row layout is something like
LinearLayout
- TextView
- Edittext
You can use something like
for(int i =0;i<getListView.getChildCount();i++){
LinearLayout layout = getListView.getChildAt(i);
String text = layout.getChildAt(1).getText();
}

I would do it this way
Inside my ListAdapter, while creating rows, save a reference to list view in an ArrayList
On click of the button, get the array list from the adapter and iterate through all edittexts

Check out TextWatcher. Add it using:
myEditText1.addTextChangedListener(new GenericTextWatcher(myEditText1));
myEditText2.addTextChangedListener(new GenericTextWatcher(myEditText2));
myEditText3.addTextChangedListener(new GenericTextWatcher(myEditText3));
...
private class GenericTextWatcher implements TextWatcher{
private View view;
private GenericTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
public void afterTextChanged(Editable editable) {
String text = editable.toString();
switch(view.getId()){
case R.id.editText1_id:
// do something
break;
case R.id.editText2_id:
// do something
break;
case R.id.editText3_id:
// do something
break;
}
}
}

Related

ListView is mixing edittexts

I have a listView with edittexts and checkboxes. I understand that i need to store information about each item, to set up again when getting the view for each item, because it recycle the java objects for the view. Following this idea I've made a list for each input type. So, i have a ArrayList of strings for edittext, and one of Boolean for checkboxes. The checkboxes are working fine when scrolling, but edittext is not.
private List<String> restore;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, null);
}
input= convertView.findViewById(R.id.input);
input.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) {
}
#Override
public void afterTextChanged(Editable editable) {
restore.set(position, editable.toString());
}
});
input.setText(restore.get(position));
}
I mention the fact that the listview is inside a fragment, but i don't think this is the problem.I don't know what to tell more, to help me/you to figure out a solution...
Unlike setXXX(), method addTextChangedListener will not replace old value with a new value, but instead will add another TextWatcher to EditText each time you call it.
So you need to removeTextChangedListener before adding new one. But to remove it, you have to store it in a variable.
Solution:
Use ViewHolder pattern.
Add a TextWatcher variable to the ViewHolder.
Before adding new TextWatcher remove old one.
Write your new created TextWatcher to the ViewHolder after you create it, and only then use it in addTextChangedListener.
Alternatively to using ViewHolder, you may just create another List<TextWatcher>, and store TextWatchers there.
Problem is with the position. You're using wrong position while setting value in restore list. Make use of setTag method to hold the position
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item, null);
}
final EditText input = convertView.findViewById(R.id.input);
input.setTag(position); //this will hold the actual position of view
input.addTextChangedListener(new MyTextWatcher(input));
input.setText(restore.get(position));
}
private class MyTextWatcher implements TextWatcher{
EditText editText;
public MyTextWatcher(EditText editText){
this.editText = editText;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
restore.set(editText.getTag(), editable.toString()); //here you use the position of view which is being edited
}
}

Linked EditText Boxes for Paste

I have four EditText boxes that together make up a value. Each box should contain 1 number. When I enter a number into one box the focus should move to the next box. I have "faked" a link between the boxes by modifying the focus when the text is changed. The following code works but I want to allow for the user to paste in values that will then be split across the EditText boxes. So if I paste "123" in box[0], box[0] should contain "1" and box[1] should contain "2" etc. I attempted to add android:maxLength="1" to the XML but when I attempt to paste content, the maxLength validation removes all but the first character.
What is the best way to split the contents of a paste across the 4 EditText boxes?
EnterNumberLayout.java
public class EnterNumberLayout extends LinearLayout {
EditText[] textBoxes;
public static final int NUMBER_OF_ENTRIES = 4;
public EnterNumberLayout(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOrientation(HORIZONTAL);
textBoxes = new EditText[NUMBER_OF_ENTRIES];
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
for (int i = 0; i < NUMBER_OF_ENTRIES; i++){
EditText et = (EditText) inflater.inflate(R.layout.number_box, null);
//et.setOnKeyListener(new BackspaceKeyListener(et));
et.addTextChangedListener(new MoveFocusWatcher(et));
et.setTag(i);
textBoxes[i] = et;
this.addView(et, i);
}
}
private class MoveFocusWatcher implements TextWatcher {
private View view;
public MoveFocusWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if ((int) this.view.getTag() < NUMBER_OF_ENTRIES - 1) {
(textBoxes[(int) this.view.getTag() + 1]).requestFocus();
}
}
public void afterTextChanged(Editable s) {}
}
}
number_box.xml
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="number|none"
android:ellipsize="start"
android:gravity="center_horizontal|center_vertical"
android:imeOptions="actionNext"/>
There are probably a few ways to do this, but I'd probably remove the text limit of 1 on the edit text and manage the length with a text watcher.
Here, if text is pasted into the first edit1 then the text watcher will split the values up into the other edit text fields. You need to be careful when changing text in the afterTextChanged callback since the change will initiate another call to the method. Since the text length in edit1 is only one after our processing, the next callback does nothing.
public class TextGroup extends LinearLayout {
EditText edit0;
EditText edit1;
EditText edit2;
EditText edit3;
public TextGroup(Context context, AttributeSet attrs) {
super(context);
View view = LayoutInflater.from(context).inflate(R.layout.edit_text_special, null);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
edit0 = (EditText) view.findViewById(R.id.edit_text0);
edit1 = (EditText) view.findViewById(R.id.edit_text1);
edit2 = (EditText) view.findViewById(R.id.edit_text2);
edit3 = (EditText) view.findViewById(R.id.edit_text3);
edit1.addTextChangedListener(watcher);
this.addView(view, lp);
}
TextWatcher watcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable editable) {
if ( edit1.getText().length() >= 3) {
edit3.setText(String.valueOf(edit1.getText().toString().charAt(2)));
}
if ( edit1.getText().length() >= 2) {
edit2.setText(String.valueOf(edit1.getText().toString().charAt(1)));
edit1.setText(String.valueOf(edit1.getText().toString().charAt(0)));
}
}
};
}

EditText in Listview Strange selection behavior after scroll

I have a problem with EditText-fields in a listview. After i scroll some settings seem to be reset (selectAllOnFocus) and the selection cursor goes bananas.
I have a listview with a custom ArrayAdapter and a custom dataobject. In this case the object only holds one String (to simplify it).
My Activity
// adapter + content
List<ListviewObject> listViewContent = new ArrayList<ListviewObject>();
for(int i = 0; i < 50; i++) {
listViewContent.add(new ListviewObject("num: " + i));
}
adapter = new CustomListAdapter(AddNewPerson.this, R.layout.list_item, listViewContent);
// list
ListView mListView = (ListView)findViewById(R.id.sample_list);
mListView.setItemsCanFocus(true);
mListView.setAdapter(adapter);
My Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HolderObject holder = null;
if(convertView == null) {
convertView = mLayoutInflater.inflate(layoutResourceId, parent, false);
holder = new HolderObject();
holder.name = (TextView) convertView.findViewById(R.id.txt);
convertView.setTag(holder);
} else {
holder = (HolderObject) convertView.getTag();
}
holder.lvObject = items.get(position);
setNameTextChangeListener(holder);
// Retrieve the correct value
holder.name.setText(holder.lvObject.getName());
return convertView;
}
public static class HolderObject {
ListviewObject lvObject;
TextView name;
}
private void setNameTextChangeListener(final HolderObject holder) {
holder.name.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Update the value
holder.lvObject.setName(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void afterTextChanged(Editable s) { }
});
}
To fix all the focusproblems I found in other threads I've set:
.setItemsCanFocus(true) on the listview
android:descendantFocusability="beforeDescendants" in the activity XML
android:windowSoftInputMode="adjustPan" in the manifest XML
Focussing and editing text works fine. When I scroll the correct values are held and all this seems to work fine.
Before I scroll and I click on some of the EditTexts this happens. (Last focused blurs, clicked one focuses, content is selected)
http://imgur.com/eeIKhCv
After I scroll down and up again, and do the same clicks as before, this happens.
http://imgur.com/75mjPc3
This is due to listView recycling mechanism. To know more about listview recycling mechanism you can refer this link
in your case you avoid the problem by storing a last focused editText and In getView set focus to only last stored integer and skip other position. hope this help you...
It's quite easy:
Declare a String[] to keep track each EditText's input inside the afterTextChanged() of "addTextChangedListener().
Becareful of the order:
viewHolder.editText.removeTextChangedListener(viewHolder.textWatcher);
viewHolder.textWatcher = 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) {
}
#Override
public void afterTextChanged(Editable editable) {
mInputs[position] = editable.toString(); //record input
viewHolder.editText.setSelection(viewHolder.editText.getText().length()); //set cursor to the end
}
};
viewHolder.editText.addTextChangedListener(viewHolder.textWatcher);
viewHolder.editText.setText(mInputs[position]);
Add android:windowSoftInputMode="adjustPan" to your Activity in AndroidManifest file.
Good luck!

how to take the value form edittext in a listview?

I have a custom list with one textView and one
edit text in each row. My question is: whenever user enters
any number inside the edittext,at that time i want to take the
value from the edittext and add it with the previous value and
displayed in the top textview.
For eg. Say inside number of edittext i entered 10 in any
edittext. 10is the first number entered.then it is going to add
with 0.after that if he enter 15 in another edittext,then 10+15 = 25
should be displayed in the top textview.
I got it...
That was as simple as using setOnFocusListener. If the focus gets lost from the edit text.at that the boolean hasFocus parameter gets false. and we can easily collect the value inside the edit text. But thanks for you support guys. Thanks 1ce again.
try this
String content = edtEditText.getText().toString();
tvTextView.setText(content);
You have to Use A TextWatcher on the EditText View like this for That:
EditText editText1 = (EditText) findViewById(R.id.e1);
TextWatcher checker = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (ChecknotNull()) {
TextView1.setText(edittext1.getText().toString().trim());;
Note: You can Also Go on Concating the values with the
previous values Of the TextView(InShort,Perform Logic Here)
}
}
private boolean ChecknotNull() {
return editText1.getText().toString().trim().length() > 0;
}
};
//Set the checker method for the EditText View like this Way
editText1.addTextChangedListener(checker);
I am not sure,this would help...but you can try with this:
Get a setOnFocusListener on your edit text like:
mEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean arg1) {
int s=Integer.parseInt(mEditText.getText().toString());
int ps=Integer.parseInt(mTextView.getText().toString());
mTextView.setText((s+ps)+"");
mEditText.setText("");// clear editText after adding its value to textview
}
});
don't forget to empty the edittext when focus is gone,otherwise when user would click onto edittext even to delete previous one,value would again be added to your textview.
In the Adapter, do this:
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder = new ViewHolder();
p = values.get(position);
if (vi == null) {
vi = inflater.inflate(R.layout.feed_items, null);
holder.text = (TextView) vi.findViewById(R.id.tv);
holder.editText = (EditText) vi.findViewById(R.id.et);
holder.editText.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
i++;
int n = Integer.parseInt(holder.text.getText().toString());
int m = Integer.parseInt(s.getText().toString());
holder.text.setText("" + n + m);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
return vi;
}

Android Handling many EditText fields in a ListView

Just a basic question: If I have several dozen EditText fields that are part of a ListAdapter, how can the individual EditText fields know to which row they belong?
Currently I am using TextWatcher to listen for text input. I have tried extending TextWatcher so that I can pass in the position of the EditText to TextWatcher's constructor.
However, when the soft keyboard pops up, the positions that correspond to the various EditText fields shuffle.
How can I track the EditText fields to their proper position?
I am using a GridView to lay things out. The layout of each item is an ImageView with a TextView and EditText field below it.
The text for each EditText is held in a global String array called strings. It is initially empty, and is updated by my TextWatcher class.
public void initList()
{
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, R.layout.shape, strings)
{
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.shape, null);
}
final String theData = getItem(position);
final EditText editText = (EditText) convertView.findViewById(R.id.shape_edittext);
editText.setText(theData);
editText.addTextChangedListener(
new MyTextWatcher(position, editText)
);
ImageView image = (ImageView) convertView.findViewById(R.id.shape_image);
image.setBackgroundResource(images[position]);
TextView text = (TextView) convertView.findViewById(R.id.shape_text);
if (gameType == SHAPES_ABSTRACT)
text.setText("Seq:");
else
text.setVisibility(View.GONE);
return convertView;
}
#Override
public String getItem(int position) { return strings[position]; }
};
grid.setAdapter(listAdapter);
}
private class MyTextWatcher implements TextWatcher {
private int index;
private EditText edittext;
public MyTextWatcher(int index, EditText edittext) {
this.index = index;
this.edittext = edittext;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
public void afterTextChanged(Editable s) { strings[index] = s.toString(); }
public void setIndex(int newindex) { index = newindex; }
}
When I click into the first EditText (see picture), the EditText shifts to the one under the smiley face.
Not taking into account if this is a good UI design, here's how you'd do it:
public class TestList
{
public void blah()
{
ArrayAdapter<DataBucket> listAdapter = new ArrayAdapter<DataBucket>()
{
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.testlayout, null);
}
final DataBucket dataBucket = getItem(position);
final EditText editText = (EditText) convertView.findViewById(R.id.theText);
editText.setText(dataBucket.getSomeData());
editText.addTextChangedListener(new TextWatcher()
{
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
public void afterTextChanged(Editable editable)
{
dataBucket.setSomeData(editable.toString());
}
});
return convertView;
}
};
}
public static class DataBucket
{
private String someData;
public String getSomeData()
{
return someData;
}
public void setSomeData(String someData)
{
this.someData = someData;
}
}
}
'DataBucket' is a placeholder. You need to use whatever class you created to store the data that gets put into and edited in the edit text. The TextWatcher will have a reference to the data object referenced. As you scroll, the edit text boxes should get updated with current data, and text changes should be saved. You may want to track which objects were changed by the user to make data/network updates more efficient.
* Edit *
To use an int position rather than directly referencing the object:
ArrayAdapter<DataBucket> listAdapter = new ArrayAdapter<DataBucket>()
{
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.testlayout, null);
}
final DataBucket dataBucket = getItem(position);
final EditText editText = (EditText) convertView.findViewById(R.id.theText);
editText.setText(dataBucket.getSomeData());
editText.addTextChangedListener(new TextWatcher()
{
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
public void afterTextChanged(Editable editable)
{
getItem(position).setSomeData(editable.toString());
}
});
return convertView;
}
};
* Edit Again *
I feel compelled to say for posterity, I wouldn't actually code it this way. I'd guess you want a little more structured data than a String array, and you're maintaining the String array outside, as well as an ArrayAdapter, so its sort of a weird parallel situation. However, this will work fine.
I have my data in a single String array rather than a multi-dimensional array. The reason is because the data model backing the GridView is just a simple list. That may be counterintuitive, but that's the way it is. GridView should do the layout itself, and if left to its own devices, will populate the row with variable numbers of cells, depending on how much data you have and how wide your screen is (AFAIK).
Enough chat. The code:
public class TestList extends Activity
{
private String[] guess;
//Other methods in here, onCreate, etc
//Call me from somewhere else. Probably onCreate.
public void initList()
{
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, /*some resourse id*/, guess)
{
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = LayoutInflater.from(getContext()).inflate(R.layout.testlayout, null);
}
final String theData = getItem(position);
final EditText editText = (EditText) convertView.findViewById(R.id.theText);
editText.setText(theData);
editText.addTextChangedListener(
new MyTextWatcher(position)
);
return convertView;
}
};
gridView.setAdapter(listAdapter);
}
class MyTextWatcher extends TextWatcher {
private int position;
public MyTextWatcher(int position) {
this.position = position;
}
public void afterTextChanged(Editable s) {
guess[position] = s.toString();
}
// other methods are created, but empty
}
}
To track the row number, each listener in EditText has to keep a reference to an item in a list and use getPosition(item) to get the position in a ListView. My example uses Button but I think that it can be applied to EditText.
class DoubleAdapter extends ArrayAdapter<Double> {
public DoubleAdapter(Context context, List<Double> list) {
super(context, android.R.layout.simple_list_item_1, list);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_row, null);
}
// keep a reference to an item in a list
final Double d = getItem(position);
TextView lblId = (TextView) convertView.findViewById(R.id.lblId);
lblId.setText(d.toString());
Button button1 = (Button) convertView.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// the button listener has a reference to an item in the list
// so it can know its position in the ListView
int i = getPosition(d);
Toast.makeText(getContext(), "" + i, Toast.LENGTH_LONG).show();
remove(d);
}
});
return convertView;
}
}
It might be worth considering whether you need the edit texts to be stored in the list cells? It seems a little bit unnecessary when the user will only be editing one at a time.
Whilst I do not know how your app is designed I would recommend rethinking your user experience slightly so that when an list item is pressed a single text edit appears for them to edit. That way you can just get the list items reference as you normally would with a list adapter, store it whilst the user is editing and update it when they have finished.
i'm not sure if that's a nice design you have, as the EditText content will have a good chance of having problems (shuffling content, missing text) once your listview is scrolled. consider trying out m6tt's idea.
but if you really want to go your way, can you post some code, specifically of your TextWatcher?
I tried to solve this and as you can see there is a simple method - I am posting the answer here as it might be useful for someone.
Not able to get the position when list view -> edit text has a text watcher.
This is the solution that worked for me :
In get view -
when I add the text watcher listener to edit text, I also added the below line
edittext.setTag(R.id.position<any unique string identitiy>, position)
in your afterTextChanged -
int position = edittext.getTag(R.id.position)
Gives the correct position number and you can do modifications based on the position number.

Categories

Resources