Selections disappear when scrolling in listview, along with strange behaviour - java

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
}

Related

Show and hide listview

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;
}
}

How to create two line ListView [closed]

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..

Custom adapter for listview using pasrequery

I am trying to create a demo app where the users enter a search and destination, the data will be queried from parse.com and then the matching result will be displayed in the next screen's listview. I have followed a few tutorials but for sure haven't been able to grasp the concept concretely enough. When I enter a search query, the progress bar shows up and then the application goes back into the previous activity. I can't understand where exactly things are going wrong.
This is my mainactivity class.
public class CarpoolingActivitySearch extends ActionBarActivity {
ListView listView;
ArrayList<Travellers> travellers;
CarpoolingAdapter adapter;
protected ProgressDialog proDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_carpooling_activity_search);
final EditText mSrc = (EditText)findViewById(R.id.carpooling_source);
final EditText mDst = (EditText)findViewById(R.id.destination);
Button mSubmitButton = (Button)findViewById(R.id.carpooling_submit);
mSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String source = mSrc.getEditableText().toString();
String destination = mDst.getEditableText().toString();
listView = (ListView) findViewById(R.id.list);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Carpooling");
query.whereEqualTo("Source", source); //assume you have a DonAcc column in your Country table
query.whereEqualTo("Destination", destination); //assume you have a DonAcc column in your Country table
startLoading();
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
if(e==null)
{
for(int i=0;i<parseObjects.size();i++)
{
Travellers travellers1 = new Travellers();
travellers1.setSource("Source");
travellers1.setDestination("Destination");
travellers.add(travellers1);
if(travellers.size() > 0)
{
adapter = new CarpoolingAdapter(getApplicationContext(),R.layout.activity_carpooling_activity_search,travellers);
listView.setAdapter(adapter);
} else {
AlertDialog.Builder popup = new AlertDialog.Builder(CarpoolingActivitySearch.this);
popup.setMessage("Seems our servers are busy. Try again in some time.");
popup.setPositiveButton("Back",null);
AlertDialog dialog = popup.create();
dialog.show();
}
}
stopLoading();
finish();
}
else {
stopLoading();
AlertDialog.Builder popup = new AlertDialog.Builder(CarpoolingActivitySearch.this);
popup.setMessage(e.getMessage());
popup.setPositiveButton("Back",null);
AlertDialog dialog = popup.create();
dialog.show();
}
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_carpooling_activity_search, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void startLoading() {
proDialog = new ProgressDialog(this);
proDialog.setMessage("loading...");
proDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
proDialog.setCancelable(false);
proDialog.show();
}
protected void stopLoading() {
proDialog.dismiss();
proDialog = null;
}
}
I have created a custom adapter for this purpose.
public class CarpoolingAdapter extends ArrayAdapter<Travellers> {
ArrayList<Travellers> travellersArrayList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
Context context;
public CarpoolingAdapter(Context context, int resource, ArrayList<Travellers> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
travellersArrayList = objects;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null) {
convertView = vi.inflate(Resource,null);
holder = new ViewHolder();
holder.mSource = (TextView)convertView.findViewById(R.id.textView);
holder.mDestination = (TextView)convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.mSource.setText(travellersArrayList.get(position).getSource());
holder.mDestination.setText(travellersArrayList.get(position).getDestination());
return convertView;
}
static class ViewHolder {
public TextView mSource;
public TextView mDestination;
}
}
And the travellers class with a default constructor and getter/setter methods.
public class Travellers {
private String Source;
private String Destination;
public Travellers() {
}
public Travellers(String source, String destination) {
super();
Source = source;
Destination = destination;
}
public String getSource() {
return Source;
}
public void setSource(String source) {
Source = source;
}
public String getDestination() {
return Destination;
}
public void setDestination(String destination) {
Destination = destination;
}
}
The main layout file named activity_carpooling_activity_search.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="com.example.android.myapplication.Carpooling.Carpooling">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/carpooling_source"
android:hint="Source"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/destination"
android:hint="Destination"
android:layout_below="#+id/carpooling_source"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="86dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="#+id/carpooling_submit"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/scrollView"
android:layout_toEndOf="#+id/carpooling_submit"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_below="#+id/carpooling_submit">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list" />
</ScrollView>
</RelativeLayout>
And finally my list_item_deatil.xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<TextView
android:layout_width="174dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_weight="0.13" />
<TextView
android:layout_width="245dp"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView2"
android:layout_weight="0.13" />
</LinearLayout>
What should I modify to make it work appropriately? I am not getting any errors as such.
First of all, you have posted a very long code blocks where indentation is not good enough to read you code.
So what I understood, as your ParseException e is null that means there is no exception. Inside that if block, after the for loop you are calling finish() which is causing your current activity instance to be destroyed thus going to previous activity.
I hope this helps you.

Selecting/highlighting multiple items in listview with custom adapter - Android

I followed a good tutorial, with some changes, to create a custom ListView that will allow me to display multiple images for each row in my ListView. What I would like to do is highlight by selecting multiple items in the list and then perform some sort of action to all of those list items by selecting an option on my Options Menu. However, the problem I seem to be running into is that I cannot select multiple items, even though I have added android:choiceMode="multipleChoice" to the ListView in the .xml file. I realize that this can be done using check boxes or radio buttons, but I would prefer to avoid that. I have attached my source code below. Any help would be appreciated. Lastly, thanks to http://custom-android-dn.blogspot.com/ for a great tutorial. Thanks.
CustomlistviewActivity.java
package DucNguyen.example.customlistview;
public class CustomlistviewActivity extends Activity {
private ListView listViewFootballLegend;
private Context ctx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customlistview);
ctx=this;
List<FootballLegend> legendList= new ArrayList<FootballLegend>();
legendList.add(new FootballLegend("Pele","October 23, 1940 (age 72)","pele","brazil"));
legendList.add(new FootballLegend("Diego Maradona","October 30, 1960 (age 52)","maradona","argentina"));
legendList.add(new FootballLegend("Johan Cruyff","April 25, 1947 (age 65)","cruyff","netherlands"));
legendList.add(new FootballLegend("Franz Beckenbauer","September 11, 1945 (age 67)","beckenbauer","germany"));
legendList.add(new FootballLegend("Michel Platini","June 21, 1955 (age 57)","platini","france"));
legendList.add(new FootballLegend("Ronaldo De Lima","September 22, 1976 (age 36)","ronaldo","brazil"));
listViewFootballLegend = ( ListView ) findViewById( R.id.FootballLegend_list);
listViewFootballLegend.setAdapter( new FootballLegendListAdapter(ctx, R.layout.legend_row_item, legendList ) );
// Click event for single list row
listViewFootballLegend.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FootballLegend o = (FootballLegend) parent.getItemAtPosition(position);
Toast.makeText(CustomlistviewActivity.this, o.getName().toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
FootballLegendListAdapter.java
package DucNguyen.example.customlistview;
public class FootballLegendListAdapter extends ArrayAdapter<FootballLegend> {
private int resource;
private LayoutInflater inflater;
private Context context;
public FootballLegendListAdapter ( Context ctx, int resourceId, List<FootballLegend> objects) {
super( ctx, resourceId, objects );
resource = resourceId;
inflater = LayoutInflater.from( ctx );
context=ctx;
}
#Override
public View getView ( int position, View convertView, ViewGroup parent ) {
convertView = ( RelativeLayout ) inflater.inflate( resource, null );
FootballLegend Legend = getItem( position );
TextView legendName = (TextView) convertView.findViewById(R.id.legendName);
legendName.setText(Legend.getName());
TextView legendBorn = (TextView) convertView.findViewById(R.id.legendBorn);
legendBorn.setText(Legend.getNick());
ImageView legendImage = (ImageView) convertView.findViewById(R.id.legendImage);
String uri = "drawable/" + Legend.getImage();
int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
Drawable image = context.getResources().getDrawable(imageResource);
legendImage.setImageDrawable(image);
ImageView NationImage = (ImageView) convertView.findViewById(R.id.Nation);
uri = "drawable/" + Legend.getNation();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
NationImage.setImageDrawable(image);
return convertView;
}
}
FootballLegend.java
package DucNguyen.example.customlistview;
public class FootballLegend {
public FootballLegend(String name, String born, String image, String nation) {
super();
this.name = name;
this.born = born;
this.image = image;
this.nation = nation;
}
private String name;
private String born;
private String image;
private String nation;
public String getName() {
return name;
}
public void setName(String nameText) {
name = nameText;
}
public String getNick() {
return born;
}
public void setNick(String born) {
this.born = born;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getNation() {
return nation;
}
public void setNation(String image) {
this.image = nation;
}
}
legend_row_item.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/legendImage"
android:layout_width="50dip"
android:layout_height="50dip" />
</LinearLayout>
<TextView
android:id="#+id/legendName"
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="15dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/legendBorn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/legendName"
android:textColor="#343434"
android:textSize="10dip"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail" />
<ImageView
android:id="#+id/Nation"
android:layout_width="45dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:layout_centerVertical="true" />
</RelativeLayout>
activity_customlistview.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/FootballLegend_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="5dp"
android:choiceMode="multipleChoice" >
</ListView>
</LinearLayout>
The root View of each item you will display in list must implement Checkable. When implementing this interface also update the drawable state of View. See this answer for how to do that.
Set a <selector> drawable as background for this root View. Which different color/drawables for checked state and normal states.
Set ListView's choice mode to single choice or multi-choice.
In list adapter, provide item views with above created View as parent layout.
Now, ListView will take care of setting checked/unchecked state on its item views. Also you can call getCheckedItemIds() or getCheckedItemPositions() on ListView to get currently selected items.

Gridview adapter images with title name for images group

I have a gridView witch contains a group of images with two columns, what I want to do is to put a title for a group of images.
Now I can do that but the problem that title is that the title is only in one column and the second column is always empty, how can I put the title in the two columns?
Here is my adapter:
public class MultimediaPhotosAdapter extends BaseAdapter {
private Context mContext;
private List<ImagesDto> imagesDto = new ArrayList<ImagesDto>();
ImagesFlickrDto imagesFlickrDto;
final String formatImage = ImagesNameFormat.FORMAT_IMAGE_DEFAULT.getImagesNameFormat();
ImagesFormatsDto currentImageFormatToDisplay;
GridView gridViewImages;
public MultimediaPhotosAdapter(Context context, GridView gridViewImages) {
this.gridViewImages = gridViewImages;
this.mContext = context;
}
#Override
public int getCount() {
return imagesDto.size();
}
#Override
public Object getItem(int position) {
return imagesDto.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View itemView = null;
HolderElementGridView holderElementGridView;
ImagesDto currentImage = imagesDto.get(position);
if(convertView == null) {
holderElementGridView = new HolderElementGridView();
itemView = View.inflate(mContext,R.layout.item_multimedia_photo,null);
holderElementGridView.image = (NetworkImageView) itemView.findViewById(R.id.imageView);
holderElementGridView.title = (TextView) itemView.findViewById(R.id.title);
itemView.setTag(holderElementGridView);
}
else {
itemView = convertView;
holderElementGridView = (HolderElementGridView)itemView.getTag();
}
if(imagesDto.get(position).isFirstElementOfCategorie()){
holderElementGridView.image.setVisibility(View.GONE);
holderElementGridView.title.setVisibility(View.VISIBLE);
holderElementGridView.title.setText(currentImage.getTitle());
}
else if(imagesDto.get(position).getUrl()!=null){
holderElementGridView.image.setVisibility(View.VISIBLE);
holderElementGridView.title.setVisibility(View.GONE);
holderElementGridView.image.setImageUrl(StringFormat.getUrlImage(mContext, currentImage.getUrl(), currentImageFormatToDisplay.getSuffix(), currentImageFormatToDisplay.getExtension()),VolleySingleton.getInstance(mContext).getImageLoader());
holderElementGridView.image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DrawerLayoutInterface screenInterface=(DrawerLayoutInterface)mContext;
if(screenInterface!=null)
screenInterface.showDiaporama(imagesFlickrDto,position);
}
});
}
// column near title is empty
else{
holderElementGridView.image.setVisibility(View.VISIBLE);
holderElementGridView.title.setVisibility(View.GONE);
}
return itemView;
}
public void update(ImagesFlickrDto imagesFlickrDto){
this.imagesFlickrDto = imagesFlickrDto;
this.imagesDto = imagesFlickrDto.getListImages();
AdministrerImagesSA administrerImages = new AdministrerImagesSAImpl();
currentImageFormatToDisplay = administrerImages.getFormatByProriete(imagesFlickrDto.getImagesFormatsDto(), formatImage);
}
class HolderElementGridView{
NetworkImageView image;
TextView title;
}
}
item_multimedia_photo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:geekui="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<com.netcosports.anderlecht.activity.utils.TypefaceTextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="#dimen/text_size_item_menu"
android:visibility="gone"
android:layout_marginLeft="5dp"
geekui:customTypeface="fonts/DIN-Regular.otf" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:src="#drawable/ic_launcher" >
</com.android.volley.toolbox.NetworkImageView>
</LinearLayout>
</LinearLayout>

Categories