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

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.

Related

Show icons only in drop-down of custom Spinner

I Have created a Spinner using adapter with icons and text. Everything is displayed correctly but there is a requirement that Activity spinner should show text only. Icons should only appear in the drop-down list.
It this possible to implement?
public class CustomAdapter extends BaseAdapter {
Context context;
int flags[];
String[] countryNames;
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, int[] flags, String[] countryNames) {
this.context = applicationContext;
this.flags = flags;
this.countryNames = countryNames;
inflter = (LayoutInflater.from(applicationContext));
}
[id3844467|#Override]
public int getCount() {
return flags.length;
}
[id3844467|#Override]
public Object getItem(int i) {
return null;
}
[id3844467|#Override]
public long getItemId(int i) {
return 0;
}
[id3844467|#Override]
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.custom_spinner_items, null);
ImageView icon = (ImageView) view.findViewById(R.id.imageView);
TextView names = (TextView) view.findViewById(R.id.textView);
icon.setImageResource(flags[i]);
names.setText(countryNames[i]);
return view;
}
}
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="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="40dp"
android:layout_height="40dp"
android:padding="5dp"
android:src="#drawable/ic_launcher" /> // for check that icon existing
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="0dp"
android:text="Demo" // for check that text existing
android:textColor="#000" />
</LinearLayout>
Set these two property in spinner hopeFully it will work
android:dropDownHeight="0dp"
android:dropDownWidth="0dp"
i'am not sure but change your getItemId like this :
#Override
public long getItemId(int position) {
return position;
}
and don't return null on getItem

Custom ListView with image, text and add item button

I am quite new to Android and can't achieve this, been searching all day.
Layout I'm trying to create.
I have created the custom xml layout, I have found ways to add items on create, but I need the list to be empty and than when the button is pressed to add from a list.
This is the layout:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow>
<ImageView
android:id="#+id/info_img_view"
android:layout_width="30dp"
android:layout_height="30dp" />
<TextView
android:id="#+id/info_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<TextView
android:id="#+id/info_time_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="right"
/>
</TableRow>
I have a ListView in the main activity:
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
How do I go about this? I would appreciate it if someone can point me to a resource where I can learn what the code is actually doing, not the tutorials I find where I just copy and paste...
Thanks!
Edit, a bit more explanation of what I'm trying to achieve
I have 6 buttons. When a button is pressed it should add a list item with two textviews, and one image out of total three images.
So for instance if Button1 is pressed: Add list item > "Text one" "Text one" "imageTwoOfThree".
Than, if Button2 is pressed: Add list item on top > "Text two" "Text two" "imageTwoOfThree"
And so on... The text is hardcoded.
Here use this:
I have created a list with dummydata you can change the text and Image according to you
First create a class Data:
public class Data {
private String name,price;
private int imageId;
public Data(){}
public Data(String name,String price,int imageId){
this.name = name;
this.price = price;
this.imageId = imageId;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
}
Then create a ListView Adapter to handle your data:
public class ListViewAdaptor extends RecyclerView.Adapter<ListViewAdaptor.MyViewHolder> {
private List<Data> mDataList;
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView name,price;
public ImageView imageView;
public MyViewHolder(View view){
super(view);
name = (TextView) view.findViewById(R.id.name);
price= (TextView) view.findViewById(R.id.price);
imageView = (ImageView) view.findViewById(R.id.image);
}
}
public ListViewAdaptor(List<Data> dataList){
this.mDataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_view_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Data data = mDataList.get(position);
holder.name.setText(data.getName());
holder.price.setText(data.getPrice());
holder.imageView.setImageResource(data.getImageId());
}
#Override
public int getItemCount() {
return mDataList.size();
}
}
layout for your list view items name it list_view_item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"
android:id="#+id/image"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/name"
android:text="name"
android:gravity="center"
android:textSize="26sp"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/price"
android:text="price"
android:gravity="center"
android:textSize="26sp"
android:layout_weight="1"/>
</LinearLayout>
Then from your activity where you want to add listView add recyclerView in layout:
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_view">
</android.support.v7.widget.RecyclerView>
Then use this recyclerview like this:
//I have called it from my MainActivity you can use it in whatever activity you'll like
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ListViewAdaptor mAdapter;
private List<Data> mDataList = new ArrayList<>();
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new ListViewAdaptor(mDataList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mAdapter);
prepareList();
}
public void prepareList(){
Data data = new Data("Item1","Price1",R.drawable.star);
mDataList.add(data);
data = new Data("Item2","Price2",R.drawable.star);
mDataList.add(data);
data = new Data("Item3","Price3",R.drawable.star);
mDataList.add(data);
data = new Data("Item4","Price4",R.drawable.star);
mDataList.add(data);
data = new Data("Item5","Price5",R.drawable.star);
mDataList.add(data);
}
}
Hope this helps!!!
You will find lots of online resources for this. But let me put it in a brief way.
Assuming you want to store 2 textviews in one single row.
1. For each layout of the row, you will need to make a custom layout xml file and design your layout there.
Next, make a class which stores the data and returns the data through getters.
class Category {
private String categoryName;
private String categoryImageURL;
Category (String categoryName, String categoryImageUrl) {
this.categoryName = categoryName;
this.categoryImageURL = categoryImageUrl;
}
String getCategoryName () {
return categoryName;
}
String getCategoryImageURL () {
return categoryImageURL;
}
}
Now make a custom arrayadapter which will link the data and the layout.
Extend the arrayadapter class with the class you defined above.
private class categoryArrayAdapter extends ArrayAdapter<Category> {
private Context context;
private List<Category> categories;
public categoryArrayAdapter (Context context, int resource, ArrayList<Category> objects) {
super(context, resource, objects);
this.context = context;
this.categories = objects;
}
public View getView (int position, View convertView, ViewGroup parent) {
Category category = categories.get(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.category_row_view, null);
TextView categoryListRowText = (TextView) view.findViewById(R.id.categoryListRowText);
TextView categoryListRowImage = (TextView) view.findViewById(R.id.categoryListRowImage);
categoryListRowText.setText(category.getCategoryName());
categoryListRowImage.setText(category.getCategoryImageURL());
return view;
}
}
Finally link the adapter to your listview
ArrayAdapter<Category> adapter = new categoryArrayAdapter(this, 0, categories);
categoryListView.setAdapter(adapter);
Hope this answered you question.

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

android chat thumbnail position

I have a conversation page with bubble and thumbnail user image, I have problem with thumbnail position: when I send text thumbnail must show on the right and when my friend sent text his thumbnail must show on the left
My XML item is :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dp" >
<LinearLayout
android:id="#+id/wrapper"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="0.5dp" >
<ImageView
android:id="#+id/icon"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#drawable/user_four"
android:padding="0dp" />
<TextView
android:id="#+id/comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dip"
android:textColor="#2e2e2e"
android:paddingLeft="10dp" />
</LinearLayout>
</RelativeLayout>
and my Java code is :
public class ChatArrayAdapter extends ArrayAdapter<Comment> {
private TextView countryName;
private List<Comment> countries = new ArrayList<Comment>();
private LinearLayout wrapper;
#Override
public void add(Comment object) {
countries.add(object);
super.add(object);
}
public ChatArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public int getCount() {
return this.countries.size();
}
public Comment getItem(int index) {
return this.countries.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.listitem_chat, parent, false);
}
wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
Comment coment = getItem(position);
countryName = (TextView) row.findViewById(R.id.comment);
countryName.setText(coment.comment);
countryName.setBackgroundResource(coment.left ? R.drawable.other_bubble : R.drawable.own_bubble);
wrapper.setGravity(coment.left ? Gravity.LEFT : Gravity.RIGHT);
return row;
}
public Bitmap decodeToBitmap(byte[] decodedByte) {
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
}
If you know in getView() method that the text is your's or your friend's you can change gravity attribute to left or right, depending on the condition, of the linear layout.
Use seperate layout for left and right then inflate it with the correct layout in your get view

Selections disappear when scrolling in listview, along with strange behaviour

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
}

Categories