I am using Custom Adapter (ListAdapter.java) that extends ArrayAdapter to fill ListView (List.java).
After that ListView row contains TextView and ToggleButton.
In List.java I can register click on ListView row:
sett_list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {
but how can I register click on ToggleButton, and get row position of that button?
EDIT: #MDMalik
In ListAdapter.java:
A):
View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.settings_row, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.option);
final ToggleButton toggle = (ToggleButton) rowView.findViewById(R.id.toggle);
B):
if (values2[position].equals("on")) {
toggle.setChecked(true);
} else {
toggle.setChecked(false);
}
C):
toggle.setTag(Integer.valueOf(position));
toggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), Integer.valueOf(position) + " : Click", Toast.LENGTH_SHORT).show();
}
});
That's it. Now I have position of clicked button. Thank you.
How can I write result to database now?
Something like this (not working):
toggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (toggle.isChecked() == true) {
checked = 1;
myDB = SQLiteDatabase.openOrCreateDatabase("database.db", null);
myDB.execSQL("UPDATE " + TableName + " SET on_off_ = 'on' WHERE sett_ = '" + values[position] + "'");
myDB.close();
} else {
checked = 0;
myDB = SQLiteDatabase.openOrCreateDatabase("database.db", null);
myDB.execSQL("UPDATE " + TableName + " SET on_off_ = 'off' WHERE sett_ = '" + values[position] + "'");
myDB.close();
}
}
});
A) As you have a CustomAdapter, you need to intalize your ToggelButton in getView.
B) Your String array should have a default value for that button, either true or false that can be achieve something like this
String chkCondition = hmap.get("chk").toString().toLowerCase();
Boolean blnChk = true;
if (chkCondition.equals("false"))
{ blnChk = false; }
chkBox.setChecked(blnChk);
C) Then you need to declare onClickListener for that where is basically reintallize your origianl array finding your TextView value and the new chk value.
private void setCheckValue(String Condition, String upc) {
for (int i = 0; i < data.size(); i++) {
String Upccode = data.get(i).get("UpcCode").toString();
if (Upccode.equals(upc)) {
HashMap<String, String> hmap = new HashMap<String, String>();
hmap = data.get(i);
hmap.put("chk", Condition);
data.set(i, hmap);
break;
}
}
}
D) Returning the modified data to the Activity by declaring a method call getData()
public ArrayList<HashMap<String, String>> getData() {
return data;
}
I use data in my CustomAdapter. Data is a ArrayList<HashMap<String, String>> .
Edit I don't do SQL command on toggle change. I collect them in a array. Then you obviously have a Submit button in your Activity. Once you press the submit button. I get the Data from the CustomAdapter. Which is done by getData() this will give you HashMap in your Activity.
I tend to achieve this by setting usual listeners inside Adapter when inflating View in getView and also remembering position for that View inside tag.
Take a look at this working example: ButtonsProblemsExampleActivity.java.
Related
I read some posts and found that reQuery() is deprecated and some suggested using SwapCursor() or ChangeCursor().
I have a Favorite button on whose click I update DB and change color of the Button. When I scroll and come back to particular view(and Button) color is reset.
I know it is because view is recycled. I have a condition based on a DB column value to set the color of the Button.
I want view to get updated values from DB after I press the Button. For which I have to refresh/requery Cursor/DB.
How do I do that with CursorAdapter keeping in mind that my min. API is 19?
UPDATE
CursorAdapter code:
public class ToDoCursorAdapter extends CursorAdapter {
SparseBooleanArray selectionArrayAr = new SparseBooleanArray();
SparseBooleanArray selectionArrayRef = new SparseBooleanArray();
SparseBooleanArray selectionArrayFav = new SparseBooleanArray();
//Boolean isSet = false;
private MainButtons_Interface mAdapterCallback;
public ToDoCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ViewHolderItem viewHolder = new ViewHolderItem();
View rowView = LayoutInflater.from(context).inflate(R.layout.listview, parent, false);
viewHolder.engTextV = (TextView) rowView.findViewById(R.id.engText);
viewHolder.arTextV = (TextView) rowView.findViewById(R.id.arabText);
viewHolder.buttonIAV = (Button) rowView.findViewById(R.id.buttonIA); //For Arabic Text
viewHolder.refTextV = (TextView) rowView.findViewById(R.id.refText);
viewHolder.buttonIRV = (Button) rowView.findViewById(R.id.buttonIR); //For Ref Text
viewHolder.buttonIFV = (ImageButton) rowView.findViewById(R.id.buttonF);
rowView.setTag(viewHolder);
return rowView;
}
#Override
public void bindView(final View view, final Context context, final Cursor cursor) {
final ViewHolderItem viewHolder = (ViewHolderItem) view.getTag();
String arabic = cursor.getString(cursor.getColumnIndexOrThrow("PlainArab_Text")).trim().replaceAll("[\n]{2,}", "TWOFEEDS").replaceAll("\n", " ").replaceAll(" +", " ").replaceAll("<br/>", "\n").replaceAll("TWOFEEDS", "\n") + "\n";
String english = cursor.getString(cursor.getColumnIndexOrThrow("PlainEng_Text")).trim().replaceAll("[\n]{2,}", "TWOFEEDS").replaceAll("\n", " ").replaceAll(" +", " ").replaceAll("<br/>", "\n").replaceAll("TWOFEEDS", "\n") + "\n";
String ref = cursor.getString(cursor.getColumnIndexOrThrow("REF")).trim().replaceAll("<br/> <br/>", " ").replaceAll("<br/>", "\n");
final Integer HadithID = cursor.getInt(cursor.getColumnIndexOrThrow("ID"));
final Integer IsFav = cursor.getInt(cursor.getColumnIndexOrThrow("IsFavorite"));
viewHolder.arTextV.setText(arabic);
viewHolder.engTextV.setText(english);
viewHolder.refTextV.setText(ref);
final int position = cursor.getPosition();
boolean isSelectedA = selectionArrayAr.get(position);
boolean isSelectedR = selectionArrayRef.get(position);
boolean isSelectedF = selectionArrayFav.get(position);
if (isSelectedA) {
viewHolder.arTextV.setVisibility(view.GONE);
viewHolder.buttonIAV.setText("Show Arabic Version");
} else if (!isSelectedA){
viewHolder.arTextV.setVisibility(view.VISIBLE);
viewHolder.buttonIAV.setText("Hide Arabic Version");
}
if (isSelectedR) {
viewHolder.refTextV.setVisibility(view.GONE);
viewHolder.buttonIRV.setText("Show Refrence");
} else if (!isSelectedR){
viewHolder.refTextV.setVisibility(view.VISIBLE);
viewHolder.buttonIRV.setText("Hide Refrence");
}
//boolean isSelectedF = selectionArrayFav.get(position);
if(isSelectedF) {
viewHolder.buttonIFV.setImageResource(R.drawable.favoritebutton_afterclick);
} else if (!isSelectedF){
viewHolder.buttonIFV.setImageResource(R.drawable.favoritebutton);
}
//Arabic Button
viewHolder.buttonIAV.setOnClickListener(
new View.OnClickListener()
{ #Override
public void onClick(View v) {
boolean isSelectedAc = selectionArrayAr.get(position);
if(!isSelectedAc) {
viewHolder.arTextV.setVisibility(v.GONE);
viewHolder.buttonIAV.setText("Show Arabic Version");
setSelectedAr(position, true);
} else if (isSelectedAc){
viewHolder.arTextV.setVisibility(v.VISIBLE);
setSelectedAr(position, false);
viewHolder.buttonIAV.setText("Hide Arabic version");
}
}
}
);
//Ref Button
viewHolder.buttonIRV.setOnClickListener(
new View.OnClickListener()
{ #Override
public void onClick(View v) {
boolean isSelectedRc = selectionArrayRef.get(position);
if(!isSelectedRc) {
viewHolder.refTextV.setVisibility(v.GONE);
viewHolder.buttonIRV.setText("Show Reference");
setSelectedRef(position, true);
} else if (isSelectedRc){
viewHolder.refTextV.setVisibility(v.VISIBLE);
setSelectedRef(position, false);
viewHolder.buttonIRV.setText("Hide Reference");
}
}
}
);
//Fav Button
viewHolder.buttonIFV.setOnClickListener(
new View.OnClickListener()
{ #Override
public void onClick(View v) {
boolean isSelectedF = selectionArrayFav.get(position);
boolean IsSet = ((ListViewActivity) context).addRemFav(HadithID);
String mess ="";
if(IsSet){
mess = "Hadith add to Favorite list";
} else if(!IsSet){
mess = "Hadith removed from Favorite list";
}
if(!isSelectedF) {
viewHolder.buttonIFV.setImageResource(R.drawable.favoritebutton_afterclick);
setSelectedF(position, true);
} else if (isSelectedF){
viewHolder.buttonIFV.setImageResource(R.drawable.favoritebutton);
setSelectedF(position, false);
}
Toast.makeText(v.getContext(), mess, Toast.LENGTH_SHORT).show();
}
}
);
}
// our ViewHolder.
static class ViewHolderItem {
TextView engTextV;
TextView arTextV;
TextView refTextV;
Button buttonIAV;
Button buttonIRV;
ImageButton buttonIFV;
}
// Method to mark items in selection
public void setSelectedAr(int position, boolean isSelected) {
selectionArrayAr.put(position, isSelected);
}
public void setSelectedRef(int position, boolean isSelected) {
selectionArrayRef.put(position, isSelected);
}
public void setSelectedF(int position, boolean isSelected) {
selectionArrayFav.put(position, isSelected);
}
UPDATE
I added this logic to my function which was called on clicking the Button.
Cursor todoCursor1 = hadDB.rawQuery("SELECT ID as _id, * FROM HAD_TABLE WHERE ID < 7001 ", null);
todoAdapter.changeCursor(todoCursor1);
Basically, you just need to requery DB so that you get updated records/Data and then change your current cursor with new one, todoCursor1 is my case above.
Also, changeCursor() will close your current cursor, in case you would want to go back to old cursor you should use swapCursor() instead as it will return you old cursor.
Now my only thing I want to know is, if this will work for APIs 19 and up.
I added this logic to my function which was called on clicking the Button.
Cursor todoCursor1 = hadDB.rawQuery("SELECT ID as _id, * FROM HAD_TABLE WHERE ID < 7001 ", null);
todoAdapter.changeCursor(todoCursor1);
Basically, you just need to requery DB so that you get updated records/Data and then change your current cursor with new one, todoCursor1 is my case above.
Also, changeCursor() will close your current cursor, in case you would want to go back to old cursor you should use swapCursor() instead as it will return you old cursor.
I'm facing a strange behaviour using an ArrayAdapter.
When the number of listview item exceed the height of the listView (say after item 8), the next item get the id 0 instead the id 9.
In my opinion this type of issue was explained here with the convertView, but i use it in the same way (i think).
The following code is my ArrayAdapter.
public class StepsAdapter extends ArrayAdapter<String> {
Context context;
List<String> steps;
public StepsAdapter(Context context, int resourceId, List<String> steps) {
super(context, resourceId, steps);
this.context = context;
}
private class ViewHolder {
EditText stepValue;
ImageView removeStep;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final String step = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_step, null);
holder = new ViewHolder();
holder.stepValue = (EditText) convertView.findViewById(R.id.stepEdit);
holder.removeStep = (ImageView) convertView.findViewById(R.id.removeStep);
holder.stepValue.setText(step);
holder.removeStep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"* Remove id step " + position, Toast.LENGTH_LONG).show();
steps.remove(position);
notifyDataSetChanged();
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
}
Then my main activity where i get existing data and put it in my listView, the add button and the save button.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_game);
mContext = getApplicationContext();
steps = new ArrayList<String>();
stepsAdapter = new StepsAdapter(mContext,R.layout.row_step,steps);
Gson gson = new GsonBuilder().create();
game = gson.fromJson(gameJson, Games.class);
/*
* Settings values
*/
gameNameValue.setText(game.getName());
gameBackgroundPreview.setBackgroundColor(game.getColor());
colorSelected = game.getColor();
for(int i = 0; i < game.getSteps().size() ; i++){
//steps.add(game.getSteps().get(i).toString());
//notifyDataSetChanged();
stepsAdapter.add(game.getSteps().get(i).toString());
}
final ListView listSteps = (ListView) findViewById(R.id.listViewSteps);
listSteps.setAdapter(stepsAdapter);
gameNameValue.setText(gameName);
addSteps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stepsId = steps.size();
Toast.makeText(getApplicationContext(), "addSteps : " + stepsId, Toast.LENGTH_LONG).show();
stepsAdapter.insert("newstep", stepsId);
}
});
buttonSaveGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String valueEditGameName = gameNameValue.getText().toString();
int valueColorBackaground = colorSelected;
String picture = "testPic";
for(int i=0; i < listSteps.getChildCount(); i++) {
LinearLayout rowLayout = (LinearLayout) listSteps.getChildAt(i);
//Log.e(TAG, ">> :) layout >>" + listSteps.getChildAt(i).getClass().getName());
EditText editRow = (EditText) rowLayout.getChildAt(0);
stepsValues.add(editRow.getText().toString());
//Log.e(TAG, ">> :) inside layout >>" + editRow.getText().toString());
}
if(valueEditGameName.trim().length() > 0 && picture.trim().length() >0 ){
Games game = new Games(valueEditGameName,valueColorBackaground,picture,stepsValues);
String goToSave = game.createJson();
Log.e(TAG, ">>Saved>>" + goToSave);
final CkdFile file = new CkdFile();
String saved = file.writeToSDFile(game.getName(), goToSave);
Toast.makeText(mContext, saved, Toast.LENGTH_LONG).show();
Intent backToMain = new Intent(mContext,MainActivity.class);
startActivity(backToMain);
} else {
Toast.makeText(mContext, "Fill all texts", Toast.LENGTH_LONG).show();
}
}
});
}
I try to add items in 2 different ways :
add item through : List steps
add item through : StepsAdapter stepsAdapter
Both give me same behaviour.
If someone has a clue to help understanding what i'm doing wrong with my implementation of ListView/ArrayAdapter.
Thanks in advance !
EDIT 1 :
After pushing some logs everywere, it understand the strange behaviour :
My adapter have only 6 slots (the limit came from the size of the listview in layout), and when my arraylist have more than 6 items, the getView select items only between 0 and 5.
I'm searching now a way to get the position in ArrayList and not the position in arrayadapter.
I faced same issue recently. Add following overrides to Adapter:
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
I found a simple xml "trick" to avoid this behaviour : i set a biger height to listView.
<ListView
android:layout_width="match_parent"
android:layout_height="1000dp"
android:layout_gravity="center_horizontal"
android:id="#+id/listViewSteps"
android:layout_margin="10dp">
</ListView>
It's not really resolve but a take it ...
I am trying to remove the list items from listactivity which has custom list adapter. Custom list adapter has textviews and checkboxes. When user selects the items by clicking on checkboxes, a button appears in the bottom of screen and on clicking on button, i want to delete the items from the adapter. I have implemented the solution by setting the position as a tag to checkbox but its not working. Checked positions and listview indices are not mapped correctly. I am posting my code here:
ListAdapter
<code>
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null)
{
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.gmail_list_layout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.checkView = (CheckBox) view.findViewById(R.id.check);
viewHolder.timeView = (TextView) view.findViewById(R.id.time_content);
viewHolder.fromView = (TextView) view.findViewById(R.id.from_content);
viewHolder.subjectView = (TextView) view.findViewById(R.id.subject_content);
viewHolder.rootLayout = (ViewGroup) view.findViewById(R.id.rootGmail);
Log.i("mustang", "Adding view at Position: " + position);
viewHolder.checkView.setTag(position);
viewHolder.checkView.setOnCheckedChangeListener(checkListener);
view.setTag(viewHolder);
}
OnCheckedChangeListener checkListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Integer position = (Integer)buttonView.getTag();
Log.i("mustang", "Position: " + position);
if(isChecked)
{
checkedPositions.put(position, position);
buttons.put(position, buttonView);
}
else
{
checkedPositions.remove(position);
buttons.remove(position);
}
Log.i("mustang", "Positions Array: " + checkedPositions.size());
ArrayList<Integer> positions = new ArrayList<Integer>(checkedPositions.values());
context.itemsSelected(positions);
}
};
public ArrayList<Integer> getCheckedPositions()
{
return new ArrayList<Integer>(checkedPositions.values());
}
</code>
Whenever checkbox is selected, button appears in bottom to remove the items. Button showing code and removal code is shown here:
Showing button when items selected by checkboxes are more than one:
<code>
public void itemsSelected(ArrayList<Integer> positions)
{
Log.i("mustang", "positions.size(): " + positions.size());
deleteItemsButton.setText("Delete " + positions.size() + " mails?");
deleteItemsButton.setVisibility(positions.size() > 0 ? Button.VISIBLE : Button.INVISIBLE);
}
</code>
And when user clicks on it following code runs:
<code>
private OnClickListener deleteItemsListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<Integer> positions = emails.getCheckedPositions();
for(Integer p : positions)
{
emails.remove(emails.getItem(p.intValue()));
}
emails.notifyDataSetChanged();
}
};
</code>
Please point me out that I am implementing the technique in the right way.
Thanks in advance.
I have a SimpleCursorAdapter class, it gets various data from DB and displays in ListView. It implements an onclicklistener that sends a messageGuid String to another activity. All this works fine.
In the row of the ListView i have added a CheckBox and set an onCheckChangeListener to it. At the moment when the checkbox is checked, the messageGuid is always the last one in the cursor.
I need to find a way to get the listview row id of the row which hold the checkbox that has been checked. I can then get the correct cursor row and then in turn the correct messageGuid.
I've commented what i would like within the onCheckedChanged method.
Thanks in advance Matt.
private class MyAdapter extends SimpleCursorAdapter implements OnItemClickListener {
Cursor c;
String messageGuid;
public MyAdapter(Context context, int layout, Cursor c, String[] from,
int[] to) {
super(context, layout, c, from, to);
}
#Override
public
View getView(int position, View convertView, ViewGroup parent) {
Log.e(TAG, "inside myadapter getview for messages");
View v = super.getView(position, convertView, parent);
if(v == null)
return null;
c = (Cursor)getItem(position);
Log.e(TAG, "(Cursor)getItem(position) = " + c + "position = " + position);
v.setTag(c);
//other code removed, not relevant
String messageSender = c.getString(c.getColumnIndex(LoginValidate.C_MESSAGE_SENDER));
String isRepliedTo = c.getString(c.getColumnIndex(LoginValidate.C_MESSAGE_REPLIED));
String isStandAlone = c.getString(c.getColumnIndex(LoginValidate.C_MESSAGE_IS_STANDALONE));
((TextView)v.findViewById(R.id.messagecreatedat)).setText(formattedMessCreatedAt );
((TextView)v.findViewById(R.id.messagetext)).setText(messageText);
((TextView)v.findViewById(R.id.messagesender)).setText(messageSender);
//#003F87 = blue
((TextView)v.findViewById(R.id.messagecreatedat)).setTextColor(Color.parseColor("#003F87"));
((TextView)v.findViewById(R.id.messagesender)).setTextColor(Color.parseColor("#003F87"));
((TextView)v.findViewById(R.id.messagetext)).setTextColor(Color.parseColor("#FF0000"));
CheckBox cb = ((CheckBox)v.findViewById(R.id.list_checkbox));
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//i'd like to something like below where i can specify the row which contains
//the checkbox that has been check and map that to the row in the cursor.
// So if the checkbox in the 2nd row in the listview has been clicked then the messageGuid from the 2nd row in the cursor is found
//c.moveToPosition(the row position of the listview which holds the checkbox that has been clicked );
messageGuid = null;
messageGuid = c.getString(c.getColumnIndex(LoginValidate.C_MESSAGE_GUID));
if(isChecked == true){
Log.e(TAG, "checkBox true and guid = " + messageGuid);
}else{
Log.e(TAG, "checkBox false and guid = " + messageGuid);
}
}
});
return v;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos,
long id) {
Cursor itemCursor = (Cursor) view.getTag();
String messageGuid = itemCursor.getString(itemCursor.getColumnIndex(LoginValidate.C_MESSAGE_GUID));
String messageText = itemCursor.getString(itemCursor.getColumnIndex(LoginValidate.C_MESSAGE_TEXT));
String messageCreatedAt = itemCursor.getString(itemCursor.getColumnIndex(LoginValidate.C_MESSAGE_CREATED_AT));
String messageSender = itemCursor.getString(itemCursor.getColumnIndex(LoginValidate.C_MESSAGE_SENDER));
String messageReplied = itemCursor.getString(itemCursor.getColumnIndex(LoginValidate.C_MESSAGE_REPLIED));
String messageSeen = itemCursor.getString(itemCursor.getColumnIndex(LoginValidate.C_MESSAGE_SEEN));
String isStandAlone = itemCursor.getString(itemCursor.getColumnIndex(LoginValidate.C_MESSAGE_IS_STANDALONE));
Intent i = new Intent(ViewMessagesActivity.this, ReplyToMessageActivity.class);
i.putExtra("guid", messageGuid);
i.putExtra("message", messageText);
i.putExtra("createdat", messageCreatedAt);
i.putExtra("sender", messageSender);
i.putExtra("messagereplied", messageReplied);
i.putExtra("messageseen", messageSeen);
i.putExtra("isstandalone", isStandAlone);
startActivity(i);
}
}// end of adapter
Make position final and use that on onCheckedChanged
or
make cb final
Add before cb.setOnCheckedChangeListener
cb.setTag(position);
And in public void onCheckedChanged you can retrieve the position
int pos = (Integer) cb.getTag();
I have a listview to populate data with a CustomAdapter as shown below by code.
1.) The listview rows are clickable and onItemClick I show up two buttons retake/review.
2.) When I click on other row the buttons which were visible on the previous row should hide.
3.) When I scroll the list all buttons are again invisible , that should not happen.
I have achieved the point no. 1 by this code , but how could I achieve 2,3. How could I modify getView() method of adapter or onItemClick() so that things work proper.
//Initialized listview with adapter
AttempListView.setAdapter(new AttemptedExcerciseAdapter(mAttempRecord,AttemptedExercise.this));
//A different adapter class to place values
public class AttemptedExcerciseAdapter extends BaseAdapter{
HashMap<Integer, AttemptedRecord> mHashMap;
Context mContext;
LinearLayout mLLButton;
public AttemptedExcerciseAdapter() {
// TODO Auto-generated constructor stub
}
public AttemptedExcerciseAdapter(HashMap<Integer, AttemptedRecord> mAttempRecord,Context mContext) {
this.mHashMap = mAttempRecord;
this.mContext=mContext;
}
#Override
public int getCount() {
return mHashMap.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
if (convertView == null) {
#SuppressWarnings("static-access")
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(AttemptedExercise.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.exerciselistlayout, null);
}
TextView attempChapter_name = (TextView) convertView.findViewById(R.id.TVchapterexercisechapterName);
TextView attemptQues = (TextView) convertView.findViewById(R.id.tvexercisesuccessrate);
TextView attemptSR = (TextView) convertView.findViewById(R.id.tvexerciseperquestiontime);
Button ReviewButton = (Button) convertView.findViewById(R.id.ReviewButton);
Button RetakeButton = (Button) convertView.findViewById(R.id.RetakeButton);
LinearLayout mLLtext = (LinearLayout) convertView.findViewById(R.id.LLText);
mLLButton = (LinearLayout) convertView.findViewById(R.id.LLButton);
mLLButton.setVisibility(View.INVISIBLE);
mLLtext.setVisibility(View.VISIBLE);
System.out.println("data value is..."+position+mHashMap.get(position + 1).getChapter_name());
attempChapter_name.setText(mHashMap.get(position+1).getChapter_name());
attemptQues.setText(" " + mHashMap.get(position+1).getTimePerQues() + " sec/ques");
attemptSR.setText(" " + mHashMap.get(position+1).getSuccess_rate() + " %");
return convertView;
}
}
//Item click listener for listview
public class ExcerciseItemClickListener implements OnItemClickListener {
ArrayList<Integer> rowNo=new ArrayList<Integer>();
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
System.out.println("click working..."+arg2);
arg1.findViewById(R.id.LLButton).setVisibility(View.INVISIBLE);
rowNo.clear();
rowNo.add(arg2);
if(rowNo.size()==1)
{
AttemptedRecord mRecordExcerciseItem = mAttempRecord.get(arg2 + 1);
final int chapter_id = mRecordExcerciseItem.getChapter_id();
final int test_id = mRecordExcerciseItem.getTest_id();
final int subject_id = mRecordExcerciseItem.getSubject_id();
System.out.println("attempted list size is..."+mAttempRecord.size());
arg1.findViewById(R.id.LLText).setVisibility(View.INVISIBLE);
arg1.findViewById(R.id.LLTake).setVisibility(View.INVISIBLE);
arg1.findViewById(R.id.LLButton).setVisibility(View.VISIBLE);
Button review=(Button) arg1.findViewById(R.id.ReviewButton);
Button retake=(Button) arg1.findViewById(R.id.RetakeButton);
review.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBHelper mDbHelper = new DBHelper(AttemptedExercise.this);
mDbHelper.createOrOpenDatabase("Dashboard");
Cursor chpater_exercise_Cursor = mDbHelper.rawQuery("select current_test_id from practice_test_summary where test_id="+test_id+" order by test_datetime desc limit 1");
chpater_exercise_Cursor.moveToFirst();
Long current_test_id =chpater_exercise_Cursor.getLong(0);
chpater_exercise_Cursor.close();
System.out.println("value of current test id is...."+current_test_id);
Intent reviewIntent = new Intent(AttemptedExercise.this, PracticeReview.class);
reviewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
if (current_test_id > 0) {
reviewIntent.putExtra("current_test_id", current_test_id);
startActivity(reviewIntent);
}
}
});
retake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("test id value when test starts is... "+test_id);
Toast.makeText(AttemptedExercise.this, "chapter_id" + chapter_id + " course_id" + " test_id" + test_id + " subject_id" + subject_id, Toast.LENGTH_LONG).show();
StartTest(4, subject_id, chapter_id, test_id);
}
});
}
}
}
In getView, you hide the button and text,that's why the view dispears when you scrolling。
mLLButton.setVisibility(View.INVISIBLE);
mLLtext.setVisibility(View.VISIBLE);
In your click listener you should record the position of the selected row, and in getView, you need to set view's visilibity status based on the postion of the view.
if you can mange to add ClickListeners of the list in getView like this
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
curruntButtonClickPosition=position;
//Visible you button here
notifyDataSetChanged();
}
});
and in getView
if(curruntButtonClickPosition=position)
//mLLButton visible
else
//mLLButton invisible
add curruntButtonClickPosition globle variable in AttemptedExcerciseAdapter class and init with -1.