Highlight a selected row in ListView for Android - java

I have created a listView set of rows which I have managed to alternate the colours successfully.
However, I want to be able to change the colour of the row once the user has selected one.
I have set my XML as follows:
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/listView"
android:listSelector="#android:color/holo_red_light"/>
My full java code is below:
public class Task2Activity extends ListActivity {
ListView list;
String [] dogTitles;
String [] dogDescriptions;
String [] dogToastDescriptions;
int[] images = {R.drawable.husky, R.drawable.pug, R.drawable.yorkshire_terrier, R.drawable.french_bulldog,
R.drawable.border_collie, R.drawable.great_dane, R.drawable.staffordshire_bull_terrier, R.drawable.golden_retriever,
R.drawable.german_shepherd, R.drawable.doberman};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_task2);
Resources res = getResources();
dogTitles = res.getStringArray(R.array.titles);
dogDescriptions = res.getStringArray(R.array.descriptions);
dogToastDescriptions = res.getStringArray(R.array.toastdescriptions);
//list = (ListView) findViewById(R.id.listView);
dogAdapter <String> adapter = new dogAdapter<String>(this, dogTitles, images, dogDescriptions) {
//list.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position %2 == 1)
{
view.setBackgroundColor(Color.parseColor("#e6e9ef"));
}
else
{
view.setBackgroundColor(Color.parseColor("#c9d0db"));
}
return view;
}
};
setListAdapter(adapter);
registerForContextMenu(getListView());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.my_context_menu, menu);
}
protected void onListItemClick(ListView l, View v, int position, long id){
String item = dogToastDescriptions[position];
Toast.makeText(this, item, Toast.LENGTH_LONG).show();
getListView().setSelected(true);
}
class dogAdapter<S> extends ArrayAdapter<String> {
Context context;
int[] images;
String[] titleArray;
String[] descriptionArray;
dogAdapter(Context c, String[] titles, int imgs[], String[] desc) {
super(c, R.layout.single_row, R.id.largeText, titles);
this.context = c;
this.images = imgs;
this.titleArray = titles;
this.descriptionArray = desc;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView);
myTitle = (TextView) v.findViewById(R.id.largeText);
myDescription = (TextView) v.findViewById(R.id.smallText);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
Log.d("dogs", "Creating a new row");
} else {
holder = (MyViewHolder) row.getTag();
Log.d("dogs", "Recycling stuff");
}
//ImageView myImage = (ImageView) row.findViewById(R.id.imageView);
//TextView myTitle = (TextView) row.findViewById(R.id.largeText);
//TextView myDescription = (TextView) row.findViewById(R.id.smallText);
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titleArray[position]);
holder.myDescription.setText(descriptionArray[position]);
return row;
}
}
}
Any help greatly appreciated. Many thanks

In onListItemClick() you can set the color of the selected item:
protected void onListItemClick(ListView l, View v, int position, long id){
String item = dogToastDescriptions[position];
v.setBackgroundColor(ContextCompat.getColor(this, android.R.color.holo_green_light));//your color here
Toast.makeText(this, item, Toast.LENGTH_LONG).show();
getListView().setSelected(true);
}
There is also an option in the Listview, that highlights selected values :
<ListView android:id="#+id/my_listView"
android:choiceMode="singleChoice"
android:listSelector="#android:color/darker_gray" <!--your color here -->
/>
android:choiceMode = "singleChoice" is what you are looking for

Related

Click listener for a button in a customised cell in a list view

I've created a customised list view for my Android app in order to add a Delete button for every cell to make the user able to delete rows from the list. The customised list view is working well but when I added a click listener for the button, the list view show empty cells instead of populating the data coming from the array.
Here is the getView code:
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Button deleteButt = (Button) row.findViewById(R.id.deleteButton);
deleteButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "delete me", Toast.LENGTH_SHORT).show();
}
});
return row;
}
I think the I should return something else not the row, but I have no idea what to return. When I think about it when I return the row it should show the rows filled with data. Note when I delete this piece of code, the list view is working well with showing the data.
This is the whole code of the adapter class
// Our adapter class
class MyAdapter extends ArrayAdapter<String> {
Context context;
String rNames[];
MyAdapter(Context c, String name[]) {
super(c, R.layout.row, R.id.customerName, name);
this.context = c;
this.rNames = name;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Button deleteButt = (Button) row.findViewById(R.id.deleteButton);
deleteButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "delete me", Toast.LENGTH_SHORT).show();
}
});
return row;
}
}
And this is the whole code of the home fragment page
public class HomeFragment extends Fragment {
// creating an empty array. This is an array of objects (array of arrays).
final ArrayList<String[]> mainObjectsArray = new ArrayList<String[]>();
//final String[][] myFamily = new String[][];
// creating another array of the titles. If our main array is an array of strings we will not need this.
// Why?. ArrayAdapter doesn't accept an array of arrays it only accepts an array of Stings, so we had to create a special array for the titles and bring them from our main array.
final ArrayList<String> theNames = new ArrayList<String>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_home, null);
// creaing a list view and connect it to the list view we created in the XML file
// Note: we need to add (final) to be able to access them from inside the loop
final ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
// Retrieving the data and filling the array with it
ParseQuery<ParseObject> query = ParseQuery.getQuery("Orders");
query.orderByDescending("updatedAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
//Log.i("findInBackground", "Retrieved: " + objects.size() + "objects");
if (objects.size() > 0) {
for (ParseObject object: objects) {
// Converting every object to an array of two itmes, title and body.
String[] artical = {object.getString("TheSavedOrder"), object.getString("mobileNumber"), object.getString("Name")};
// Adding the array to our main array so we will have an array of arrays
mainObjectsArray.add(artical);
//Log.i("This my family array: ", myFamily.toString());
}
// We will add only the names to the array (theNames). theTitles will be an array of strings so we can populate it in the list view.
for (int i = 0; i < mainObjectsArray.size(); i++){
theNames.add(mainObjectsArray.get(i)[2]);
//Log.i("Here are teh title: ", myFamily.get(i)[0]);
Log.i("Here is thti: ", theNames.get(i));
}
// Converting theNames from ArrayList to an array
String[] namesArray = new String[theNames.size()];
namesArray = theNames.toArray(namesArray);
// Applaying our adapter
MyAdapter adapter = new MyAdapter(getActivity(), namesArray);
myListView.setAdapter(adapter);
}
}
}
});
// When clicking on an item in the list view
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Log.i("The body is: ", mainObjectsArray.get(position));
Intent intent = new Intent(getContext(), TheBody.class);
intent.putExtra("mobile", mainObjectsArray.get(position)[1]); // mainObjectsArray.get(position)[1] means we will pass the second item in every array which is the (mobileNumber).
intent.putExtra("order", mainObjectsArray.get(position)[0]);
startActivity(intent);
}
});
return rootView;
}
// Our adapter class
class MyAdapter extends ArrayAdapter<String> {
Context context;
String rNames[];
MyAdapter(Context c, String name[]) {
super(c, R.layout.row, R.id.customerName, name);
this.context = c;
this.rNames = name;
}
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
Button deleteButt = (Button) row.findViewById(R.id.deleteButton);
deleteButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "delete me", Toast.LENGTH_SHORT).show();
}
});
return row;
}
}
}
This is the XML code of the fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/myListView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
And finally this is the XML code of the customised cell
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp"
android:descendantFocusability="blocksDescendants">
<TextView
android:id="#+id/customerName"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="custoemr name"
android:textColor="#000"
android:layout_margin="5dp"
android:textSize="20sp"/>
<Button
android:id="#+id/deleteButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
/>
</LinearLayout>
Please help I've been struggling with this for some days!
Many thanks.
public View getView(final int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
Button deleteButt = (Button) row.findViewById(R.id.deleteButton);
deleteButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "delete me", Toast.LENGTH_SHORT).show();
} });
return row;
}
Pls also note that your list, rNames, is an array[] that is fixed size and cannot remove an individual item. You should use ArrayList if you want to implement the delete function.
Updated:
public class HomeFragment extends Fragment {
// creating an empty array. This is an array of objects (array of arrays).
ArrayList<MainObjects> mainObjectsList = new ArrayList<>();
ListView myListView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, null);
// creaing a list view and connect it to the list view we created in the XML file
// Note: we need to add (final) to be able to access them from inside the loop
myListView = (ListView) rootView.findViewById(R.id.myListView);
// Retrieving the data and filling the array with it
ParseQuery<ParseObject> query = ParseQuery.getQuery("Orders");
query.orderByDescending("updatedAt");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
//Log.i("findInBackground", "Retrieved: " + objects.size() + "objects");
if (objects.size() > 0) {
for (ParseObject object : objects) {
// Converting every object to an array of two items, title and body.
//String[] artical = {object.getString("TheSavedOrder"), object.getString("mobileNumber"), object.getString("Name")};
MainObjects article = new MainObjects(object.getString("TheSavedOrder"), object.getString("mobileNumber"), object.getString("Name");
// Adding the array to our main array so we will have an array of arrays
mainObjectsList.add(article);
//Log.i("This my family array: ", myFamily.toString());
}
// Applying our adapter
MyAdapter adapter = new MyAdapter(getActivity(), mainObjectsList);
myListView.setAdapter(adapter);
}
}
}
});
// When clicking on an item in the list view
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Log.i("The body is: ", mainObjectsList.get(position));
Intent intent = new Intent(getContext(), TheBody.class);
intent.putExtra("mobile", mainObjectsList.get(position).getMobileNumber());
intent.putExtra("order", mainObjectsList.get(position).getSavedOrder());
startActivity(intent);
}
});
return rootView;
}
class MainObjects {
String savedOrder = "", mobileNumber = "", name = "";
public MainObjects(String savedOrder, String mobileNumber, String name) {
this.savedOrder = savedOrder;
this.mobileNumber = mobileNumber;
this.name = name;
}
public String getSavedOrder() {
return savedOrder;
}
public String getMobileNumber() {
return mobileNumber;
}
public String getName() {
return name;
}
}
class MyAdapter extends ArrayAdapter<MainObjects> {
Context context;
LayoutInflater inflater;
ArrayList<MainObjects> rNames;
MyAdapter(Context c, ArrayList<MainObjects> name) {
super(c, R.layout.row, R.id.customerName, name);
this.context = c;
this.rNames = name;
inflater = getLayoutInflater();
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = inflater.inflate(R.layout.row, parent, false);
TextView nameTv = (TextView) row.findViewById(R.id.customerName);
nameTv.setText(getItem(position).getName());
Button deleteButt = (Button) row.findViewById(R.id.deleteButton);
deleteButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = (int)view.getTag();
String msg = "Delete: " + pos + ". " + getItem(pos).getName() + " !!";
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
rNames.remove(pos);
notifyDataSetChanged();
//
// Codes to update permanent storage, e.g. files/server/db.
//
} });
deleteButt.setTag(position);
return row;
}
}
}

Android How to refresh or reload listview data and final totaling data

Android How to refresh or reload listview data and final totaling data that is total of the all price of the cart
check image i want the blue circle price add and show on the red circle and but if i delete or change quantity of product then also update the price in red circle
this is my code
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolderItem viewHolder;
if(convertView==null){
inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.toptext = (TextView) convertView.findViewById(R.id.cartname);
viewHolder.prc = (TextView) convertView.findViewById(R.id.textView76);
viewHolder.shp = (TextView) convertView.findViewById(R.id.textView77);
viewHolder.subtotal = (TextView) convertView.findViewById(R.id.textView79);
//viewHolder.textView80 = (TextView) convertView.findViewById(R.id.textView80);
viewHolder.img = (ImageView) convertView.findViewById(R.id.imageView7);
viewHolder.imageView2 = (ImageView) convertView.findViewById(R.id.imageView2);
viewHolder.spinner = (Spinner)convertView.findViewById(R.id.spinner);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolderItem) convertView.getTag();
}
final CartResponse response = getItem(position);
int subtotal1=0;
mydb = new DBHelper(getContext());
if(response != null) {
/* ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
R.array.qty, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
viewHolder.spinner.setAdapter(adapter);*/
viewHolder.spinner.setSelection(Integer.parseInt(response.getQty())-1);
viewHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
response.setQty(viewHolder.spinner.getSelectedItem()+"");
if(mydb.updateContact(Integer.parseInt(response.getid()),response.getPname(),Integer.parseInt(response.getPrice()),Integer.parseInt(response.getCutPrice()),++pos,Integer.parseInt(response.getShipping()),response.getPhoto())){
Log.d("key",""+response.getQty());
updateResults();
//Toast.makeText(getContext(),"updated", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
viewHolder.imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mydb.deleteContact(Integer.parseInt(response.getid()));
//int index =callback.indexOf(response.getid());
callback.remove(response);
updateResults();
Toast.makeText(getContext(),"Remove", Toast.LENGTH_SHORT).show();
}
});
int tamount=0,tship=0,gt=0;
tamount=tamount+(Integer.parseInt(response.getPrice())* Integer.parseInt(response.getQty()));
tship=tship+(Integer.parseInt(response.getShipping())* Integer.parseInt(response.getQty()));
gt=tamount+tship;
subtotal1=Integer.parseInt(response.getPrice()) + Integer.parseInt(response.getShipping());
viewHolder.toptext.setText(response.getPname());
viewHolder.prc.setText("Rs."+tamount);
//Log.d("key",""+response.getPrice());
viewHolder.shp.setText("Rs."+tship);
viewHolder.subtotal.setText("Sub total Rs."+gt);
Picasso.get().load("https://www.exmple.com/photos/"+response.getPhoto()+".png").placeholder(R.drawable.placeholder).memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into(viewHolder.img);
}
Cart class
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_cart, container, false);
mydb = new DBHelper(getContext());
cart_list = mydb.getAllCotacts();
cartitems=cart_list.size();
int amount=0,shping=0;
for(int i=0;i<cartitems;i++){
int price = (Integer.parseInt(cart_list.get(i).getPrice())*Integer.parseInt(cart_list.get(i).getQty()));
int shp=(Integer.parseInt(cart_list.get(i).getShipping())*Integer.parseInt(cart_list.get(i).getQty()));
amount=amount+price;
shping=shping+shp;
}
TextView cout=(TextView)view.findViewById(R.id.textView75);
TextView gprice=(TextView)view.findViewById(R.id.textView87);
TextView gship=(TextView)view.findViewById(R.id.textView88);
gprice.setText("Rs."+amount);
gship.setText("Rs."+shping);
if(cartitems>0){
cout.setText("Your Cart Item");
}else{
cout.setText("Shopping Cart is Empty");
}
final CartAdapter adapter = new CartAdapter(getContext(), R.layout.cart_item, cart_list);
final ListView order_list = (ListView)view.findViewById(R.id.cartlist);
order_list.setAdapter(adapter);
adapter.notifyDataSetChanged();
order_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
adapter.notifyDataSetChanged();
//mydb.deleteContact(cart_list.get(position).getid());
//Log.d("key",""+cart_list.get(position).getQty());
//cart_list.get(position).getid();
}});
return view;
}

How to programmatically hide a single row from list view (Custom adapter)

I have a list view app and using a custom adapter, but I can't hide a specific row from the adapter.
My codes
-: In java :-
Adapter
class Adapter extends ArrayAdapter {
int[] imageArray;
String[] titleArray;
String[] descriptionArray;
public Adapter(Context context, String[] titles1, String [] description1, int[] img1) {
super(context, R.layout.settings_list_row, R.id.settingsTitles, titles1);
this.imageArray = img1;
this.titleArray = titles1;
this.descriptionArray = description1;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.settings_list_row,parent,false);
ImageView myImage = (ImageView) row.findViewById(R.id.settingsIcons);
TextView myTitle = (TextView) row.findViewById(R.id.settingsTitles);
TextView myDescription = (TextView) row.findViewById(R.id.settingsDescriptions);
myImage.setImageResource(imageArray[position]);
myTitle.setText(titleArray[position]);
myDescription.setText(descriptionArray[position]);
return row;
}
}
Main activity
String [] titles = {"ti1","ti2","ti3","ti4","ti5"};
String [] descriptions = {"de1","de2","de3","de4","de5"};
int [] images = {R.drawable.ic_image,R.drawable.ic_image,R.drawable.ic_image,R.drawable.ic_image,R.drawable.ic_image};
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
lv = (ListView) findViewById(R.id.listView);
final Adapter adapter = new Adapter(getApplicationContext(), titles, descriptions, images);
lv.setAdapter(adapter);
}
-: To remove :-
adapter.remove(position == 0);
But not working!!
In your ListAdapter, you would simply filter out the items you do not want displayed by returning modified values for getCount(), getItem() and getItemId() as appropriate.
For Example
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.custom_list_item, null);
holder.tvName = (TextView) rowView.findViewById(R.id.textViewName);
holder.img = (ImageView) rowView.findViewById(R.id.imageView1);
if (items[position].NeedForCollapsed){
System.out.println("set Visibility.Gone");
holder.tvName.setVisibility(View.GONE);
holder.img.setVisibility(View.GONE);
return rowView;
}
//new values
holder.tvName.setText(items[position].name);
holder.img.setImageResource(GetImageID(items[position]));
return rowView;
}
public class Holder
{
TextView tvName;
ImageView img;
}

Listview lag when scrolling, and crash when add item

I have a custom listview with a button to add more elements
but when I add and element the app crash, but when I restart I find that the element is added, (rarely it doesn't crash)
And i
I use custom adapter
class CustomAdapter extends BaseAdapter {
ArrayList<ListItem> listItems = new ArrayList<ListItem>();
CustomAdapter(ArrayList<ListItem> list){
this.listItems = list;
}
#Override
public int getCount() {
return listItems.size();
}
#Override
public Object getItem(int position) {
return listItems.get(position).name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.list_item,null);
TextView name = (TextView) view.findViewById(R.id.name);
TextView lastm = (TextView) view.findViewById(R.id.last);
TextView time = (TextView) view.findViewById(R.id.time);
CircleImageView pic= (CircleImageView) view.findViewById(R.id.pic);
name.setText(listItems.get(i).name);
lastm.setText(listItems.get(i).lastm);
time.setText(listItems.get(i).time);
Bitmap bmp = BitmapFactory.decodeByteArray(listItems.get(i).pic,0,listItems.get(i).pic.length);
pic.setImageBitmap(bmp);
return view;
}
}
and when I add an element the app crashs
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText=(EditText) mView.findViewById(R.id.name);
String name=editText.getText().toString();
boolean result=myDataBase.insertData(imageViewToByte(img),name,"no messages yet","");
if (result) {
Toast.makeText(Main2Activity.this, "Saved in DATABASE", Toast.LENGTH_SHORT).show();
viewLastData();
dialog.dismiss();
}
If your ListView lags it's because you used wrap_content for the listView's layout_height. It forces your ListView to count all the items inside and it has a huge performance impact.
So replace wrap_content by match_parent to avoid those lags.
EDIT: Use a ViewHolder pattern too in your Adapter, see this link.
Here is an example:
// ViewHolder Pattern
private static class ViewHolder {
TextView name, status;
}
#Override #NonNull
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater vi = LayoutInflater.from(getContext());
convertView = vi.inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.text_name);
holder.status = (TextView) convertView.findViewById(R.id.another_text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Then do the other stuff with your item
// to populate your listView
// ...
return convertView
}

Android + ListView + swipe element

i'm using this library for my project, everything is works fine(swiping elements), but my questions is - is it possible to start swiping animation by click on some ListView element?
and second question:
how can i implement timedSwipeUndo for custom object?
here is my code for ListView
final ArrayAdapter<Product> adapter = new MyListAdapter(this,R.layout.text_view,productsDef);
SimpleSwipeUndoAdapter simpleSwipeUndoAdapter = new SimpleSwipeUndoAdapter(adapter, this, new MyOnDismissCallback(adapter));
AlphaInAnimationAdapter animAdapter = new AlphaInAnimationAdapter(simpleSwipeUndoAdapter);
animAdapter.setAbsListView(listView);
assert animAdapter.getViewAnimator() != null;
animAdapter.getViewAnimator().setInitialDelayMillis(INITIAL_DELAY_MILLIS);
listView.setAdapter(animAdapter);
/* Enable drag and drop functionality */
listView.enableDragAndDrop();
listView.setDraggableManager(new TouchViewDraggableManager(R.id.list_row_draganddrop_touchview));
listView.setOnItemMovedListener(new MyOnItemMovedListener(adapter));
listView.setOnItemLongClickListener(new MyOnItemLongClickListener(listView));
/* Enable swipe to dismiss */
listView.enableSimpleSwipeUndo();
/* Add new items on item click */
//listView.setOnItemClickListener(new MyOnItemClickListener(listView));
In Doc is - for timedUndoAdapter use TimedUndoAdapter. but when i trying create adapter i have error:
Error:(249, 51) error: constructor TimedUndoAdapter in class TimedUndoAdapter cannot be applied to given types;
required: V,Context,OnDismissCallback
found: ArrayAdapter<Product>,DefaultProductsListUserEdit,DefaultProductsListUserEdit.MyOnDismissCallback
reason: inferred type does not conform to declared bound(s)
inferred: ArrayAdapter<Product>
bound(s): BaseAdapter,UndoAdapter
where V is a type-variable:
V extends BaseAdapter,UndoAdapter declared in constructor <V>TimedUndoAdapter(V,Context,OnDismissCallback)
i can't use TimedAdapter for custom object or i must override some method?
here is myAdapter:
public class MyListAdapter extends ArrayAdapter<Product> implements UndoAdapter {
private final Context mContext;
HashMap<Product, Integer> mIdMap = new HashMap<Product, Integer>();
ArrayList<Product> products = new ArrayList<Product>();
final int INVALID_ID = -1;
LayoutInflater lInflater;
public MyListAdapter(Context context, int textViewResourceId, List<Product> prod) {
//super(context, textViewResourceId, prod);
super(prod);
lInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
for (int i = 0; i < prod.size(); i++) {
//add(prod.get(i));
mIdMap.put(prod.get(i),i);
}
}
#Override
public long getItemId(final int position) {
//return getItem(position).hashCode();
Product item = (Product) getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
//TextView view = (TextView) convertView;
View view = convertView;
if (view == null) {
//view = (TextView) LayoutInflater.from(mContext).inflate(R.layout.list_row, parent, false);
view = lInflater.inflate(R.layout.item, parent, false);
}
Product p = getItem(position);
//view.setText(getItem(position).getProductName());
((TextView) view.findViewById(R.id.tvDescr)).setText(p.getProductName());
return view;
}
#NonNull
#Override
public View getUndoView(final int position, final View convertView, #NonNull final ViewGroup parent) {
View view = convertView;
if (view == null) {
//view = LayoutInflater.from(mContext).inflate(R.layout.undo_row, parent, false);
view = lInflater.inflate(R.layout.undo_row, parent, false);
}
return view;
}
#NonNull
#Override
public View getUndoClickView(#NonNull final View view) {
return view.findViewById(R.id.undo_row_undobutton);
}
public View getHeaderView(final int position, final View convertView, final ViewGroup parent) {
TextView view = (TextView) convertView;
//View view = convertView;
if (view == null) {
//view = (TextView) LayoutInflater.from(mContext).inflate(R.layout.list_header, parent, false);
//view = lInflater.inflate(R.layout.list_header, parent, false);
}
//view.setText(mContext.getString(R.string.header, getHeaderId(position)));
return view;
}
public long getHeaderId(final int position) {
return position / 10;
}
}
and class MyOnDismissCallback(adapter):
private class MyOnDismissCallback implements OnDismissCallback {
private final ArrayAdapter<Product> mAdapter;
#Nullable
private Toast mToast;
MyOnDismissCallback(final ArrayAdapter<Product> adapter) {
mAdapter = adapter;
}
#Override
public void onDismiss(#NonNull final ViewGroup listView, #NonNull final int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
mAdapter.remove(position);
}
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(
DefaultProductsListUserEdit.this,
"REMOVED ITEM",
Toast.LENGTH_LONG
);
mToast.show();
}
}
Thx in advance!

Categories