Ive looked at a few other questions on stackoverflow about this questions however I am not able to implement this into my code as I have done things a bit differently I believe. I am still learning Android Studio so please bear with me for any stupidity.
I'm looking to create check boxes on the right side of the listview I currently have that when checked will stay in that state when the user loads the application back in.
XML:
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Which Will Be Next"
android:textAllCaps="false"
android:textColor="#f1b75a"
android:textSize="32sp"
android:textStyle="bold" />
<ListView
android:id="#+id/results_listview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_below="#+id/textView3"></ListView>
</RelativeLayout>
Activity Code:
public class .... extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_flavour);
ListView resultListView = (ListView) findViewById(R.id.results_listview);
HashMap<String, String> nameAddress = new HashMap<>();
nameAddress.put("exmp ", "Locate");
List<HashMap<String, String>> listItems = new ArrayList<>();
SimpleAdapter adapter = new SimpleAdapter(this, listItems, R.layout.list_item, new String[]{"First Address", "Second Address"},new int[]{R.id.tv1, R.id.tv3});
Iterator it = nameAddress.entrySet().iterator();
while (it.hasNext()){
HashMap<String, String> resultsMap = new HashMap<>();
Map.Entry pair = (Map.Entry)it.next();
resultsMap.put("First Address", pair.getKey().toString());
resultsMap.put("Second Address", pair.getValue().toString());
listItems.add(resultsMap);
}
resultListView.setAdapter(adapter);
}
}
List Items.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckedTextView
android:id="#+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ffa200"
android:textSize="21sp"
android:textStyle="bold"
android:drawableLeft="?android:attr/listChoiceIndicatorMultiple"
/>
<CheckedTextView
android:id="#+id/tv3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:textSize="16sp"
android:textStyle="bold"
/>
</LinearLayout>
Any help is appreciated :)
I suggest the you can use Recyclerview instead listview, Try this way
public class CardViewDataAdapter extends
RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
private List<Student> stList;
public CardViewDataAdapter(List<Student> students) {
this.stList = students;
}
// Create new views
#Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.cardview_row, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
final int pos = position;
viewHolder.tvName.setText(stList.get(position).getName());
viewHolder.tvEmailId.setText(stList.get(position).getEmailId());
viewHolder.chkSelected.setChecked(stList.get(position).isSelected());
viewHolder.chkSelected.setTag(stList.get(position));
viewHolder.chkSelected.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Student contact = (Student) cb.getTag();
contact.setSelected(cb.isChecked());
stList.get(pos).setSelected(cb.isChecked());
Toast.makeText(
v.getContext(),
"Clicked on Checkbox: " + cb.getText() + " is "
+ cb.isChecked(), Toast.LENGTH_LONG).show();
}
});
}
// Return the size arraylist
#Override
public int getItemCount() {
return stList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvName;
public TextView tvEmailId;
public CheckBox chkSelected;
public Student singlestudent;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
tvName = (TextView) itemLayoutView.findViewById(R.id.tvName);
tvEmailId = (TextView) itemLayoutView.findViewById(R.id.tvEmailId);
chkSelected = (CheckBox) itemLayoutView
.findViewById(R.id.chkSelected);
}
}
// method to access in activity after updating selection
public List<Student> getStudentist() {
return stList;
}
}
http://android-pratap.blogspot.in/2015/01/recyclerview-with-checkbox-example.html
Related
Hi I am completing a school project, and I need the background of a list item to be red with white text if the urgent switch is on. Currently, if I add an item with the urgent switch all of the background of the list view changes. I seen somewhere someone said to use an array, but when I tried that block of code it wouldn't work. Thanks in advance!
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="576dp"
android:layout_columnSpan="3"
android:focusableInTouchMode="true"
android:isScrollContainer="true">
</ListView>
<EditText
android:id="#+id/editText"
android:layout_width="209dp"
android:layout_height="wrap_content"
android:layout_weight="0"
android:hint="#string/typeHere"
android:textSize="20dp" />
<Switch
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="1"
android:layout_column="1"
android:layout_weight="0"
android:text="#string/urgent" />
<Button
android:id="#+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="1"
android:layout_column="2"
android:layout_weight="0"
android:text="#string/add" />
</GridLayout>
<?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:orientation="vertical">
<TextView
android:id="#+id/to_do_TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Testing"
android:textSize="25dp" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
Button buttonAdd;
Boolean urgent = false;
EditText editText;
ListAdapter adapter;
ListView myListView;
Switch switch1;
ArrayList<String> itemList = new ArrayList<String>( Arrays.asList("Clean Bathroom","Buy Apples","Buy Bananas" ));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//declare variables
buttonAdd = findViewById(R.id.buttonAdd);
editText = findViewById(R.id.editText);
switch1 = findViewById(R.id.switch1);
ListView myListView = findViewById(R.id.listView);
myListView.setAdapter(adapter = new ListAdapter());
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
itemList.add(editText.getText().toString());
editText.setText("");
//also tried setting value you here and using in getView
if(switch1.isChecked()){
urgent = true;
} else{
urgent = false;
}adapter.notifyDataSetChanged();
}
});
}
// adapter class
class ListAdapter extends BaseAdapter{
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int position) {
return itemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View old, ViewGroup parent) {
View newView =old;
LayoutInflater inflater = getLayoutInflater();
if(newView==null){
newView = inflater.inflate(R.layout.item,parent,false);
}
TextView textview= newView.findViewById(R.id.to_do_TextView);
textview.setText(getItem(position).toString());
if(switch1.isChecked()){
textview.setBackgroundColor(Color.RED);
textview.setText(getItem(position).toString());
}return newView;
}
//to do row class
class ToDoItem {
String name;
Boolean urgent;
}}}
This happen because you use a global variable Boolean urgent to all items in list.
You need send to ListAdapter the information if is urgent with a String doing use of class ToDoItem like this:
itemList.add(new ToDoItem(itemList.add(editText.getText().toString()), switch1.isChecked()));
the full code would be:
public class MainActivity extends AppCompatActivity {
Button buttonAdd;
EditText editText;
ListAdapter adapter;
ListView myListView;
Switch switch1;
//Create list
ArrayList<ToDoItem> itemList = new ArrayList<>();
//add data
itemList.add(new ToDoItem("Clean Bathroom", false);
itemList.add(new ToDoItem("Buy Apples", false);
itemList.add(new ToDoItem("Buy Bananas", true);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//declare variables
buttonAdd = findViewById(R.id.buttonAdd);
editText = findViewById(R.id.editText);
switch1 = findViewById(R.id.switch1);
ListView myListView = findViewById(R.id.listView);
myListView.setAdapter(adapter = new ListAdapter());
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Here set to list a item with String and boolean
itemList.add(new ToDoItem(itemList.add(editText.getText().toString()), switch1.isChecked()));
editText.setText("");
adapter.notifyDataSetChanged();
}
});
}
// adapter class
class ListAdapter extends BaseAdapter{
#Override
public int getCount() {
return itemList.size();
}
//Here get a item like ToDoItem
#Override
public ToDoItem getItem(int position) {
return itemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View old, ViewGroup parent) {
View newView =old;
LayoutInflater inflater = getLayoutInflater();
if(newView==null){
newView = inflater.inflate(R.layout.item,parent,false);
}
TextView textview= newView.findViewById(R.id.to_do_TextView);
//Here get a name
textview.setText(getItem(position).name);
if(getItem(position).urgent){
textview.setBackgroundColor(Color.RED);
}
return newView;
}
}
//Class that have the information on items
class ToDoItem {
String name;
Boolean urgent;
public ToDoItem(String name, Boolean urgent) {
this.name = name;
this.urgent = urgent;
}
}
}
My app that I am creating has two listviews. My second listview does not look the same as my second one. The lines that seperate each item are too close to the text, but I want them to have space on both the top and bottom, like the first list. I have tried to change the padding and the margins but that does not works and I have also tried to change it in one of the Java classes but I get error messages.
Here are two pictures for comparison(The first list is on the left and the second list is on the right)
The second list:
<ListView
android:id="#+id/countryselector"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_above="#+id/checkItem"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="60dp"
android:clickable="false"/>
<TextView
android:id="#+id/checkboxtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/emptyElement"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="NO ITEM AVAILABLE!"
android:textColor="#525252"
android:textSize="19.0sp"
android:visibility="gone" />
<Button
android:id="#+id/checklist"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentTop="true"
android:gravity="end"
android:layout_alignParentLeft="true"
android:text=""
android:background="#mipmap/arrow2"
My first list:
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="left"
android:text="Favorites"
android:textColor="#222"
android:textSize="15dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="2dp"
android:textStyle="normal" />
<Button
android:id="#+id/tofavorites"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_alignParentTop="true"
android:gravity="end"
android:layout_alignParentLeft="true"
android:text=""
android:background="#mipmap/arrow2" />
<ListView
android:layout_marginTop="60dp"
android:id="#+id/countrieselector"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:clickable="false" />
<TextView
android:id="#+id/checkboxtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Here Is my adapter class for the second list:
public class AdapterFavorite extends BaseAdapter {
ArrayList<String> items;
ArrayList<String> items1;
LayoutInflater inflater;
ArrayList selectedItems;
List<Item> dummyItems;
ArrayList<Integer> itemsValue = new ArrayList<>();
Activity activity;
DbUtility dbUtility;
Context context;
AdapterFavorite(Activity activity, ArrayList<String> items, Context context) {
this.items = items;
inflater = activity.getLayoutInflater();
selectedItems = new ArrayList<String>();
this.activity = activity;
this.context = context;
dbUtility = new DbUtility(activity);
}
#Override
public int getCount() {
return items.size();
}
#Override
public String getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
dbUtility.open();
View v = view;
if (v == null) {
v = inflater.inflate(R.layout.checkboxlayoutfavorite, null);
}
TextView textview_countries = (TextView) v.findViewById(R.id.Textview_languages);
Button button = (Button) v.findViewById(R.id.checkbox);
items1 = new ArrayList<>();
textview_countries.setText(items.get(i));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
////Where I tried to add/move items when the checkbox is clicked
dbUtility.delete_byID(items.get(i));
items.remove(i);
notifyDataSetChanged();
}
});
return v;
}
}
Here is my main Java class for the second listL:
ublic class FavoriteActivity extends AppCompatActivity {
DbUtility dbUtility;
List<Item> dummyItems = new ArrayList<>();
Button mainList;
KeyboardPrefManager keyboardPrefManager;
ArrayList<String> items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ListView chl = (ListView) findViewById(R.id.languageselector);
mainList = (Button) findViewById(R.id.checklist);
chl.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
items = new ArrayList<>();
dbUtility = new DbUtility(this);
dbUtility.open();
dummyItems = dbUtility.getAllContacts();
keyboardPrefManager = new KeyboardPrefManager(this);
for (int a = 0; a < dummyItems.size(); a++) {
items.add(dummyItems.get(a).getValue());
}
mainList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(FavoriteActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
AdapterFavorite adapter = new AdapterFavorite(this, items, this);
chl.setAdapter(adapter);
chl.setEmptyView(findViewById(R.id.emptyElement));
chl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String item = items.get(i); // Getting the dummy item from the List with position i
Toast.makeText(FavoriteActivity.this, "Clicked on " + item, Toast.LENGTH_SHORT).show();
keyboardPrefManager.selectKeyboard(item);
}
});}}
Please check your list item xml for both list same or not.Thanks
I am working on an Android project in which I am currently working on chat functionality. Now, whenever an user sends a message, it is added in the ListView, which is populated by BaseAdapter. A new message is added by baseAdapterObject.add(item);.
Now, whenever an user sends a message, I am adding it directly to the already existing List and then waiting for a reply from the server confirming the message was delivered. For the first step, I would like to show a Gray checkmark, and for 2nd message received from server, I would like to show Blue checkmark.
Unfortunately, I don't know how to access the already populated list and change the background image of an ImageView. . Each message has a random-number, with which I can compare for which message I received confirmation.
Code :
public void recieveUpdatedMessageFromServer(String channelName, Map<String, Object> input){
String randomNumberFromServer = ((Map) input.get("data")).get("random").toString();
if (randomNumberFromServer.equals(randomNos)) {
messageRecieved = true;
randomNos = "";
}
chatMessagesAdapter.add(insertMap);
runOnUiThread(new Runnable() {
#Override
public void run() {
chatMessagesAdapter.notifyDataSetChanged();
}
});
public class ChatMessagesAdapter extends BaseAdapter {
private Activity activity = null;
private ArrayList<HashMap<String, String>> data;
private LayoutInflater inflater = null;
public ChatMessagesAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void add(HashMap<String, String> item) {
data.add(item);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.chat_messages_row, parent, false);
TextView chatText = (TextView) vi.findViewById(R.id.chatText);
ImageView userImage = (ImageView) vi.findViewById(R.id.chatImage);
TextView firstName = (TextView) vi.findViewById(R.id.personName);
ImageView checkMark = (ImageView) vi.findViewById(R.id.checMarkChat);
HashMap<String, String> chatList;
chatList = data.get(position);
chatText.setText(chatList.get(ChatMessagesActivity.chatText));
checkMark.setBackgroundResource(R.drawable.blue_icon);
firstName.setText(chatList.get(ChatMessagesActivity.firstName));
if (!(chatList.get(ChatMessagesActivity.chatImageId).equals("0"))) {
Picasso.with(context).load(StaticRestTemplate.baseURL + "image/" + chatList.get(ChatMessagesActivity.chatImageId)).fit().into(userImage);
}
return vi;
}
}
}
chat_messages_row.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="130dp"
android:orientation="horizontal"
android:padding="2.5dip">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="125dp"
android:id="#+id/frameLayout2">
<ImageView
android:id="#+id/chatImage"
android:layout_width="107dp"
android:layout_height="107dp"
android:padding="2dp" />
</FrameLayout>
<TextView
android:id="#+id/chatText"
android:layout_width="230dp"
android:layout_height="76dp"
android:layout_gravity="right|center_vertical"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/frameLayout2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/personName"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/chatText"
android:layout_alignEnd="#+id/chatText"
android:layout_toRightOf="#+id/textView"
android:layout_toEndOf="#+id/textView"
/>
<ImageView
style="?android:attr/buttonStyleSmall"
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/checMarkChat"
android:background="#drawable/blue_icon"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/personName"
android:layout_alignEnd="#+id/personName" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="49dp"
android:layout_marginStart="49dp"
android:layout_marginTop="208dp" />
</RelativeLayout>
I hope this much information is enuf. Kindly let me know if anything else required. Thank you. :-)
Consider using a class object to help.
For example, you can create a list of message objects:
class Message {
private String message;
private boolean gray_tick;
private boolean blue_tick;
....
}
Change your hashmap in your BaseAdapter to take in the corresponding object.
private ArrayList<HashMap<String, Message>> data;
From there, you can set your BaseAdapter to read these values and show the correct coloured ticks at the right time.
Hope this helps!
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 to select row item using Tick mark like iphone in android?iam using imageview in list_row.xml.when i click the list row item then i show image in row imageview.
if(getItem(position)!=null){
img.setvisibilty(View.Visible);}
else{System.out.println("imagenull");}
iam using this but image display in last row only.please help me how to select item using tickmark image.
public class DistanceArrayAdapter extends ArrayAdapter<Constant>{
public static String category,state,miles;
public ImageView img;
private Context context;
private int current = -1;
ArrayList<Constant> dataObject;
public DistanceArrayAdapter(Context context, int textViewResourceId,
ArrayList<Constant> dataObject) {
super(context, textViewResourceId, dataObject);
this.context=context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView=convertView;
if(rowView==null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.category_row, parent, false);
}
//TextView textView = (TextView) rowView.findViewById(R.id.text1);
TextView textView1 = (TextView) rowView.findViewById(R.id.text2);
//textView.setText(""+getItem(position).id);
textView1.setText(""+getItem(position).caption);
img=(ImageView)rowView.findViewById(R.id.img);
img.setVisibility(View.GONE);
if(position%2==1)
{
rowView.setBackgroundResource(R.color.even_list);
}
else
{
rowView.setBackgroundResource(R.color.odd_list);
}
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(img.getVisibility()==View.GONE)
{
img.setVisibility(View.VISIBLE);
System.out.println("1");
}
if(img.getVisibility()==View.VISIBLE){
img.setVisibility(View.GONE);
System.out.println("12");
}
miles=getItem(position).caption;
System.out.println("miles"+miles);
}
});
return rowView;
}
}
Drawing from https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
String[] GENRES = new String[] {"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"};
private CheckBoxAdapter mCheckBoxAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.lv);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
listView.setAdapter(mCheckBoxAdapter);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
for (int i = 0; i < GENRES.length; i++) {
if (mCheckBoxAdapter.mCheckStates.get(i) == true) {
result.append(GENRES[i]);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 1000).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int position, long id) {
mCheckBoxAdapter.toggle(position);
}
class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener {
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
String[] gen;
private SparseBooleanArray mCheckStates;
private SparseBooleanArray mCheckStates;
CheckBoxAdapter(MainActivity context, String[] genres) {
super(context, 0, genres);
mCheckStates = new SparseBooleanArray(genres.length);
mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gen = genres;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return gen.length;
}
}
}
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
And the XML file for the checkboxes:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="34dp"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:layout_marginRight="22dp"
android:layout_marginTop="23dp" />
</RelativeLayout>
When you click the button a toast message with list of item choosen is displayed. You can modify the above according to your requirements.
Set selection mode on your ListView
//if using ListActivity or ListFragment
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//or
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//myListView is reference to your ListView
1.Make visibility gone to you tick mark image
2.Implement view.setOnClickListener in arrayadapter.
3.In that check image.getVisibility()==View.GONE then make image.setVisibity(View.Visible)
4.if image.getVisiblity()==View.VISIBLE then make your image.setVisibity(View.GONE)
Try this.