I want to do list view like this. What I want is when user touch 1st item, the 2nd item row appear. When user touch 3rd row item the previous item automatically hide again. How can i achieve this instead of using expandable listview? guide me in achieving this. Thanks in advance.
I'm sorry that i'm a bit busy, so i can't write the code right now. But below is the way which you can use to get what you want. I will add code when i will get time.
There is a parameter name "android:animateayoutchanges", apply it to the parent of your view which will be visible and invisible.
Save the position of the item which you have clicked and expanded.
When you click that item, Set the visibility of the view to visible.
When you again click on that item position, set that item's visibility to gone.
When you click some other item, then set the visibility of the stored item position to gone, set currently selected item's visibility to visible and store it's position.
That's it.
android:animateayoutchanges is used so that when you set the visibility to visible or gone and views move upward or downward, then this movement will have smooth animation.
I will update my answer with code later But you will get an idea from above steps.
UPDATE
public class ShippingAdapter extends RecyclerView.Adapter<ShippingAdapter.ViewHolder> {
private ArrayList<ShippingOptions> list;
private int expandedPosition = -1;
private int listSize = 0;
private int checkedPositon = -1;
private String currency;
public ShippingAdapter(ArrayList<ShippingOptions> list, String currency, AdapterInterface listener) {
this.list = list;
listSize = list.size();
this.currency = currency;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_shipping_options, parent, false);
// Layout in which you will add **android:animatelayoutchanges**
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
ShippingOptions item = list.get(position);
holder.name.setText(item.getName());
holder.fee.setText(utils.getFormattedCurrency(currency, Double.parseDouble(item.getShippingFee())));
holder.description.setText(item.getDescription());
holder.deliveryTime.setText(item.getDeliveryTime());
if (listSize == 1) {
list.get(position).setExpanded(true);
}
**if (list.get(position).isExpanded()) {
holder.expandableView.setVisibility(View.VISIBLE);
holder.checkBox.setVisibility(View.VISIBLE);
if (checkedPositon == position) {
holder.checkBox.setChecked(true);
} else {
holder.checkBox.setChecked(false);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.parent.setElevation(12);
holder.parent.setTranslationZ(6);
holder.parent.setClipToPadding(false);
holder.parent.setClipToOutline(false);
}
} else {
holder.expandableView.setVisibility(View.GONE);
holder.checkBox.setVisibility(View.GONE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.parent.setElevation(0);
holder.parent.setTranslationZ(0);
}
}**
**holder.parent.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public void onClick(View v) {
if (listSize > 1) {
if (expandedPosition == position) {
if (list.get(position).isExpanded()) {
list.get(position).setExpanded(false);
} else {
list.get(position).setExpanded(true);
}
notifyItemChanged(position);
} else {
if (expandedPosition >= 0) {
list.get(expandedPosition).setExpanded(false);
notifyItemChanged(expandedPosition);
}
expandedPosition = position;
list.get(expandedPosition).setExpanded(true);
notifyItemChanged(expandedPosition);
}
}
}
});**
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView name, fee, description, deliveryTime;
public LinearLayout parent, expandableView;
public CheckBox checkBox;
public ViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.tv_shipping_name);
fee = (TextView) v.findViewById(R.id.tv_shipping_fee);
description = (TextView) v.findViewById(R.id.tv_description);
deliveryTime = (TextView) v.findViewById(R.id.tv_delivery_time);
parent = (LinearLayout) v.findViewById(R.id.parent);
expandableView = (LinearLayout) v.findViewById(R.id.expandable_view);
checkBox = (CheckBox) v.findViewById(R.id.checkbox);
}
}
}
list_shipping_options.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:background="#color/white"
android:orientation="vertical"
android:padding="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="?listPreferredItemHeightSmall"
android:gravity="center_vertical">
<TextView
android:id="#+id/tv_shipping_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/text_medium"
android:textColor="#color/colorPrimary" />
<CheckBox
android:id="#+id/checkbox"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentEnd="true"
android:background="?android:attr/listChoiceIndicatorMultiple"
android:button="#null"
android:checked="false"
android:visibility="visible" />
</RelativeLayout>
<LinearLayout
android:id="#+id/expandable_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:visibility="visible">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/label_shipping_fee" />
<TextView
android:id="#+id/tv_shipping_fee"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/lable_description" />
<TextView
android:id="#+id/tv_description"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/delivery_time" />
<TextView
android:id="#+id/tv_delivery_time"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
ShippingOptions.class
public class ShippingOptions implements Serializable {
private String id;
private String name;
private String shippingFee;
private String description;
private String deliveryTime;
private boolean isExpanded;
private boolean isChecked;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getShippingFee() {
return shippingFee;
}
public void setShippingFee(String shippingFee) {
this.shippingFee = shippingFee;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDeliveryTime() {
return deliveryTime;
}
public void setDeliveryTime(String deliveryTime) {
this.deliveryTime = deliveryTime;
}
public boolean isExpanded() {
return isExpanded;
}
public void setExpanded(boolean expanded) {
isExpanded = expanded;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
}
Related
Actually I m new to android development and i m trying to implement my product images like a carousel with a library called "why not" using glide with recyclerview. but I m not able to see the photos like this. I am not getting how to implement a carousel like this, What i m doing wrong please help me . Please guide me someone please
I am trying to make it like this
MY Design xml
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="5dp"
app:cardCornerRadius="8dp"
app:cardElevation="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<org.imaginativeworld.whynotimagecarousel.ImageCarousel
android:id="#+id/carousel"
android:layout_width="match_parent"
android:layout_height="200dp"
android:scaleType="centerCrop">
</org.imaginativeworld.whynotimagecarousel.ImageCarousel>
<TextView
android:id="#+id/roomName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:text="Room with kitchen"
android:textColor="#232222"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/roomRent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:text="Rent 4500/- month"
android:textColor="#232222"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</androidx.cardview.widget.CardView>
Model Class
public class Rooms {
public Rooms(String carousel, String title, int rent) {
this.carousel = carousel;
this.title = title;
this.rent = rent;
}
private String carousel,title;
private int rent;
public String getCarousel() {
return carousel;
}
public void setCarousel(String carousel) {
this.carousel = carousel;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getRent() {
return rent;
}
public void setRent(int rent) {
this.rent = rent;
}
}
My Adapter class
public class RoomsAdapter extends RecyclerView.Adapter<RoomsAdapter.RoomsViewHolder>{
Context context;
ArrayList<Rooms> rooms;
public RoomsAdapter(Context context, ArrayList<Rooms> rooms) {
this.context = context;
this.rooms = rooms;
}
#NonNull
#Override
public RoomsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RoomsViewHolder(LayoutInflater.from(context).inflate(R.layout.room_design_layout, parent, false));
}
#Override
public void onBindViewHolder(#NonNull RoomsViewHolder holder, int position) {
Rooms room = rooms.get(position);
Glide.with(context)
.load(room.getCarousel())
.into(holder.carousel);
holder.roomtitle.setText(room.getTitle());
holder.roomrent.setText(String.valueOf(room.getRent()));
}
#Override
public int getItemCount() {
return rooms.size();
}
public class RoomsViewHolder extends RecyclerView.ViewHolder{
ImageView carousel;
TextView roomtitle, roomrent;
public RoomsViewHolder(#NonNull View itemView) {
super(itemView);
carousel = itemView.findViewById(R.id.carousel);
roomtitle = itemView.findViewById(R.id.roomName);
roomrent = itemView.findViewById(R.id.roomRent);
}
}
}
Here is Sample Code with carousel View by using WHY NOT IMAGE CAROUSEL library. Check this code
I have following Layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fafafa"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingEnd="16dp"
android:paddingLeft="16dp"
android:paddingStart="16dp">
<View
android:id="#+id/item_divider"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginBottom="16dp"
android:background="#D3D3D3" />
<TextView
android:id="#+id/item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="22sp"
tools:text="Léon: The Professional" />
<LinearLayout
android:id="#+id/sub_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/sub_item_genre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
tools:text="Genre: Crime, Drama, Thriller" />
<TextView
android:id="#+id/sub_item_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
tools:text="Year: 1993" />
</LinearLayout>
</LinearLayout>
In my recyclerview adapter:
#Override
public void onBindViewHolder(RecViewHolder holder, int position) {
Movie movie = list.get(position);
boolean expanded = movie.isExpanded();
subItem.setVisibility(expanded ? View.VISIBLE : View.GONE);
holder.title.setOnClickListener(v -> {
boolean expanded = movie.isExpanded();
movie.setExpanded(!expanded);
notifyItemChanged(position);
});
}
As you can see in the code when you click on an item, subItem get hidden/shown.
What I want to achieve is : when you click on last items in the list, I want it to display whole row (include sub item). At the current moment it changes visibility to VISIBLE, but subItem of the row is invisible to user until user scrolls to it.
In the following picture God Father is last visible item. How to display whole row includes God Father as title and sub item when user clicks ?
If you scroll to the bottom of RecyclerView expanded item, the problem will be solved. The key point is using LinearSmoothScroller for scrolling. Try below code:
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.RecViewHolder> {
private List<Movie> list;
private RecyclerView mRecyclerView;
private RecyclerView.SmoothScroller mSmoothScroller;
public RecAdapter(List<Movie> list) {
this.list = list;
}
#Override
public RecViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.item_movie, parent, false);
return new RecViewHolder(view);
}
#Override
public void onBindViewHolder(RecViewHolder holder, int position) {
Movie movie = list.get(position);
holder.bind(movie);
holder.itemView.setOnClickListener(v -> {
boolean expanded = movie.isExpanded();
movie.setExpanded(!expanded);
notifyItemChanged(position);
if (movie.isExpanded()) {
mSmoothScroller.setTargetPosition(position);
new Handler().postDelayed(() -> mRecyclerView.getLayoutManager().startSmoothScroll(mSmoothScroller), 100);
}
});
}
#Override
public int getItemCount() {
return list == null ? 0 : list.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
mRecyclerView = recyclerView;
mSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) {
#Override
protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_ANY;
}
#Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return 150f / displayMetrics.densityDpi;
}
};
}
public class RecViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private TextView genre;
private TextView year;
private View subItem;
public RecViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.item_title);
genre = itemView.findViewById(R.id.sub_item_genre);
year = itemView.findViewById(R.id.sub_item_year);
subItem = itemView.findViewById(R.id.sub_item);
}
private void bind(Movie movie) {
boolean expanded = movie.isExpanded();
subItem.setVisibility(expanded ? View.VISIBLE : View.GONE);
title.setText(movie.getTitle());
genre.setText("Genre: " + movie.getGenre());
year.setText("Year: " + movie.getYear());
}
}
}
Here is the result:
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I created a list view with one line of text for each textView in the list, and was wondering how i can create two lines of text for each item in the list view.
Im using an ArrayAdapter but i couldn't find any helpful documents on the android dev. site on how to create two lines. Additionally, I haven't seen any info. on how to be flexible with the list view- e.g. how do i make editText's inside the listView, or how do i change background color of list items. Can someone please help me bc ive been looking all over but to no avail. Thanks!!
here is a general answer ..that allows you to create your own list view items..
first of all you have to create your listview item for exemple my item is:
medecinListItem.xml
<?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"
android:background="#dddddd"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:background="#drawable/bg_parent_rounded_corner"
android:orientation="vertical"
android:paddingBottom="20dp"
android:paddingTop="20dp" >
<RelativeLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView3"
android:maxWidth="40dp"
android:maxHeight="40dp"
android:minHeight="40dp"
android:minWidth="40dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="15dp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="10dp"
android:layout_weight="4.08"
android:layout_toLeftOf="#+id/imageView"
android:layout_toStartOf="#+id/imageView"
android:layout_toRightOf="#+id/imageView3"
android:layout_toEndOf="#+id/imageView3">
<TextView
android:id="#+id/NomMed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:textStyle="bold" />
<TextView
android:id="#+id/SpeMed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#a0a3a7"
android:textSize="13dp" />
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:scaleType="fitXY"
android:src="#drawable/ic_action_navigation_more_vert"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
<TextView
android:id="#+id/NumMed"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:textColor="#0a80d1"
android:gravity="right" />
<TextView
android:id="#+id/AdreMed"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:gravity="right" />
</LinearLayout>
</LinearLayout>
screenshot of the listitem :
and use custom list adapter that allow you to inflate your items in the listview :
(here is my listAdapter)
public class MedecinListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<MedecinItem> MedecinItems;
public MedecinListAdapter(Activity activity, List<MedecinItem> MedecinItems) {
this.activity = activity;
this.MedecinItems = MedecinItems;
}
#Override
public int getCount() {
return MedecinItems.size();
}
#Override
public Object getItem(int location) {
return MedecinItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.medecin_list_item, null);
TextView nom = (TextView) convertView.findViewById(R.id.NomMed);
TextView specialite = (TextView) convertView
.findViewById(R.id.SpeMed);
TextView adresse = (TextView) convertView
.findViewById(R.id.AdreMed);
TextView numero = (TextView) convertView.findViewById(R.id.NumMed);
ImageView imageMed = (ImageView) convertView.findViewById(R.id.imageView3);
ImageView image = (ImageView) convertView.findViewById(R.id.imageView);
final MedecinItem item = MedecinItems.get(position);
nom.setText(item.getNom());
numero.setText(getString(R.string.numero)+":"+item.getNumero());
adresse.setText(getString(R.string.adresse)+":"+item.getAdresse());
if(Locale.getDefault().getLanguage().equals("ar"))
specialite.setText(avoirSpeEnArabe(item.getSpecialite()));
else
specialite.setText(item.getSpecialite());
String spe=avoirSpeEnFrancais(item.getSpecialite());
System.out.println("spe '"+spe+"'");
int id = getResources().getIdentifier(avoirSpe2(spe).toLowerCase(), "drawable", getPackageName());
imageMed.setImageResource(id);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainActivity.context, v);
popup.getMenuInflater().inflate(R.menu.medecin_list_menu,
popup.getMenu());
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item2) {
line2=item.getNumero();
Emailm=avoirEmail(line2);
switch (item2.getItemId()) {
case R.id.Appeler:
Call(item.getNumero());
break;
case R.id.EnvoyerMsg:
msg(Emailm);
break;
case R.id.AfficherDet:
menuItem = "3";
Vider();
telecharger();
break;
case R.id.Afficher:
String Lat;
String Lon;
Cursor medecin = MainActivity.db.lireMedecin();
while (medecin.getPosition() < medecin.getCount()) {
if (medecin.getString(4).equals(line2)) {
Lat = medecin.getString(5);
Lon = medecin.getString(6);
Mapfrag2.map.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(Lat), Double.parseDouble(Lon)))
.title(item.getNom())
.snippet(line2).icon(BitmapDescriptorFactory
.fromResource(Icone(medecin.getString(7).charAt(0)))));
MainActivity.vp.setCurrentItem(1, true);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(Double.parseDouble(Lat), Double.parseDouble(Lon)));
Mapfrag2.map.moveCamera(center);
Mapfrag2.map.animateCamera(zoom);
}
medecin.moveToNext();
}
break;
case R.id.AvoirRdv:
telecharger();
menuItem = "2";
break;
default:
break;
}
return true;
}
});
}
});
if (!MedecinItems.get(position).anime){
Animation animation = AnimationUtils.loadAnimation(MainActivity.context, R.anim.fade_in);
convertView.startAnimation(animation);
MedecinItems.get(position).anime=true;}
return convertView;
}
}
and this is the MedecinItem:
public class MedecinItem {
private String id,nom, numero, adresse, specialite;
public boolean anime=false;
public MedecinItem(String id, String nom, String numero, String adresse,
String specialite) {
super();
this.id = id;
this.nom = nom;
this.numero = numero;
this.specialite = specialite;
this.adresse = adresse;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getSpecialite() {
return specialite;
}
public void setSpecialite(String specialite) {
this.specialite = specialite;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
}
use it like this:
List<MedecinItem> medecinItems=new ArrayList<MedecinItem>();
//here you add items to your list
MedecinListAdapter mla=new MedecinListAdapter(MainActivity.this,medecinItems);
((ListView) findViewById(R.id.listView)).setAdapter(mla);
and here is the simplest way to create the listView items with two lines..
first declare your list to store two lines items
List<Map<String, String>> list= new ArrayList<Map<String, String>>();
after that create two lines item and add it to that list like this :
Map<String, String> item= new HashMap<String, String>(2);
item.put("Line1", "Name : Charaf");
item.put("Line1","Phone number: 1234567");
list.add(item);
now show the previous items in the listview :
SimpleAdapter adapter = new SimpleAdapter(this, list,
android.R.layout.simple_list_item_2,
new String[] {"Line1", "Line2" },
new int[] {android.R.id.text1, android.R.id.text2 });
listView.setAdapter(Adapter);
to read data from listView ... for example when clickin on item.. add this:
Map<String, String> item= new HashMap<String, String>(2);
item=listview.getAdapter().getItem(position);
String name=item.get("Line1");
You will definitely need to subclass ArrayAdapter and override getView().
ArrayAdapter only knows how to handle one TextView per row . That is what i know as how i understood your question..
How do I use the swipe gesture to remove cards from my recycle-view in the same way that it is done in Google-now etc. So far I've created the cardview application but it's removing cards via a swipe gesture which I'm having problems with. I haven't found a single tutorial or question answered on this website which could help.
Any help would be very much appreciated. My code is below.
MyActivity
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_my);
setContentView(R.layout.activity_my);
RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
ContactAdapter ca = new ContactAdapter(createList(30));
recList.setAdapter(ca);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private List<ContactInfo> createList(int size) {
List<ContactInfo> result = new ArrayList<ContactInfo>();
for (int i=1; i <= size; i++) {
ContactInfo ci = new ContactInfo();
ci.name = ContactInfo.NAME_PREFIX + i;
ci.surname = ContactInfo.SURNAME_PREFIX + i;
ci.email = ContactInfo.EMAIL_PREFIX + i + "#test.com";
result.add(ci);
}
return result;
}
}
ContactInfo.java
public class ContactInfo {
protected String name;
protected String surname;
protected String email;
protected static final String NAME_PREFIX = "Name_";
protected static final String SURNAME_PREFIX = "Surname_";
protected static final String EMAIL_PREFIX = "email_";
}
ContactAdapter.java
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<ContactInfo> contactList;
public ContactAdapter(List<ContactInfo> contactList) {
this.contactList = contactList;
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i) {
ContactInfo ci = contactList.get(i);
contactViewHolder.vName.setText(ci.name);
contactViewHolder.vSurname.setText(ci.surname);
contactViewHolder.vEmail.setText(ci.email);
contactViewHolder.vTitle.setText(ci.name + " " + ci.surname);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout, viewGroup, false);
return new ContactViewHolder(itemView);
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected TextView vSurname;
protected TextView vEmail;
protected TextView vTitle;
public ContactViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.txtName);
vSurname = (TextView) v.findViewById(R.id.txtSurname);
vEmail = (TextView) v.findViewById(R.id.txtEmail);
vTitle = (TextView) v.findViewById(R.id.title);
}
}
}
activity_my.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MyActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
card_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
card_view:cardCornerRadius="4dp"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="20dp"
android:background="#color/bkg_card"
android:text="contact det"
android:gravity="center_vertical"
android:textColor="#android:color/white"
android:textSize="14dp"/>
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/title"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"/>
<TextView
android:id="#+id/txtSurname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Surname"
android:gravity="center_vertical"
android:textSize="10dp"
android:layout_below="#id/txtName"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
/>
<TextView
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:textSize="10dp"
android:layout_marginTop="10dp"
android:layout_alignParentRight="true"
android:layout_marginRight="150dp"
android:layout_alignBaseline="#id/txtName"/>
<TextView
android:id="#+id/txtAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textSize="10dp"
android:layout_alignStart="#id/txtEmail"
android:layout_alignBaseline="#id/txtSurname"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
You can use below code (ItemTouchHelper.SimpleCallback from Android support V7) to remove the cards from RecyclerView using swipe gesture
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
contacts.remove(viewHolder.getAdapterPosition());
ca.notifyItemRemoved(viewHolder.getAdapterPosition());
}
#Override
public void onMoved(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, int fromPos, RecyclerView.ViewHolder target, int toPos, int x, int y) {
super.onMoved(recyclerView, viewHolder, fromPos, target, toPos, x, y);
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
itemTouchHelper.attachToRecyclerView(recList);
I have run into some strange issues with my listview. I created a list using listview, along with a custom adapter to display rows with a text field and multiple images. I beleive that I have that part working well. I also put two buttons at the bottom of the listview so that I can select rows and modify them using the two buttons. I implemented highlighting by simply changing the background color and then setting a boolean flag that is part of each row so I can know what rows are highlighted. Now I am experiencing two issues. The first is that if I select a row and then scroll so that row is outside of the screen, then the row becomes un-highlighted, which is bad. I only want a row to become un-highlighted if the user clicks on it again or if a command is issued. The second problem is that once the adapter is updated or a row moves out of view, if you try to click on a row it will immediately un-highlight itself; this only happens once. After that happens then you can click on the row and it will stay highlighted. I would very much appreciate some help with this.
Regards.
HelmetList.java
public class HelmetList
{
public HelmetList (String name, String address, String img_hel, String img_rec, String img_bat,
String img_dsk, String img_str, Boolean selected)
{
super();
this.name = name;
this.address = address;
this.img_hel = img_hel;
this.img_rec = img_rec;
this.img_bat = img_bat;
this.img_dsk = img_dsk;
this.img_str = img_str;
this.selected = selected;
}
private String name;
private String address;
private String img_hel;
private String img_rec;
private String img_bat;
private String img_dsk;
private String img_str;
private Boolean selected;
public String getName ()
{
return name;
}
public void setName (String s_name)
{
this.name = s_name;
}
public String getAddress ()
{
return address;
}
public void setAddress (String s_address)
{
this.address = s_address;
}
public String getImgHel ()
{
return img_hel;
}
public void setImgHel (String s_img_hel)
{
this.img_hel = s_img_hel;
}
public String getImgRec ()
{
return img_rec;
}
public void setImgRec (String s_img_rec)
{
this.img_rec = s_img_rec;
}
public String getImgBat ()
{
return img_bat;
}
public void setImgBat (String s_img_bat)
{
this.img_bat = s_img_bat;
}
public String getImgDsk ()
{
return img_dsk;
}
public void setImgDsk (String s_img_dsk)
{
this.img_dsk = s_img_dsk;
}
public String getImgStr ()
{
return img_str;
}
public void setImgStr (String s_img_str)
{
this.img_str = s_img_str;
}
public Boolean getSelected ()
{
return selected;
}
public void setSelected (Boolean s_selected)
{
this.selected = s_selected;
}
}
HelmetListAdapter.java
public class HelmetListAdapter extends ArrayAdapter<HelmetList>
{
private int resource;
private LayoutInflater inflater;
private Context context;
public HelmetListAdapter (Context p_context, int p_resource, List<HelmetList> p_objects)
{
super (p_context, p_resource, p_objects);
resource = p_resource;
inflater = LayoutInflater.from (p_context);
context = p_context;
}
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
convertView = ( RelativeLayout ) inflater.inflate( resource, null );
HelmetList Helmet = getItem (position);
TextView hname = (TextView) convertView.findViewById(R.id.h_name);
hname.setText(Helmet.getName ());
TextView haddress = (TextView) convertView.findViewById(R.id.h_address);
haddress.setText(Helmet.getAddress ());
ImageView himage = (ImageView) convertView.findViewById(R.id.h_image);
String uri = "drawable/" + Helmet.getImgHel();
int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
Drawable image = context.getResources().getDrawable(imageResource);
himage.setImageDrawable(image);
ImageView hrec = (ImageView) convertView.findViewById(R.id.h_rec);
uri = "drawable/" + Helmet.getImgRec();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hrec.setImageDrawable(image);
ImageView hlbat = (ImageView) convertView.findViewById(R.id.h_lb);
uri = "drawable/" + Helmet.getImgBat();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hlbat.setImageDrawable(image);
ImageView hldsk = (ImageView) convertView.findViewById(R.id.h_ld);
uri = "drawable/" + Helmet.getImgDsk();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hldsk.setImageDrawable(image);
ImageView hstr = (ImageView) convertView.findViewById(R.id.h_str);
uri = "drawable/" + Helmet.getImgStr();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
hstr.setImageDrawable(image);
return convertView;
}
}
MainActivity.java
public class MainActivity extends Activity
{
private ListView lvhelmets;
private HelmetListAdapter adhelmets;
private Context ctx;
List<Integer> selected;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx = this;
List<HelmetList> helmetlist = new ArrayList<HelmetList>();
helmetlist.add(new HelmetList("Bell", "11111", "helmetpic0", "rec",
"bat", "mm", "str", Boolean.FALSE));
helmetlist.add(new HelmetList("Shoei", "33333", "helmetpic1", "rec",
"bat", "mm", "str", Boolean.FALSE));
helmetlist.add(new HelmetList("Harley Davidson", "55555", "helmetpic2", "rec",
"bat", "mm", "str", Boolean.FALSE));
helmetlist.add(new HelmetList("Joe Rocket", "77777", "helmetpic3", "rec",
"bat", "mm", "str", Boolean.FALSE));
lvhelmets = (ListView) findViewById(R.id.Helmet_list);
lvhelmets.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
adhelmets = new HelmetListAdapter(ctx, R.layout.row_format, helmetlist);
lvhelmets.setAdapter (adhelmets);
Button price = (Button) findViewById(R.id.bPrice);
Button safety = (Button) findViewById(R.id.bSafety);
price.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
lvhelmets.setAdapter(adhelmets);
int count = lvhelmets.getCount();
for (int i = 0; i < count; i++)
{
HelmetList helmet = (HelmetList) lvhelmets.getItemAtPosition(i);
helmet.setSelected(Boolean.FALSE);
}
adhelmets.notifyDataSetChanged();
}
});
safety.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
lvhelmets.setAdapter(adhelmets);
int count = lvhelmets.getCount();
for (int i = 0; i < count; i++)
{
HelmetList helmet = (HelmetList) lvhelmets.getItemAtPosition(i);
helmet.setSelected(Boolean.FALSE);
}
adhelmets.notifyDataSetChanged();
}
});
lvhelmets.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
HelmetList helmet = (HelmetList) parent.getItemAtPosition(position);
if (!helmet.getSelected())
{
view.setBackgroundColor(Color.LTGRAY);
helmet.setSelected(Boolean.TRUE);
}
else
{
view.setBackgroundColor(Color.TRANSPARENT);
helmet.setSelected(Boolean.FALSE);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/Helmet_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="5dp"
android:choiceMode="multipleChoice"
android:layout_weight="1">
</ListView>
<LinearLayout
android:id="#+id/btnHolderLL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/bPrice"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="1dp"
android:paddingLeft="1dp"
android:textColor="#FFFFFF"
android:background="#222222"
android:text="Price"
android:clickable="true" />
<Button
android:id="#+id/bSafety"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:paddingRight="1dp"
android:paddingLeft="1dp"
android:textColor="#FFFFFF"
android:background="#222222"
android:text="Safety"
android:clickable="true" />
</LinearLayout>
</LinearLayout>
row_format.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<!-- ListRow Left side Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/h_image"
android:layout_width="50dip"
android:layout_height="50dip"
android:layout_marginLeft="5dip"/>
</LinearLayout>
<TextView
android:id="#+id/h_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:textColor="#040404"
android:typeface="sans"
android:textSize="20dip"
android:layout_marginTop="5dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/h_address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/h_name"
android:textColor="#343434"
android:textSize="12dip"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail" />
<ImageView
android:id="#+id/h_rec"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/h_lb"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="45dp"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/h_ld"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="85dp"
android:layout_centerVertical="true" />
<ImageView
android:id="#+id/h_str"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentRight="true"
android:layout_marginRight="125dp"
android:layout_centerVertical="true" />
</RelativeLayout>
This happens because of the view recycling.
In the method getView() of your adapter, add the following piece of code :
if (!helmet.getSelected()) {
convertView.setBackgroundColor(Color.LTGRAY);
} else {
convertView.setBackgroundColor(Color.TRANSPARENT);
}
You might want to rewrite your view recycling by the way; the one you implemented is not effective at all.
A first step would be to add this :
#Override
public View getView (int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, parent, false);
}
// continue the rest of the cell data filling
}