Scrolling issue in listview - android

//Filling the ArrayList From the Fragment
gridmodel = new TypeTruckPogo("Truck 14 wheel",-1,false);
list.add(gridmodel);
gridmodel = new TypeTruckPogo("Truck 16 wheel",-1,false);
list.add(gridmodel);
final TypeOfTruckAdapter truckAdapter=new TypeOfTruckAdapter(context, list);
truckListView.setAdapter(truckAdapter);
//My POGO CLASS
public class TypeTruckPogo{
String typeOfTruckName;
int nmbrOfTruck;
boolean isEditTextVisiable;
public TypeTruckPogo(String typeOfTruckName,int nmbrOfTruck,boolean isEditTextVisiable){
this.typeOfTruckName=typeOfTruckName;
this.nmbrOfTruck=nmbrOfTruck;
this.isEditTextVisiable=isEditTextVisiable;
}
public String getTypeOfTruckName() {
return typeOfTruckName;
}
public String setTypeOfTruckName(String typeOfTruckName) {
this.typeOfTruckName = typeOfTruckName;
return typeOfTruckName;
}
public int getNmbrOfTruck() {
return nmbrOfTruck;
}
public Integer setNmbrOfTruck(int nmbrOfTruck) {
this.nmbrOfTruck = nmbrOfTruck;
return nmbrOfTruck;
}
public boolean isEditTextVisiable() {
return isEditTextVisiable;
}
public Boolean setIsEditTextVisiable(boolean isEditTextVisiable) {
this.isEditTextVisiable = isEditTextVisiable;
return isEditTextVisiable;
}
}
// My Adapter Class,this class have 20 item in the list,at first time it's showing 8 item , when user press on single row then editText become visible and if user press the same position twice the editText become inviable,But the problem is that when user tap on any position(let say he tapped on position 0) then editText is visible but when i scroll down then other editText is also becoming visible sometime position 8 sometime 15.ANY HELP APPRECIATED !!!! Single row contain textView and editText
public class TypeOfTruckAdapter extends BaseAdapter{
List<TypeTruckPogo> list;
Context context;
LayoutInflater inflater;
public String[] Current;
TypeTruckPogo typeTruckPogo;
public static HashMap<Integer,String> truckHashMap=new HashMap<Integer,String>();
public TypeOfTruckAdapter( Context context,List<TypeTruckPogo> list) {
this.list = list;
this.context = context;
for(int i=0;i<list.size();i++)
{
truckHashMap.put(i,"");
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
class Viewholder{
TextView name;
EditText nmbrOfTruck;
int ref;
Viewholder(View view) {
name = (TextView) view.findViewById(R.id.textView1);
nmbrOfTruck = (EditText) view.findViewById(R.id.et_nmbr_of_truck_id);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Viewholder holder;
typeTruckPogo = list.get(position);
if(convertView==null){
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.single_row_for_type_of_truck, parent, false);
holder = new Viewholder(convertView);
convertView.setTag(holder);
}else{
holder = (Viewholder)convertView.getTag();
}
// For position zero i have to set the text color to blue color,else dark gray color
if(position==0){
holder.name.setTextColor(context.getResources().getColor(R.color.blue_color));
}else{
holder.name.setTextColor(context.getResources().getColor(R.color.darkgray));
}
// setting the name on the textview
holder.name.setText(list.get(position).getTypeOfTruckName());
//setting the tag on edittext
holder.nmbrOfTruck.setTag(position);
//setting the viewholder position
holder.ref = position;
// clicking on listview making edittext to appear (initially edittext is invisiable)
// if edittext is visiable make it invisiable and if it is invisiable make it visiable
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.findViewById(R.id.et_nmbr_of_truck_id).getVisibility() == View.VISIBLE) {
v.findViewById(R.id.et_nmbr_of_truck_id).setVisibility(View.INVISIBLE);
} else {
v.findViewById(R.id.et_nmbr_of_truck_id).setVisibility(View.VISIBLE);
}
}
});
// if user write on editText save the input by the user in specified position
//truckHashMap is hashmap where I saving the position as a key and value as the user Input
holder.nmbrOfTruck.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
Current = new String[holder.ref];
truckHashMap.put(position, s.toString().trim());
}
});
// Setting the User Input at specified Position
holder.nmbrOfTruck.setText(truckHashMap.get(position));
Config.colorFont(context, null, holder.name, null);
return convertView;
}

You have to use else statement which set your default text color in your adapter:
...
if(position==0){
holder.name.setTextColor(context.getResources().getColor(R.color.blue_color));
} else {
// here set your default text color black for example
holder.name.setTextColor(context.getResources().getColor(R.color.black_color));
}
...
Hope it helps!

Where your else condition ?
if(position==0)
{
holder.name.setTextColor(context.getResources().getColor(R.color.blue_color));
} else {
// Calling when if Condition not Satisfied .
holder.name.setTextColor(context.getResources().getColor("Your_Color"));
}

Related

Listview with edittext value lost while scrolling

I'm not expert in android listview and Edittext. However, I am stuck with some annoying problem regarding this issue. I am fetching values in listview without any problem but when I input something in Edittext and scroll down the value of EditText changes it's position. Here is my code.
//product class
public class products {
public String prod_sl;
public String prod_code;
public String product_name;
public String product_desc;
public String prod_qnty;
public String prod_uom;
public String prod_price;
boolean ShowName;
public products(String psl, String pcode,String Name, String Desc, String UOM) {
this.prod_sl = psl;
prod_code = pcode;
prod_qnty="";
prod_price ="";
product_name=Name;
product_desc=Desc;
prod_uom =UOM;
}
/* public boolean isShowName() {
return ShowName;
}
public void setShowName(boolean showName) {
ShowName = showName;
}*/
//sl
public String getSl() { return prod_sl; }
public void setSl(String psl) { this.prod_sl = psl; }
//product code
public String getCode() { return prod_code; }
public void setCode(String pcode) { this.prod_code = pcode; }
//product Name
public String getName() { return product_name; }
public void setName(String product_name) { this.product_name = product_name; }
//product desc
public String getDesc() { return product_desc; }
public void setDesc(String product_desc) { this.product_desc = product_desc; }
//product UOM
public String getUom() { return prod_uom; }
public void setUom(String prod_uom) { this.prod_uom = prod_uom; }
// product quantity
public String getQnty() {
return prod_qnty; }
public void setQnty(String prod_qnty) {
this.prod_qnty = prod_qnty; }
//product price
public String getPrice() {
return prod_price; }
public void setPrice(String prod_price) {
this.prod_price = prod_price; }
}
And here is the adapter class
public class ListViewAdapter extends ArrayAdapter<products> {
Context mContext;
View v;
private String[] arrTemp;
LayoutInflater inflater;
ArrayList<products> arrayproducts;
public String[] scoresToUpdate=new String[1000];
//public String Array scoresToUpdate =scoresToUpdate[];
public static EditText edit_qnty,prod_price;
public static HashMap<Integer,String> myList=new HashMap<Integer,String>();
public ListViewAdapter(Context context, int resource, ArrayList<products> arrayproducts) {
super(context, resource);
this.mContext = context;
this.arrayproducts = arrayproducts;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
try {
final int pos=position;
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_adapter_view, null);
holder = new ViewHolder();
holder.prod_sl = (TextView) convertView.findViewById(R.id.prod_sl);
holder.prod_code = (TextView) convertView.findViewById(R.id.prod_code);
holder.txtTitle = (TextView) convertView.findViewById(R.id.adapter_text_title);
holder.txtDescription = (TextView) convertView.findViewById(R.id.adapter_text_description);
holder.prod_uom = (TextView) convertView.findViewById(R.id.prod_uom);
holder.prod_qnty = (EditText) convertView.findViewById(R.id.prod_qnty);
holder.prod_price = (EditText) convertView.findViewById(R.id.prod_price);
// edit_qnty = (EditText) convertView.findViewById(R.id.prod_qnty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
// holder.prod_qnty.setText(scoresToUpdate[pos]);
}
holder.ref = position;
products prod = arrayproducts.get(position);
holder.prod_sl.setText("" + position);
holder.prod_code.setText(prod.getCode());
holder.txtTitle.setText(prod.getName());
holder.txtDescription.setText(prod.getDesc());
holder.prod_uom.setText(prod.getUom());
Log.e("row values",""+position+"\t-"+prod.getCode()+""+prod.getName()+""+prod.getDesc()+""+prod.getUom());
// holder.prod_qnty.setText(arrTemp[position]);
holder.prod_qnty.setText(scoresToUpdate[position]);
holder.prod_qnty.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
arrayproducts.get(pos).setQnty(holder.prod_qnty.getText().toString().trim());
myList.put(pos,arg0.toString().trim());
if (!arg0.equals("0")){
scoresToUpdate[pos] = arg0.toString();
Log.e("On text Change","Pos"+pos+"\tqnty:"+holder.prod_qnty.getText().toString().trim()+"\t Args: "+arg0.toString());
}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
Log.e("After Text change","Pos"+holder.ref+"\tqnty:"+holder.prod_qnty.getText().toString().trim());
// arrTemp[holder.ref] = arg0.toString();
}
});
//holder.prod_qnty.setText(myList.get(position));
holder.prod_qnty.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
Log.e("Current Qnty",edit_qnty.getText().toString().trim());
if(holder.prod_qnty.getText().toString().trim().equals("0")){
holder.prod_qnty.setText("");
}
String inttext = (""+holder.prod_qnty.getText().toString().trim());
if (!inttext.equals("0")){
holder.prod_price.setText("");
}
return false;
//return true;
}
});
//Using setOnclickListener not setOnCheckedChangeListener
//we need to update adapter once we finish with editing
/* holder.prod_qnty.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
final int pos = v.getId();
final EditText Qnty = (EditText) v;
Log.e("Qnty For the positon","POS: "+pos+"\tQnty: "+Qnty.getText().toString().trim());
arrayproducts.get(pos).setQnty(Qnty.getText().toString().trim());
//holder.prod_qnty.setText(Caption.getText().toString().trim());
}
}
});*/
/* holder.prod_price.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
arrayproducts.get(position).setPrice(Caption.getText().toString().trim());
}
}
});
*/
return convertView;
}
catch(Exception e){
Toast.makeText(mContext, "!!!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
Log.e("Exception:",""+e.toString());
}
return convertView;
}
/* #Override
public int getCount() {
return arrayproducts.size();
}*/
#Override
public int getCount() {
// TODO Auto-generated method stub
if(arrayproducts != null && arrayproducts.size() != 0){
return arrayproducts.size();
}
return 0;
}
/*#Override
public Objects getItem(int position) {
// TODO Auto-generated method stub
return arrayproducts[position];
}*/
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public void getQnty(){
if(edit_qnty.getText().toString().trim().equals("0"))
edit_qnty.setText("");
}
static class ViewHolder {
TextView prod_sl;
TextView prod_code;
TextView txtTitle;
TextView txtDescription;
TextView prod_uom;
EditText prod_qnty,prod_price;
TextWatcher qtyWatcher;
TextWatcher priceWatcher;
int ref;
}
}
Please help me, With regards
This works for me !
if (holder.qtyWatcher != null) {
holder.txtFourth.removeTextChangedListener(holder.qtyWatcher);
}
// Create the TextWatcher corresponding to this row
holder.qtyWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
if(s.toString().equals("")||s.toString().equals("0")){
arrayproducts.get(position).setQnty("0");
}
else{
arrayproducts.get(position).setQnty(s.toString());
}
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
};
not sure that listview and recycleview can be used like this as they involve a recycling mechanism to reuse created views and rebind data from arrays or cursors as users scroll down/up to see more data. in other words, the row views created are with limited number to only fill the screen (with few extra from both sides) and they are recycled and reused to show data, if you insert a price or quantity for one product line, how the recycling process will rebind to show same data you inserted or show it on same position, I doubt this is possible.
I suggest that you restructure your application on parent/child base. show on list parent data, for example fixed product data, when users click one product line another screen opens so users insert new data, for example the price for that particular product line, the layout of your child screen will contains the edittext and any other data input views, in such case you need to integrate SQLite database so that you persist the new data provided by users.
hope this may provide you with some useful ideas to help you achieve your target.

How to update values in database using an update image button in custom list adapter?

This is my custom list adapter. I want to update the values in table using the update ImageButton in the list. On clicking it, the old values should be shown in a new activity and then the edited value must be stored in the database. However, I am unable to pass an intent inside the onClick() method.
Please suggest me a solution
public class CustomListAdapter extends BaseAdapter implements ListAdapter
{
private ArrayList<String> list = new ArrayList<String>();
private Context context;
OnItemSelectedListener onItemSelectedListener;
public int pos;
String pass,pass2,edit,epass;
public CustomListAdapter(List list, Context context) {
this.list = (ArrayList<String>) list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
//pass2 = list.toString();
return list.get(pos);
}
//#Override
//public Long getItemId(int pos) {
//
// //just return 0 if your list items do not have an Id variable.
//}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_custom_list, null);
}
//Handle TextView and display string from your list
final TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
ImageButton deleteBtn = (ImageButton)view.findViewById(R.id.delete_btn);
ImageButton editBtn = (ImageButton)view.findViewById(R.id.edit_btn);
//Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position);
pass = listItemText.getText().toString();
notifyDataSetChanged();
pass2 = pass.substring(0,pass.indexOf(' '));
System.out.println(pass2);
Moneydb.delete(pass2);
}
});
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v2) {
// TODO Auto-generated method stub
edit=listItemText.getText().toString();
epass = listItemText.getText().toString();
edit = epass.substring(0,epass.indexOf(' '));
Moneydb.edit(edit);
}
});
return view;
}
protected Context getContext() {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
//return list.get(position).getId();
return 0;
}
public void clear() {
//CustomListAdapter collection = null;
// TODO Auto-generated method stub
list.clear();
notifyDataSetChanged();
}
I suggest you to assign and ContextMenu to your list view with two MenuItem, Edit and Delete and write associated code outside of adapter
or you can start Activity by :
Intent new_intent = new Intent(v.getRootView().getContext(),edit_activity.class);
new_intent.putExtra("Key","Value");
v.getRootView().getContext().startActivity(new_intent);
i think the first method is best ;)

Change the Background of Select/Click listview Item - Android

I am working on the quiz application.For that I am using listview for the dispaly the answers options, I want to change the listview background color when user select the listview item, If answer is correct then set the green background and wrong then set red background
I am tring so much, but i don,t get the solution.
Adapter class
public class ListviewAdapter extends BaseAdapter{
public List<String> Questions;
public Activity context;
public LayoutInflater inflater;
private int[] colors = new int[] { 0x30505050, 0x30808080 };
private String[] opt_no;
public static View change_color;
public ListviewAdapter(Activity context,List<String> answers, String[] que_opt_no) {
super();
this.context = context;
this.Questions = answers;
this.opt_no = que_opt_no;
//this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Questions.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return Questions.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
TextView txtquestion;
TextView txtquestion_no;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
// this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
String fontPath = "fonts/Face Your Fears.ttf";
if(convertView==null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.quiz_questions_listitem, null);
holder.txtquestion = (TextView) convertView.findViewById(R.id.textView_option);
holder.txtquestion_no = (TextView) convertView.findViewById(R.id.textView_option_no);
// holder.txtquestion .setTypeface(Typeface.createFromAsset(convertView.getContext().getAssets(),fontPath));
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
/* int colorPos = position % colors.length;
convertView.setBackgroundColor(colors[colorPos]); */
change_color = convertView;
// convertView.setBackgroundResource(R.drawable.listview_background);
holder.txtquestion.setText(Questions.get(position));
holder.txtquestion_no.setText(opt_no[position]);
return convertView;
}
/*public static void setbackground(){
String answer = SelectedAnswer.getAnswer();
if (Display_questions.currentQ.getAnswer().trim().equals(answer.trim()))
{
Toast.makeText(change_color.getContext(), "red",Toast.LENGTH_SHORT).show();
change_color.setBackgroundResource(R.drawable.listview_background);
//ListviewAdapter.change_color.setBackgroundResource(R.drawable.listview_background);
//Display_questions.currentGame.incrementRightAnswers();
}
else{
Toast.makeText(change_color.getContext(), "Blue",Toast.LENGTH_SHORT).show();
change_color.setBackgroundResource(R.drawable.listview_false_background);
//Display_questions.currentGame.incrementWrongAnswers();
}
}*/
}
Java class
public class Display_questions extends Activity{
public static Question currentQ;
public static GamePlay currentGame;
ListView listview;
ListviewAdapter adapter;
String que_opt_no[] = {"a) ","b)","c) ","d) "};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_questions);
listview = (ListView) findViewById(R.id.questions_list);
listview.setItemsCanFocus(false);
GoToNextQuestion();
}
private void GoToNextQuestion() {
// TODO Auto-generated method stub
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {
String selectedFromList = (String) listview.getItemAtPosition(pos);
SelectedAnswer.setAnswer(selectedFromList);
if (!checkAnswer(pos)) return;
if (currentGame.isGameOver()){
Intent i = new Intent(Display_questions.this, Display_result.class);
i.putExtra("Timer_Value", TimerTime);
startActivity(i);
finish();
}
else{
GoToNextQuestion();
}
}
});
setQuestions();
}
private void setQuestions() {
// set the question text from current question
String question = currentQ.getQuestion().trim();
TextView qText = (TextView) findViewById(R.id.txt_questions);
qText.setText(question);
// set the available options
List<String> answers = currentQ.getQuestionOptions();
adapter = new ListviewAdapter(this,answers,que_opt_no);
listview.setAdapter(adapter);
}
static boolean checkAnswer(int selectedPosition) {
String answer = SelectedAnswer.getAnswer();
if (answer==null){
return false;
}
else {
AnswerStates state = AnswerStates.NONE;
if (currentQ.getAnswer().trim().equals(answer.trim()))
{
//listview.setBackgroundResource(R.drawable.listview_background);
currentGame.incrementRightAnswers();
state = AnswerStates.RIGHT;
}
else{
//ListviewAdapter.setbackground();
currentGame.incrementWrongAnswers();
state = AnswerStates.WRONG;
}
adapter.setSelectedAnswerState(selectedPosition, state);
adapter.notifyDataSetChanged();
return true;
}
}
}
Edit :
check My images :
1.)
2.)
Do you want to change the background of listview or the selected item when a correct answer is selected.
#Override
public void onItemClick(AdapterView<?> myAdapter, View myView, int pos, long mylng) {
String selectedFromList = (String) listview.getItemAtPosition(pos);
if(selectedFromList.equals("your_answer")) {
// to change the listview background
listview.setBackgroundColor(getResources().getColor(R.color.your_color_id));
// to change the selected item background color
myView.setBackgroundColor(getResources().getColor(R.color.your_color_id));
}
I would suggest to go with the following way:
Adapter class:
add storing of selected position and its state (CORRECT/INCORRECT) or color, e.g.:
public class ListviewAdapter extends BaseAdapter{
enum AnswerStates {
// Colors can be provided also for bg
WRONG(R.drawable.wrong_bg),
RIGHT(R.drawable.right_bg),
NONE(R.drawable.list_item_bg);
/** Drawable id to be used for answer state */
private int mBg;
private AnswerStates(int bg) {
mBg = bg;
}
/** getter for drawabale for answer state */
int getBg() {
return mBg;
}
}
...
/** Position of selected answer */
private int mSelectedPosition = -1;
/** State of selected answer */
private AnswerStates mSelectedAnswerState = AnswerStates.NONE;
...
/** Setter for selected answer */
public void setSelectedAnswerState(int selectedPosition, AnswerStates state) {
mSelectedPosition = selectedPosition;
mSelectedAnswerState = state;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
// Your stuff
...
if (position == mSelectedPosition) {
convertView.setBackgroundResource(mSelectedAnswerState.getBg());
} else {
// use default bg
convertView.setBackgroundResource(AnswerStates.NONE.getBg());
}
return convertView;
}
...
}
And Activity class:
public class Display_questions extends Activity{
...
// Added position parameter to the function
static boolean checkAnswer(int selectedPosition) {
//getSelectedAnswer();
String answer = SelectedAnswer.getAnswer();
if (answer==null){
return false;
}
else {
AnswerStates state = AnswerStates.NONE;
if (currentQ.getAnswer().trim().equals(answer.trim()))
{
// here set the background Green color
currentGame.incrementRightAnswers();
state = AnswerStates.RIGHT;
}
else{
// here set the background red color
//ListviewAdapter.setbackground();
currentGame.incrementWrongAnswers();
state = AnswerStates.WRONG;
}
adapter.setSelectedAnswerState(selectedPosition, state);
adapter.notifyDataSetChanged();
return true;
}
}
}
This way is more reliable than another answer, because it will work even if list with answers get scrolled and views get reused by list view.

EditText Content Changes on ListView Scroll

I have an Android application with an customized adapter that extends Cursor Adapter.
I overrided bindView and newview methods of CursorAdapter. Each of my ListView row contains an EditText. When I enter some text in EditText and scrolldown the ListView the content of the EditText text is moved to another EditText.
Can anyone help me in sorting out this issue to how to prevent EditText from reused its content when ListView is scrolled down.
Thanks in Advance,
Here is the code:
private class AddScreenArrayAdapter extends ArrayAdapter<AddScreenItems>{
ViewHolder viewHolder = null;
public String[] holder_values;
public AddScreenArrayAdapter(Context context, int textViewResourceId,
List<AddScreenItems> objects) {
super(context, textViewResourceId, objects);
holder_values = new String[objects.size()];
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.additem_row, null);
viewHolder = new ViewHolder();
viewHolder.label = (TextView) v.findViewById(R.id.label_add_item);
viewHolder.dbName=(TextView)v.findViewById(R.id.dbtable_name);
viewHolder.value = (EditText) v.findViewById(R.id.value_add_item);
viewHolder.value.addTextChangedListener(new TextWatcher()
{
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
holder_values[viewHolder.ref]= arg0.toString();
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// TODO Auto-generated method stub
}
});
v.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder) v.getTag();
}
AddScreenItems addScreenItems = addScreenItemsList.get(position);
if(addScreenItems!=null)
{
viewHolder.label.setText(addScreenItems.labelname);
viewHolder.dbName.setText(addScreenItems.databaseTableName);
// viewHolder.ref = position;
if (holder_values[position] != null)
{
viewHolder.value.setText(holder_values[position]);
}
else {
viewHolder.value.setText("");
}
}
return v;
}
}
static class ViewHolder {
public TextView label;
public EditText value;
public TextView dbName;
int ref;
}
If you're having problem after scrolling it's the view recycling that's messing you up. You basically need to set up an array to hold the contents of the EditTexts so when you scroll they don't get messed up.
Here's a link to another answer I gave on a similar topic. It ought to point the way for you. SO Answer
EDIT
I use setOnFocusChangeListener to run code when the user finishes an entry in the EditText box.
qty.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
LinearLayout parent = (LinearLayout) v.getParent();
EditText qtyTemp = (EditText) parent.findViewById(R.id.qty);
quantity[pos] = qtyTemp.getText().toString();
}
}
});

Android - EditText as search box doesn't work

I would like to enable search functionality to EditText. My requirement is like this:
when someone types with some letter, suppose the user types 'a', then it should show all the words which starts with 'a' should be shown as a drop down list. For example, if I first typed "copy" in the EditText, if again, I cleared the EditText and tried to type "co", then it should show the drop-down list "copy","come","cow"....
I want to enable this feature to my EditText view. It worked when I had a ListView with only a textview inside, but now that I have two textview in my ListView it doesn't work.
This is my activity:
public class sedactivity extends Activity {
ListView lview;
ListViewAdapter lviewAdapter;
EditText ed;
private static final String first[] = {
"America",
"Busta",
"Cactus",
"Fire",
"Garden",
"Hollywood",
"King",};
private static final String second[] = {
"Uniti",
"Chiusa",
"Verde",
"Fiamme",
"Aperto",
"Boulevard",
"Kong",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed = (EditText)findViewById(R.id.EditText1);
lview = (ListView) findViewById(R.id.listView2);
lviewAdapter = new ListViewAdapter(this, first, second);
System.out.println("adapter => "+lviewAdapter.getCount());
lview.setAdapter(lviewAdapter);
lview.setTextFilterEnabled(true);
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textlength=ed.getText().length();
arr_sort.clear();
for(int i=0;i<first.length;i++)
{
if(textlength<=first[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) first[i].subSequence(0, textlength)))
{
arr_sort.add(first[i]);
}
}
}
}});}
}
And this is my ListView Adapter
public class ListViewAdapter extends BaseAdapter{
Activity context;
String title[];
String description[];
public ListViewAdapter(Activity context, String[] title, String[] description) {
super();
this.context = context;
this.title = title;
this.description = description;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
}
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
return convertView;
}
}
I think an AutoCompleteTextView might be more suitable to implement this feature.
Check out this example to create your own Listener to check the values inside Edittext on key press event - How to implement your own Listener
Instead of extending BaseAdapter you extend ArrayAdapter. It implements the Filterable interface for you. In TextWatcher call getFilter().filter(text); method.
public void afterTextChanged(Editable s) {
listview.getAdapter().getFilter().filter(s);
}

Categories

Resources