Android Handling many EditText fields in a ListView - android

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.

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
}
}

Text change event inside listview in android

I am new to android and I have a editText inside the listview what I want when the user puts some text or value into the editText this value should get displayed into a textview inside same listitem.I tried to get it done in getView of the custom adapter but its not working for me.My code is like this:
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.list_style_task
, parent, false);
}
LItem p = getProduct(position);
tvAQuantity=((TextView) view.findViewById(R.id.tvAQuantity )) ;
((TextView) view.findViewById(R.id.tvMaterial )).setText(p.getMName() );
((TextView) view.findViewById(R.id.tvTask )).setText(p.getTName() );
tvBQuantity=((TextView) view.findViewById(R.id.tvBQuantity )) ;
tvBQuantity.setText(p.getBQ());
etQuantity=(EditText)view.findViewById(R.id.etTaskQuantity);
etQuantity.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(Integer.parseInt(s.toString())<=Integer.parseInt(tvBQuantity.getText().toString()))
{
tvAQuantity.setText(s.toString());
}
else
{
tvAQuantity.setText(tvBQuantity.getText());
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
// CheckBox cbBuy = (CheckBox) view.findViewById(R.id.checkbox);
//cbBuy.setOnCheckedChangeListener(myCheckChangList);
// cbBuy.setTag(position);
// cbBuy.setChecked(p.selected);
return view;
}
Need your valuable suggestions.
2 Alternatives are:
You have to update respected string into your model class which is to be displayed into textview.
You can call notifyDataSetChanged(); after setText() method in your adapter.This will refresh your List View.
Instead setting text to TextView try updating string value in your list model. You are facing this issue because your model is not getting updated on textchange event.
if(Integer.parseInt(s.toString())<=Integer.parseInt(tvBQuantity.getText().toString()))
{
//update string value in your model.
//tvAQuantity.setText(s.toString());
}
else
{
//update string value in your model.
//tvAQuantity.setText(tvBQuantity.getText());
}

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!

Using Textwatcher causes weird issue in edittext search bar which's included at the top of adapter

In the application, I have a customized adapter which extends BaseAdapter. The adapter includes a header of two items, one of which is a search bar.
What I'm trying to do is to input text on the bar to search content on the listview, using my adapter. The challenge here is for Samsung Galaxy Note II, when I enter a character, the search bar shows what it is. However, for the second character I want to input, the bar shows nothing and it seems the previous character was cleared too. For any other devices, this works well. I have no idea of this. Can any guru knows the solution?
Here follows some snippet of ResearveHeaderAdapter:
#Override
public View getView(final int position, final View convertView, final ViewGroup parent)
{
View rowView = null;
HeaderItem header = mHeaderDef.get(position);
if (header != null)
{
switch(header)
{
case REFRESHBAR:
{
rowView = updateRefreshRow(convertView, parent);
break;
}
case SEARCHBAR:
{
rowView = updateSearchRow(convertView, parent);
break;
}
default:
{
rowView = super.getView(position, convertView, parent);
break;
}
}
}
else
{
rowView = super.getView(position, convertView, parent);
}
return rowView;
}
private View updateSearchRow(final View convertView, final ViewGroup parent)
{
mCacheSearchView = mAllContentInflator.inflate( R.layout.search_bar_item, parent, false );
mEditText = (ClearableEditText) mCacheSearchView.findViewById(R.id.topSearchBar);
mEditText.setText(getSearchVarString());
mEditText.setOnKeyListener(getSearchListener());
mEditText.addTextChangedListener(getSearchTextWatcher());
String search = getSearchVarString();
String stxt = mEditText.getText().toString();
if (getSearchVarString().trim().length() > 0)
{
mEditText.requestFocus();
}
mEditText.setEnabled(true);
return mCacheSearchView;
}
Its subclass AllContentAdapter:
public class AllContentAdapter extends ReserveHeaderAdapter
{
public AllContentAdapter(Activity callerContext,
MediaObjectManager manager, boolean sensitive,
MediaPolicy displayPolicy) {
super(callerContext, manager, sensitive, displayPolicy);
// TODO Auto-generated constructor stub
super.appendHeaderItem(HeaderItem.REFRESHBAR);
super.appendHeaderItem(HeaderItem.SEARCHBAR);
}
private static OnKeyListener mOnKeySearchListener = null;
private static TextWatcher mSearchTextWatcher = null;
private static OnClickListener mOnClickRefreshListener = null;
private static String mSearchString = "";
#Override
protected String getSearchVarString()
{
return mSearchString;
}
#Override
protected void setSearchVarString(String searchString)
{
mSearchString = searchString;
}
#Override
protected OnKeyListener getSearchListener()
{
return mOnKeySearchListener;
}
#Override
protected TextWatcher getSearchTextWatcher()
{
return mSearchTextWatcher;
}
#Override
protected OnClickListener getClickRefreshListener()
{
return mOnClickRefreshListener;
}
public void setOnClickRefreshListener(OnClickListener listener)
{
mOnClickRefreshListener = listener;
}
public void setSearchOnKeyListener(OnKeyListener listener)
{
mOnKeySearchListener = listener;
}
public void addTextChangedListenerForSearch(TextWatcher listener)
{
mSearchTextWatcher = listener;
}
So for the desired Activity, I called the adapter.addTextChangedListenerForSearch(new TextWatcher()) which is like this:
((AllContentAdapter) mAdapter).addTextChangedListenerForSearch(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
String stxt = s.toString();
((AllContentAdapter) mAdapter).setSearchVarString(stxt);
// some handle code omitted...
AllContentScreen.this.loadSearchFilter();// do some filter to search desired content
}
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
});
The real result is that on Note II, when entering the second character, (Editable)s catches noting but empty string. Why?
That's strange. I'm willing to bet that the Note uses a special InputConnection. http://developer.android.com/reference/android/view/inputmethod/BaseInputConnection.html
which produces custom Editables. You may want to set a custom Editable.Factory on your search EditText. Also, look at setting a SpanWatcher to monitor span activity, especially the composing spans. Here's an example from a RichEditText library I created.
// Replaces the default edit text factory that produces editables
// which our custom editable and listener
public class TextFactory extends Editable.Factory{
#Override
public Editable newEditable(final CharSequence source){
return new RichTextStringBuilder(source,
mSpanWatcher);
}
}
At the least, this will let you see a better picture of what's happening.
From debugging process, I probably found what problem was for this special device and solved this issue therefore. That is, when EditText.getText().getString() is not empty, we'll show the searchbar and setSelection(position). The 'position' here represents the searchbar. For any other devices, this works fine. For Note II, it seems that if we want setSelection for the position of EditText, this function will clear the entered text and return empty string. So the solution is to avoid this function by using a flag to see whether the EditText has empty string or not and do catch what is entered in the search bar.

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;
}

Categories

Resources