I'm implementing an application in which user can store Debit Cards and later they can use it by just entering the CVV number of the same card. I have used RecyclerView for all the items(Debit Cards) stored by the user. Everything is working fine, view is rendering all good and I have used LinearLayoutManager to show Horizontal scroll.
Now the problem which I am facing is whenever I try to enter CVV of any card as soon as I click on it the view gets shifted towards the last item of the list of Stored Cards, So if I'm having three cards stored in my list and I try to enter CVV for the first one the view is shifting directly to the third card but the focus remains on the first cards EditText. I don't know what's going on with the same. I'm sharing some code part for the same.
Setting adapter and defining horizontal scroll :-
recyclerAdapter = new RecyclerStoredCardAdapter(mContext, storedCards);
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
storedCardListRecycler.setLayoutManager(layoutManager);
storedCardListRecycler.setVisibility(View.VISIBLE);
storedCardListRecycler.setAdapter(recyclerAdapter);
Sharing the screenshots with this so it will get clear. Any help would be appreciable. Thanks.
I have did this using ListView not with RecyclerView
But you can do with RecyclerView also.
Here is my used class demo.
SettingItemListViewAdapter.java
/**
* Created by vishalchhodwani on 18/10/16.
*/
public class SettingItemListViewAdapter extends BaseAdapter {
private final String TAG = "SettingItemListViewAdapter";
Context context;
List<SettingListViewItem> settingItemList;
OnMyClickListeners onMyClickListeners;
MyDatabaseAdapter myDatabaseAdapter;
public SettingItemListViewAdapter(Context context, List<SettingListViewItem> settingItemList) {
this.context = context;
this.settingItemList = settingItemList;
myDatabaseAdapter = new MyDatabaseAdapter(context);
}
public void setMyClickListener(OnMyClickListeners onMyClickListeners) {
this.onMyClickListeners = onMyClickListeners;
}
#Override
public int getCount() {
return settingItemList.size();
}
#Override
public Object getItem(int position) {
return settingItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.setting_listview_item, parent, false);
holder.settingListViewForm = (RelativeLayout) convertView.findViewById(R.id.settingListViewItem_form1);
holder.vrijeTekst = (EditText) convertView.findViewById(R.id.settingListViewItem_ed_virje_row1);
holder.kenteken = (EditText) convertView.findViewById(R.id.settingListViewItem_ed_kenketen_row1);
holder.checkRow = (ImageView) convertView.findViewById(R.id.settingListViewItem_check_row1);
holder.deleteRow = (ImageView) convertView.findViewById(R.id.settingListViewItem_deleteRow);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.vrijeTekst.setText(settingItemList.get(position).getItemVrijeTekst());
holder.kenteken.setText(settingItemList.get(position).getItemKenteken());
boolean isSelected = settingItemList.get(position).isItemSelected();
holder.checkRow.setImageResource(isSelected ? R.drawable.checked : R.drawable.uncheked);
holder.vrijeTekst.setTag(position);
holder.vrijeTekst.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(final View v, boolean hasFocus) {
try {
if (!hasFocus) {
if (settingItemList.size() > 0) {
int position = (int) v.getTag();
EditText Caption = (EditText) v;
settingItemList.get(position).setItemVrijeTekst(Caption.getText().toString());
}
} else {
EditText caption = (EditText) v;
caption.setCursorVisible(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
holder.kenteken.setTag(position);
holder.kenteken.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(final View v, boolean hasFocus) {
try {
if (!hasFocus) {
if (settingItemList.size() > 0) {
int position = (int) v.getTag();
EditText Caption = (EditText) v;
settingItemList.get(position).setItemKenteken(Caption.getText().toString());
}
} else {
EditText caption = (EditText) v;
caption.setCursorVisible(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
holder.checkRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myDatabaseAdapter.isAvailableInTable(settingItemList.get(position).getItemId()))
onMyClickListeners.onSelectButtonClicked(position);
}
});
holder.deleteRow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onMyClickListeners.onDeleteItemButtonClicked(position);
}
});
if (getCount() == position + 1) {
holder.vrijeTekst.requestFocus();
holder.vrijeTekst.performClick();
}
return convertView;
}
public static class ViewHolder {
RelativeLayout settingListViewForm;
EditText vrijeTekst, kenteken;
ImageView checkRow, deleteRow;
}
}
SettingN_New.java (It is a fragment)
public class SettingN_New extends Fragment implements OnClickListener, OnMyClickListeners {
private final String TAG = "SettingN_New";
Context context;
private TextView tv_demo;
ToggleButton togglebtn_save;
Button btn_save, btn_add;
ListView settingItemListView;
List<SettingListViewItem> settingItemList;
SettingItemListViewAdapter settingItemListViewAdapter;
MyDatabaseAdapter myDatabaseAdapter;
TinyDB loginpref;
boolean isNewRowAdded = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//This line of code will stay focus on selected edittext in list
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
ActionBar bar = getActivity().getActionBar();
bar.show();
View rootView = inflater.inflate(R.layout.setting_new, container, false);
initializeViews(rootView);
setUI();
getListOfItems();
return rootView;
}
private void setUI() {
try {
if (loginpref.getBoolean(ConstantLib.PREF_AUTO_LOGIN)) {
togglebtn_save.setChecked(true);
} else {
togglebtn_save.setChecked(false);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private void initializeViews(View rootView) {
context = getActivity();
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View headerView = inflater.inflate(R.layout.setting_listview_header, null);
btn_save = (Button) headerView.findViewById(R.id.btn_save);
btn_add = (Button) headerView.findViewById(R.id.btn_add);
togglebtn_save = (ToggleButton) headerView.findViewById(R.id.togglebtn_save);
tv_demo = (TextView) headerView.findViewById(R.id.tv_demo);
settingItemList = new ArrayList<>();
settingItemListView = (ListView) rootView.findViewById(R.id.setting_listView);
settingItemListView.setClickable(true);
settingItemListView.refreshDrawableState();
settingItemListView.addHeaderView(headerView);
settingItemListView.setItemsCanFocus(true);
settingItemListViewAdapter = new SettingItemListViewAdapter(context, settingItemList);
settingItemListViewAdapter.setMyClickListener(this);
settingItemListView.setAdapter(settingItemListViewAdapter);
myDatabaseAdapter = new MyDatabaseAdapter(context);
loginpref = new TinyDB(getActivity());
btn_save.setOnClickListener(this);
btn_add.setOnClickListener(this);
tv_demo.setOnClickListener(this);
togglebtn_save.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
loginpref.putBoolean(ConstantLib.PREF_AUTO_LOGIN, isChecked);
}
});
}
private void getListOfItems() {
settingItemList.clear();
settingItemList.addAll(myDatabaseAdapter.getAllData());
if (settingItemList.size() == 0) {
isNewRowAdded = true;
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId(settingItemList.size() + "");
settingListViewItem.setItemVrijeTekst("");
settingListViewItem.setItemKenteken("");
settingListViewItem.setItemSelected(false);
settingItemList.add(settingListViewItem);
} else {
isNewRowAdded = false;
}
notifyDataSetChanged();
}
private void hideKeyboard() {
// Check if no view has focus:
View view = getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_save:
clearFocus();
hideKeyboard();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (isValidationSuccess())
saveAllData();
}
}, 200);
break;
case R.id.btn_add:
addAnotherRow();
break;
case R.id.tv_demo:
clickedOnTvDemo();
break;
}
}
private void clickedOnTvDemo() {
try {
Intent i = new Intent(getActivity(), Setting_exp_activity.class);
startActivity(i);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
private boolean isValidationSuccess() {
Log.e(TAG, "isValidationSuccess() called : settingItemList.size()==" + settingItemList.size());
for (int i = 0; i < settingItemList.size(); i++) {
if (settingItemList.get(i).getItemVrijeTekst().equalsIgnoreCase("") || settingItemList.get(i).getItemKenteken().equalsIgnoreCase("")) {
showToast("Veld mag niet leeg zijn");// showToast("Fields should not be empty!!");
return false;
}
}
return true;
}
private void saveAllData() {
Log.e(TAG, "saveAllData() called");
myDatabaseAdapter.clearTable();
for (int i = 0; i < settingItemList.size(); i++) {
isNewRowAdded = false;
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId(i + "");
settingListViewItem.setItemVrijeTekst(settingItemList.get(i).getItemVrijeTekst());
settingListViewItem.setItemKenteken(settingItemList.get(i).getItemKenteken());
settingListViewItem.setItemSelected(settingItemList.get(i).isItemSelected());
myDatabaseAdapter.insertDataToTable(settingListViewItem);
}
DialogUtils.showInfoDialog(getActivity(),
"Instellingen opgeslagen");
}
private void addAnotherRow() {
Log.e(TAG, "addAnotherRow() called");
if (settingItemList.size() > 0 && !isNewRowAdded) {
if (!settingItemList.get(settingItemList.size() - 1).getItemVrijeTekst().equalsIgnoreCase("") && !settingItemList.get(settingItemList.size() - 1).getItemKenteken().equalsIgnoreCase("")) {
isNewRowAdded = true;
Log.e(TAG, "addAnotherRow() called check 1");
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId(settingItemList.size() + "");
settingListViewItem.setItemVrijeTekst("");
settingListViewItem.setItemKenteken("");
settingListViewItem.setItemSelected(false);
settingItemList.add(settingListViewItem);
notifyDataSetChanged();
} else {
Log.e(TAG, "addAnotherRow() called check 2");
showToast("Al toegevoegd");// showToast("Already Added!!");
}
} else {
if (!isNewRowAdded) {
isNewRowAdded = true;
Log.e(TAG, "addAnotherRow() called check 3");
SettingListViewItem settingListViewItem = new SettingListViewItem();
settingListViewItem.setItemId("0");
settingListViewItem.setItemVrijeTekst("");
settingListViewItem.setItemKenteken("");
settingListViewItem.setItemSelected(false);
settingItemList.add(settingListViewItem);
notifyDataSetChanged();
} else {
Log.e(TAG, "addAnotherRow() called check 4");
showToast("Al toegevoegd");// showToast("Already Added!!");
}
}
settingItemListView.setSelection(settingItemList.size());
Log.e(TAG, "addAnotherRow() called check 5");
Log.e(TAG, "after settingItemList.size()==" + settingItemList.size());
}
#Override
public void onDeleteItemButtonClicked(int position) {
Log.e(TAG, "onDeleteItemButtonClicked() position==" + position);
if (myDatabaseAdapter.getAllData().size() > 0)
showAlertForDeleteItem(position);
else
showToast("Er is geen item te verwijderen"); // showToast("No item to Delete");
}
#Override
public void onSelectButtonClicked(int position) {
Log.e(TAG, "onSelectButtonClicked() position==" + position);
for (int i = 0; i < settingItemList.size(); i++) {
Log.e(TAG, "onSelectButtonClicked() called check 3");
settingItemList.get(i).setItemSelected(false);
}
settingItemList.get(position).setItemSelected(true);
notifyDataSetChanged();
}
private void showAlertForDeleteItem(final int position) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setMessage("Weet je zeker dat je dit item wilt wissen?");//alertDialog.setMessage("Are you sure you want to delete this item?");
// ja==yes
alertDialog.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myDatabaseAdapter.deleteTableRow(settingItemList.get(position).getItemId() + "");
settingItemList.remove(position);
settingItemListViewAdapter.notifyDataSetChanged();
if (settingItemList.size() == position + 1) {
isNewRowAdded = false;
}
if (settingItemList.size() == 0) {
isNewRowAdded = false;
addAnotherRow();
}
}
});
//Annuleer==cancel
alertDialog.setNegativeButton("Annuleer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private void notifyDataSetChanged() {
settingItemListViewAdapter.notifyDataSetChanged();
}
private void showToast(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
public void clearFocus() {
if (getActivity().getWindow().getCurrentFocus() != null) {
getActivity().getWindow().getCurrentFocus().clearFocus();
}
}
}
I am giving you my whole class. why? Because it will give you more understanding that how I used it with ListView.
Test it and Let me know. :)
Note
This line of code is very important - getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST);
Not able to reproduce this issue. Let me know if the following code does what you are facing. If not, can provide more feedback if you share you Adapter's Code.
MainActivity.java
public class MainActivity
extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
MyAdapter adapter = new MyAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerView.setAdapter(adapter);
}
}
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_ite, parent);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((EditText)((MyViewHolder)holder).mBinding.findViewById(R.id.editText)).setHint(position + " ");
}
#Override
public int getItemCount() {
return 100;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
View mBinding;
public MyViewHolder(View binding) {
super(binding);
this.mBinding = binding;
}
}
}
The 2xml layouts:
<EditText
android:id="#+id/editText"
android:layout_height="200dp"
android:layout_width="300dp"/>
</android.support.v7.widget.CardView>
My main_activity.xml is as follows:
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</RelativeLayout>
As you can see this is the simplest case. Let me know if I missed anything.
Related
I have implemented an recycler view with Multi Select successfully using addOnItemTouchListener for identifying and selecting using single and double click.When i have Less than 5 items int the recycler view,Everything works fine but when i have more data,to be exact when the recycler view starts recycling the view,my selection is going crazy and it selects differnt possition.I logged out to see the clicking position,those seems to be right but something is not right which makes my selection wrong.I'm new to programming and to android app development.Can anyone take alot at this and help me out please,Here is my code
My adapter class
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactHolder> implements SectionIndexer, Filterable {
public List<Contact> contactList;
List<Contact> filteredUsersList;
CustomFilter filter;
Context mContext;
int itemResource;
ArrayList<Contact> selected_usersList = new ArrayList<>();
int pos;
private ArrayList<Integer> mSectionPositions;
ContactAdapter(Context mContext, int itemResource, List<Contact> contactList, ArrayList<Contact> selectedList) {
this.contactList = contactList;
this.mContext = mContext;
this.itemResource = itemResource;
this.selected_usersList = selectedList;
this.filteredUsersList = contactList;
}
#Override
public ContactHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(itemResource, parent, false);
return new ContactHolder(v);
}
#Override
public void onBindViewHolder(final ContactHolder holder, int position) {
pos = position;
final Contact contact = contactList.get(pos);
holder.colg.setText(contact.getColg());
holder.name.setText(contact.getName());
holder.job.setText(contact.getJob());
if (contact.getImage() != null)
holder.img.setImageBitmap(Utility.getPhoto(contact.getImage()));
}
#Override
public int getItemCount() {
return this.contactList.size();
}
class ContactHolder extends RecyclerView.ViewHolder {
private TextView name, colg, job, id, mentee, mentor, participant;
private ImageView selected;
// private PorterShapeImageView img;
private HexagonMaskView img;
private RelativeLayout rr_layout;
ItemClickListener itemClickListener;
ContactHolder(View itemView) {
super(itemView);
// Set up the UI widgets of the holder
// img = (PorterShapeImageView) itemView.findViewById(R.id.contact_image);
img = (HexagonMaskView) itemView.findViewById(R.id.contact_image);
name = (TextView) itemView.findViewById(R.id.contact_name);
colg = (TextView) itemView.findViewById(R.id.contact_colg);
job = (TextView) itemView.findViewById(R.id.contact_job);
mentee = (TextView) itemView.findViewById(R.id.mentee);
mentor = (TextView) itemView.findViewById(R.id.mentor);
participant = (TextView) itemView.findViewById(R.id.participant);
rr_layout = (RelativeLayout) itemView.findViewById(R.id.rr_layout);
selected = (ImageView) itemView.findViewById(R.id.tic_contact_selected);
}
}
}
My RecyclerItemClickListener Class
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener {
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null) {
mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
My Implementation of addOnItemTouchListener
contactsRecyclerViewT.addOnItemTouchListener(new RecyclerItemClickListener(this, contactsRecyclerViewT, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, final int position) {
Log.e("tag", "" + position);
for (int i = 0; i < multiselect_list.size(); i++) {
Log.e("tag", "sss" + multiselect_list.get(i).getName());
}
pos = position;
contact = contactArrayList.get(position);
menteeTextView = (TextView) view.findViewById(R.id.mentee);
mentorTextView = (TextView) view.findViewById(R.id.mentor);
participantTextView = (TextView) view.findViewById(R.id.participant);
rr_layout = (RelativeLayout) view.findViewById(R.id.rr_layout);
selected = (ImageView) view.findViewById(R.id.tic_contact_selected);
img = (HexagonMaskView) view.findViewById(R.id.contact_image);
name = (TextView) view.findViewById(R.id.contact_name);
if (isMultiSelect) {
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
multi_select(position);
if (multiselect_list.contains(contactArrayList.get(position))) {
contact.setStatus("0");
Log.e("tag", "setStatus" + contact.getStatus());
Log.e("tag", "position " + position);
rr_layout.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.bg_card_selected));
selected.setVisibility(View.VISIBLE);
mentorTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
participantTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
menteeTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorAccent));
menteeTextView.setVisibility(View.VISIBLE);
mentorTextView.setVisibility(View.VISIBLE);
participantTextView.setVisibility(View.VISIBLE);
menteeTextView.setClickable(true);
mentorTextView.setClickable(true);
participantTextView.setClickable(true);
} else {
rr_layout.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.cement));
selected.setVisibility(View.GONE);
Log.e("tag", "position " + position);
menteeTextView.setVisibility(View.GONE);
mentorTextView.setVisibility(View.GONE);
participantTextView.setVisibility(View.GONE);
menteeTextView.setClickable(false);
mentorTextView.setClickable(false);
participantTextView.setClickable(false);
}
}
});
mentorTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
contact.setStatus("1");
Log.e("tag", "setStatus" + contact.getStatus());
mentorTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorAccent));
menteeTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
participantTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
}
});
menteeTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
contact.setStatus("0");
Log.e("tag", "setStatus" + contact.getStatus());
mentorTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
participantTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
menteeTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorAccent));
}
});
participantTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
contact.setStatus("2");
Log.e("tag", "setStatus" + contact.getStatus());
mentorTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
menteeTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
participantTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorAccent));
}
});
name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ContactsActivity.this, OtherProfileActivity.class);
intent.putExtra("id", Integer.parseInt(contactArrayList.get(position).getId()));
startActivity(intent);
}
});
} else {
Intent intent = new Intent(ContactsActivity.this, OtherProfileActivity.class);
intent.putExtra("id", Integer.parseInt(contactArrayList.get(position).getId()));
startActivity(intent);
}
// contactList.get(position).setStatus("1");
// contactList.get(position).setStatus("0");
}
#Override
public void onItemLongClick(View view, int position) {
contact = contactArrayList.get(position);
Log.e("tag", "" + position);
for (int i = 0; i < multiselect_list.size(); i++) {
Log.e("tag", "sss" + multiselect_list.get(i).getName());
}
menteeTextView = (TextView) view.findViewById(R.id.mentee);
mentorTextView = (TextView) view.findViewById(R.id.mentor);
participantTextView = (TextView) view.findViewById(R.id.participant);
rr_layout = (RelativeLayout) view.findViewById(R.id.rr_layout);
selected = (ImageView) view.findViewById(R.id.tic_contact_selected);
img = (HexagonMaskView) view.findViewById(R.id.contact_image);
name = (TextView) view.findViewById(R.id.contact_name);
if (!isMultiSelect) {
multiselect_list = new ArrayList<>();
isMultiSelect = true;
if (mActionMode == null) {
mActionMode = startActionMode(mActionModeCallback);
}
}
multi_select(position);
if (multiselect_list.contains(contactArrayList.get(position))) {
rr_layout.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.bg_card_selected));
selected.setVisibility(View.VISIBLE);
contact.setStatus("0");
Log.e("tag", "setStatus" + contact.getStatus());
Log.e("tag", "position " + position);
mentorTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
participantTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
menteeTextView.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorAccent));
menteeTextView.setVisibility(View.VISIBLE);
mentorTextView.setVisibility(View.VISIBLE);
participantTextView.setVisibility(View.VISIBLE);
menteeTextView.setClickable(true);
mentorTextView.setClickable(true);
participantTextView.setClickable(true);
} else {
rr_layout.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.cement));
selected.setVisibility(View.GONE);
Log.e("tag", "position " + position);
menteeTextView.setVisibility(View.GONE);
mentorTextView.setVisibility(View.GONE);
participantTextView.setVisibility(View.GONE);
menteeTextView.setClickable(false);
mentorTextView.setClickable(false);
participantTextView.setClickable(false);
}
}
}));
ArrayList<AlphabetItem> mAlphabetItems = new ArrayList<>();
List<String> strAlphabets = new ArrayList<>();
for (int i = 0; i < contactArrayList.size(); i++) {
Contact contact = contactArrayList.get(i);
String name = contact.getName();
if (name == null || name.trim().isEmpty())
continue;
String word = name.substring(0, 1);
if (!strAlphabets.contains(word)) {
strAlphabets.add(word);
mAlphabetItems.add(new AlphabetItem(i, word, false));
}
}
}
add boolena array
boolean [] itemcheck;
initialize in constructor wit your arraylist.
itemcheck = new boolean[feedItemList.size()];
check in bindview holder like this
if(itemcheck[position]==true){
holder.row_linearlayout.setBackgroundColor(Color.parseColor("#b7c5ea"));
}else {
holder.row_linearlayout.setBackgroundColor(0xFFFFFFFF);
//holder.row_linearlayout.setBackgroundResource(R.drawable.blurback);
}
and set ture or false onclick of your relativelayout controle instead of any other controle .
holder.row_linearlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LinearLayout Lout = (LinearLayout) v.findViewById(R.id.selectlinear);
if(model.isSelected()){
Lout.setBackgroundColor(0xFFFFFFFF);
itemcheck[position]=false;
//get all other controle value here
}else{
Lout.setBackgroundColor(Color.parseColor("#b7c5ea"));
itemcheck[position]=true;
//get all other controle value here
}
}
});
You are doing most of the view manipulation in Onclick listener, you should move that to you adapter onBindView, because even if you set in Onclick listener, it will modify when user scroll.
I am not giving complete view manipulation, I am just giving the hint how we should do.
#Override
public void onBindViewHolder(final ContactHolder holder, int position) {
pos = position;
final Contact contact = contactList.get(pos);
holder.colg.setText(contact.getColg());
holder.name.setText(contact.getName());
holder.job.setText(contact.getJob());
if (contact.getImage() != null)
holder.img.setImageBitmap(Utility.getPhoto(contact.getImage()));
if (multiselect_list.contains(contactArrayList.get(position))) { // May be you should check form your fragment or actvity using listeners
holder.mentee.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
holder.participant.setBackgroundColor(ContextCompat.getColor(ContactsActivity.this, R.color.colorPrimary));
holder.mentee.setVisibility(View.VISIBLE);
holder.participant.setVisibility(View.VISIBLE);
} else {
holder.mentee.setVisibility(View.GONE);
holder.participant.setVisibility(View.GONE);
}
}
I have listview All the values are delete and update properly but only the last value is not delete in the listview.
Added a full fragment code. Take a look
For example
If I have three values in the listview If I delete 1 and 2 its removing and listview refresh properly but the last one is not refreshed in the listview
private SwipeMenuListView mylistview;
String userid;
private EditText txtsearch;
private ArrayList<JobItem> jobitems;
private JobListAdapter adapter;
SwipeMenuCreator creator;
ImageLoader imageLoader;
DisplayImageOptions options;
public Fragment_Employer_MyJobList() {
}
public static float dp2px(Context context, int dipValue) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.layoutjoblist, container, false);
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.displayer(new RoundedBitmapDisplayer(1000))
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.img_app_icon)
.showImageOnFail(R.drawable.img_app_icon)
.showImageOnLoading(R.drawable.img_app_icon).build();
mylistview = (SwipeMenuListView) rootView.findViewById(R.id.mylistview);
creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "open" item
SwipeMenuItem openItem = new SwipeMenuItem(
getActivity());
// set item background
openItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
0xCE)));
// set item width
openItem.setWidth((int) dp2px(getActivity(), 90));
// set item title
openItem.setTitle("DELETE");
// set item title fontsize
openItem.setTitleSize(18);
// set item title font color
openItem.setTitleColor(Color.WHITE);
// add to menu
menu.addMenuItem(openItem);
}
};
txtsearch = (EditText) rootView.findViewById(R.id.txtsearch);
txtsearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable theWatchedText) {
String text = txtsearch.getText().toString().toLowerCase(Locale.getDefault());
if (adapter != null)
adapter.filter(text);
}
});
return rootView;
}
SharedPreferences settings;
#Override
public void onResume() {
super.onResume();
jobitems = new ArrayList<JobItem>();
jobitems.clear();
adapter.notifyDataSetChanged();
settings = getActivity().getSharedPreferences(AppUtils.PREFS_NAME, Context.MODE_PRIVATE);
userid = settings.getString("userid", "");
AuthController.getStaticInstance().
employer_joblist(getActivity(), userid, APIConstants
.POST, new AuthControllerInterface.AuthControllerCallBack()
{
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONArray mainarray = new JSONArray(message);
for (int i = 0; i < mainarray.length(); i++) {
JSONObject json_job = mainarray.getJSONObject(i);
JobItem item = new JobItem();
item.Id = json_job.getString("ID");
item.EMPID = json_job.getString("EMPID");
item.TITLE = json_job.getString("TITLE");
item.DESC = json_job.getString("DESC");
item.CID = json_job.getString("CID");
item.PRICE = json_job.getString("PRICE");
item.LOCAT = json_job.getString("LOCAT");
item.ADATE = json_job.getString("ADATE");
item.FOLLOW = json_job.getString("FOLLOW");
JSONArray array = json_job.getJSONArray("IMAGES");
if (array.length() > 0) {
if (!array.isNull(0))
item.IMG1 = array.getString(0);
if (!array.isNull(1))
item.IMG2 = array.getString(1);
if (!array.isNull(2))
item.IMG3 = array.getString(2);
if (!array.isNull(3))
item.IMG4 = array.getString(3);
if (!array.isNull(4))
item.IMG5 = array.getString(4);
}
jobitems.add(item);
}
adapter = new JobListAdapter(getActivity(), jobitems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
JobItem item = jobitems.get(position);
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
});
mylistview.setMenuCreator(creator);
mylistview.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
// unfollow
userid = settings.getString("userid", "");
AuthController.getStaticInstance().employer_delete_job(getActivity(), userid, jobitems.get(position).Id, APIConstants.POST, new AuthControllerInterface.AuthControllerCallBack() {
#Override
public void onSuccess(String message) {
Log.e("==response==>", "==response==>" + message);
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
// onResume();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
// onResume();
}
//setup
onResume();
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
} catch (JSONException e) {
e.printStackTrace();
try {
JSONObject obj = new JSONObject(message);
Toast.makeText(getActivity(), obj.getString("ERROR") + "", Toast.LENGTH_LONG).show();
} catch (JSONException e1) {
e1.printStackTrace();
Toast.makeText(getActivity(), message + "", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailed(String error) {
Log.e("==error==>", "==error==>" + error);
}
}, Fragment_Employer_MyJobList.this);
}
#Override
public void showLoading() {
AppUtils.showProgress(getActivity(), "Please wait...");
// onResume();
}
#Override
public void stopLoading() {
AppUtils.dismissProgress();
// onResume();
}
public class OnItemClickListner implements View.OnClickListener {
int mposition;
JobItem item;
public OnItemClickListner(int position, JobItem item) {
this.mposition = position;
this.item = item;
}
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), Activity_Emp_jobdetail.class);
Bundle bundle = new Bundle();
bundle.putSerializable("jobitem", item);
intent.putExtras(bundle);
startActivity(intent);
}
}
private class JobListAdapter extends BaseAdapter {
LayoutInflater _inflater;
private List<JobItem> worldpopulationlist = null;
private ArrayList<JobItem> arraylist;
public JobListAdapter(Context context, List<JobItem> worldpopulationlist) {
_inflater = LayoutInflater.from(context);
this.worldpopulationlist = worldpopulationlist;
this.arraylist = new ArrayList<JobItem>();
this.arraylist.addAll(worldpopulationlist);
}
public int getCount() {
// TODO Auto-generated method stub
return worldpopulationlist.size();
}
public JobItem getItem(int position) {
// TODO Auto-generated method stub
return worldpopulationlist.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder _holder;
if (convertView == null) {
convertView = _inflater.inflate(R.layout.layout_job_row, null);
_holder = new ViewHolder();
_holder.txtjobtitle = (TextView) convertView
.findViewById(R.id.txtjobtitle);
_holder.txtjobbudget = (TextView) convertView
.findViewById(R.id.txtjobbudget);
_holder.txtjobdesc = (TextView) convertView
.findViewById(R.id.txtjobdesc);
_holder.imageviewjob = (ImageView) convertView
.findViewById(R.id.imageviewjob);
_holder.txtlocation = (TextView) convertView
.findViewById(R.id.txtlocation);
convertView.setTag(_holder);
} else {
_holder = (ViewHolder) convertView.getTag();
}
_holder.txtjobtitle.setText(worldpopulationlist.get(position).TITLE.trim());
_holder.txtjobbudget.setText(worldpopulationlist.get(position).PRICE.trim());
_holder.txtjobdesc.setVisibility(View.VISIBLE);
_holder.txtjobbudget.setVisibility(View.GONE);
_holder.txtjobdesc.setText(worldpopulationlist.get(position).DESC);
imageLoader.displayImage(worldpopulationlist.get(position).IMG1, _holder.imageviewjob, options);
_holder.txtlocation.setText(worldpopulationlist.get(position).LOCAT.trim());
//convertView.setOnClickListener(new OnItemClickListner(position, worldpopulationlist.get(position)));
return convertView;
}
private class ViewHolder {
ImageView imageviewjob;
TextView txtjobtitle, txtjobdesc;
TextView txtlocation, txtjobbudget;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
} else {
for (JobItem wp : arraylist) {
if (wp.TITLE.toLowerCase(Locale.getDefault())
.contains(charText)) {
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
}
you have to tell your ListView that something changed in it's former List by calling notifyDataSetChanged() method of your adapter
Also you should not create a new instance of ArrayList, but only clear the old instance. Don't forget to check for null before clearing.
try calling the adapter again with a null like.
setListAdapter()
I am having a listview and it has one checkbox and two textfields , i would like to change check box visibility properties from listview on click funtion, i am able to change the properties from inside the getView funtion but i want it from listview click. Help me find a solution
public class HelpList extends Fragment {
amfFunctions amf;
MyCustomAdapter dataAdapter = null;
Database_Contact contact = new Database_Contact();
DBHelper mydb = new DBHelper(getActivity());
public static final int PICK_CONTACT = 1;
public String user_phone_number;
public String buddyName;
public String buddyNum;
LayoutInflater vi;
View v ;
Fragment fragment = null;
Button myAddButton,myDelButton;
int selected = 0;
Boolean isInternetPresent = false;
ConnectionDetector cd;
ArrayList<Database_Contact> selectedList = new ArrayList<>();
Database_Contact addcontacts = new Database_Contact();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.activity_helplist, container, false);
// Inflate the layout for this fragment
displayListView();
cd = new ConnectionDetector(getActivity());
myDelButton = (Button)v. findViewById(R.id.deleteContact);
myDelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
DeleteContact();
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_SHORT).show();
}
}
});
Constants.i = 0;
myAddButton = (Button)v. findViewById(R.id.Addanother);
myAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
Log.e("Myaddbutton text ", (String) myAddButton.getText());
if (isInternetPresent) {
if (myAddButton.getText().equals("Close")){
Toast.makeText(getActivity(),
getString(R.string.click_to_close), Toast.LENGTH_SHORT).show();
}
else{
AddContact();
}
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_LONG).show();
}
}
});
return v;
}
private void displayListView() {
mydb = new DBHelper(getActivity());
ArrayList<Database_Contact> contactlist = (ArrayList<Database_Contact>)
mydb.getAllDatabase_Contacts();
Collections.sort(contactlist, new Comparator<Database_Contact>() {
#Override
public int compare(Database_Contact lhs, Database_Contact rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.activity_allcontactlist, contactlist);
ListView listView = (ListView)v.findViewById(R.id.helplistview);
// Assign adapter to ListView
listView.setTextFilterEnabled(true);
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact)
parent.getItemAtPosition(position);
contact.isSelected();
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Database_Contact> {
private ArrayList<Database_Contact> contactlist;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Database_Contact> contactlist) {
super(context, textViewResourceId, contactlist);
this.contactlist = new ArrayList<Database_Contact>();
this.contactlist.addAll(contactlist);
}
private class ViewHolder {
TextView code;
TextView Number;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.activity_allcontactlist,
null);
holder = new ViewHolder();
holder.code = (TextView)
convertView.findViewById(R.id.helplist_name);
holder.Number = (TextView)
convertView.findViewById(R.id.helplist_num);
holder.name = (CheckBox)
convertView.findViewById(R.id.checkbox_all);
convertView.setTag(holder);
final ViewHolder finalHolder = holder;
final ViewHolder finalHolder1 = holder;
holder.code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.Number.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Database_Contact contact = (Database_Contact)
cb.getTag();
contact.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Database_Contact contact = contactlist.get(position);
holder.code.setText(contact.getName());
holder.Number.setText(contact.getPhoneNumber());
holder.name.setText("");
holder.name.setChecked(contact.isSelected());
holder.name.setTag(contact);
return convertView;
}
}
}
As I could not find any perfect solution i tried it in a different manner alough its a bit diffenrt from what i wanted i.e on click i used my displayListView() funtion and got the work done
ischeckboxVisible = true;
Runnable run = new Runnable() {
#Override
public void run() {
displayListView();
}
};
getActivity().runOnUiThread(run);
and coming to getView i have used:
if (!ischeckboxVisible)
{
holder.name.setVisibility(View.GONE);
}
if (ischeckboxVisible)
{
holder.name.setVisibility(View.VISIBLE);
}
so every time i do the click it changes the ischeckboxVisible to either true or false and initializes the displatListview() and it works.
I have had help from here Android hide and show checkboxes in custome listview on button click
Hope this might come in handy for some one out there.
Please check below code if it helps you,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact) contactlist.get(position);
contact.setSelected(!contact.isSelected());
if(contact.isSelected())
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.VISIBLE);
}
else
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.GONE);
}
}
});
I'm hoping that someone here could help me. I'm trying to delete an item from my Listview by clicking a button from another activity. I'm sending a an intent and resultcode in the onActivityResult to the activity that contains the listview but nothing is happening. Any help would be greatly appreciated. Thanks
Delete Button Activity
private void deleteClicked() {
Intent result = new Intent();
result.putExtra("myReminder", item);
getActivity() .setResult(12, result);
getActivity().finish();
}
ListView Activity
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
Log.e(TAG, "REMOVE CALLEDcode");
if (requestCode == 05) {
if (resultCode == 12) {
Chops item = (Chops) data.getSerializableExtra("myReminder");
removeChop(item);
refreshFragment();
}
}
}
private void removeChop(Chops item) {
// TODO Auto-generated method stub
Log.d(TAG, "REMOVE CALLED");
for (Iterator iterator = SaveTheChops.listofchops.iterator(); iterator.hasNext(); ) {
Chops deleteChop = (Chops) iterator.next();
if (match(item, deleteChop)) {
iterator.remove();
//SaveTheChops.addChop(getActivity());
return;
}
}
}
private boolean match(Chops item, Chops deleteChop) {
if (item.getmAlbum().equals(deleteChop.getmAlbum()) &
item.getmArtist().equals(deleteChop.getmArtist()) &
item.getmSong().equals(deleteChop.getmSong()) &
item.getmAudio().equals(deleteChop.getmAudio()) &
item.getmPic().equals(deleteChop.getmPic()) &
item.getmSection().equals(deleteChop.getmSection()))
{ Log.e(TAG, "MATCH");
return true;
}
Log.e(TAG, " NO MATCH");
return false;
}
private void refreshFragment() {
Log.e(TAG, "REFRESHED");
Fragment frg = null;
frg = getFragmentManager().findFragmentByTag("ListFragmenttag");
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
}
If it helps here is my ListAdapter
public static class ListViewDemoAdapter extends ArrayAdapter<Chops> implements MediaPlayer.OnCompletionListener {
final String TAG = "MyChopActivty";
private boolean isPlaying;
private boolean isRecording;
private List<Chops> mItems;
MediaPlayer mPlayer;
public Chops item;
File audiofile = null;
private int length;
Intent intent, fileIntent;
String mAudio;
public ListViewDemoAdapter(Context context, List<Chops> items) {
super(context, R.layout.each_item, items);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
final LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.each_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.cover_photo);
viewHolder.tvAlbum = (TextView) convertView.findViewById(R.id.tvAlbum);
viewHolder.tvPlay = (Button) convertView.findViewById(R.id.listPly);
viewHolder.tvSong = (TextView) convertView.findViewById(R.id.tvSong);
convertView.setTag(viewHolder);
final Button PIL = (Button) convertView.findViewById(R.id.listPly);
final Button PAUSIL = (Button) convertView.findViewById(R.id.listPause);
PAUSIL.setEnabled(false);
PAUSIL.setVisibility(View.INVISIBLE);
PIL.setTag(position);
PIL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
Chops item = getItem(position);
Toast.makeText(getContext(), "PLAY FROM LIST?", Toast.LENGTH_SHORT).show();
if (item.getmAudio() != null) {
mAudio = item.getmAudio();
Log.d(TAG, " from LISTPLAY " + mAudio);
try {
playAudio(mAudio);
if (isPlaying) {
PAUSIL.setEnabled(true);
PAUSIL.setVisibility(View.VISIBLE);
PIL.setEnabled(false);
PIL.setVisibility(View.INVISIBLE);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
PAUSIL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "PAUSING", Toast.LENGTH_SHORT).show();
stopPlaying();
isPlaying = false;
PAUSIL.setEnabled(false);
PAUSIL.setVisibility(View.INVISIBLE);
PIL.setEnabled(true);
PIL.setVisibility(View.VISIBLE);
}
});
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Chops item = getItem(position);
viewHolder.ivIcon.setImageBitmap(StringToBitMap(item.getmPic()));
viewHolder.tvAlbum.setText(item.getmAlbum());
viewHolder.tvSong.setText(item.getmSong());
return convertView;
}
Instead, Add a method to remove an item from your dataset inside your Adapter class. Something along the lines of:
public void remove(int position){
mItems.remove(position);
notifyDataSetChanged();
}
Then call yourAdapter.remove(positionToRemove); from the onClick of the Activity with the button.
Hi i have listview of songs with checkbox using Aquery i am unable to save the State of chekckbox while list scrolldown. i have two arraylist one is for by clicking song image & other is for checkbox if user select the chekbox it should play song accordingly to checkbox arraylist. i have used this also check.setChecked(SelectedBox.get(clickedposition).getisCheck()); . But no help
so far what i have done is here
private void createList() {
listAq = new AQuery(this);
adapter = new ArrayAdapter<Audio>(SongList.this, R.layout.list_row,details) {
#Override
public View getView(final int position, View convertView,final ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_row, parent, false);
}
final int clickedposition = position;
final AQuery aq = listAq.recycle(convertView);
Audio item = getItem(position);
aq.id(R.id.MovieName).text(item.getAlbumName());
aq.id(R.id.SongName).text(item.getTitle());
aq.id(R.id.checkBox1).getCheckBox().setSelected(item.getisCheck());
aq.id(R.id.nameLayout).clicked(new OnClickListener() {
#Override
public void onClick(View v) {
DialogBuilder(position);
}
});
check = (CheckBox) convertView.findViewById(R.id.checkBox1);
check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
try {
if (isChecked) {
checkbox = true;
if (details.get(clickedposition).getisCheck() == false) {
SelectedBox.add(details.get(clickedposition));
System.out.println(SelectedBox.size());
details.get(clickedposition).setisCheck(true);
}
} else {
final String name = details.get(clickedposition).getFilename();
for (int i = 0; i <= SelectedBox.size(); i++) {
if (name.equals(SelectedBox.get(i).getFilename())) {
SelectedBox.remove(i);
details.get(clickedposition).setisCheck(false);
}
}
}
notifyDataSetChanged();
}
catch (Exception e) {
e.getMessage();
}
}
});
try{
}
catch (Exception e) {
// TODO: handle exception
}
url = "drawable/" + item.getThumbnail();
imageResource = getResources().getIdentifier(url, null,getPackageName());
aq.id(R.id.song_image).image(imageResource);
if (position != playingValue) {
aq.id(R.id.imageplay).invisible();
aq.id(R.id.imageplay).getImageView().bringToFront();
} else {
aq.id(R.id.imageplay).visible();
}
ImageView img = (ImageView)convertView.findViewById(R.id.song_image);
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
checkbox = false;
SelectedBox.clear();
currentSongIndex = position;
try {
if (ChannelService.playerFlag == 0) {
playSong(currentSongIndex);
} else if ((ChannelService.playerFlag == 1)
|| ((ChannelService.playerFlag == 2))) {
if (currentSongIndex != playingValue) {
try {
final Intent serviceIntent = new Intent(
getApplicationContext(),
ChannelService.class);
stopService(serviceIntent);
mPlay.setBackgroundResource(R.drawable.play_btn);
playSong(currentSongIndex);
} catch (final IllegalStateException e) {
e.printStackTrace();
}
}
mPlay.setBackgroundResource(R.drawable.pause_btn);
final Intent in = new Intent("updateNotification");
sendBroadcast(in);
}
} catch (final IllegalStateException e) {
e.getMessage();
}
notifyDataSetChanged();
}
});
return convertView;
}
};
aq.id(R.id.listView1).adapter(adapter);
}
When you scroll down a list in Android, it destroys the rows that doesn't fit in the screen.
I allways use an array of objects to save the state of each row so when android calls getView you can ask the state of them:
public class AudioRow{
public int id;
public boolean checked;
...
}
Then at getView you can do something like that:
public View getView(final int position, View convertView,final ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_row, parent, false);
}
final int clickedposition = position;
AudioRow ar = audioRows.get(position);
if(ar.checked) {
//do something;
}
...
#Override
public void onClick(View v) {
if(ar.checked) ar.checked = false;
else ar.checked = true;
DialogBuilder(position);
}
});
I hope it helps you.