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..
Related
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
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;
}
}
I am using a loop to read all the spinner elements (inside a cardview) in the listview.
But the loop gives one item less i.e. the last item.
I have included all the source code.
What may be the problem?
Is there any other way to read all the items in listview?
Main Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/ll_gpa"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ListView
android:id="#+id/listSubs"
android:scrollbars="none"
android:layout_height="0dip"
android:layout_width="match_parent"
android:layout_weight="1"
/>
<Button
android:text="Calculate GPA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnGpa"
android:textAlignment="center"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</RelativeLayout>
Single Item Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cv_subject"
android:layout_marginBottom="2dp"
android:layout_marginTop="2dp"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="15dp"
android:id="#+id/rl_subject"
>
<TextView
android:id="#+id/subTitle"
android:textSize="16sp"
android:text="Subject"
android:layout_toStartOf="#+id/subGrade"
android:layout_toLeftOf="#+id/subGrade"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="none"
/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:dropDownWidth="40dp"
android:textAlignment="center"
android:entries="#array/grades"
android:id="#+id/subGrade"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
MainActivity
public class MainActivity extends AppCompatActivity {
private static SubjectArrayAdapter adapter;
private ProgressDialog progress;
JsonArray subs = new JsonArray();
JsonArray dataGrades = new JsonArray();
ListView listView;
ArrayList<SubjectClass> subjects = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
res = new GetSubNames().execute();
subs = res.getAsJsonArray("subjects");
for (int i = 0; i < subs.size(); i++){
JsonObject temp = subs.get(i).getAsJsonObject();
subjects.add(new SubjectClass(temp.get("subCode").getAsString(), temp.get("subTitle").getAsString()));
}
adapter = new SubjectArrayAdapter(subjects,GpaActivity.this);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Button btnGpa = (Button) findViewById(R.id.btnGpa);
btnGpa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CalcGPA().execute();
JsonArray temparr = new JsonArray();
for (int i = 0; i < listView.getChildCount(); i++) {
// Get row's spinner
View listItem = listView.getChildAt(i);
JsonObject temp = new JsonObject();
Spinner spinner = (Spinner) listItem.findViewById(R.id.subGrade);
temp.addProperty("subject",subjects.get(i).getCode());
temp.addProperty("grade", spinner.getSelectedItem().toString());
temparr.add(temp);
}
dataGrades = temparr;
}
});
}
}
Custom Class
class SubjectClass{
String title;
String code;
SubjectClass(String code, String title) {
this.code = code;
this.title = title;
}
String getTitle(){
return this.title;
}
String getCode(){
return this.code;
}
void setCode(String code){
this.code = code;
}
void setTitle(String title){
this.title = title;
}
}
Custom ArrayAdapter
public class SubjectArrayAdapter extends ArrayAdapter<SubjectClass>{
private ArrayList<SubjectClass> dataSet;
Context mContext;
// View lookup cache
private static class ViewHolder {
TextView txtName;
}
public SubjectArrayAdapter(ArrayList<SubjectClass> data, Context context) {
super(context, R.layout.item_subject, data);
this.dataSet = data;
this.mContext=context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
SubjectClass dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_subject, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.subTitle);
result = convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result = convertView;
}
viewHolder.txtName.setText(dataModel.getCode() + " " + dataModel.getTitle());
// Return the completed view to render on screen
return convertView;
}
}
for (int i = 0; i < listView.getCount(); i++) {
// Get row's spinner
View listItem = listView.getItemAtPosition(i);
JsonObject temp = new JsonObject();
Spinner spinner = (Spinner) listItem.findViewById(R.id.subGrade);
temp.addProperty("subject",subjects.get(i).getCode());
temp.addProperty("grade", spinner.getSelectedItem().toString());
temparr.add(temp);
}
Check for above code in main activity. Use .getCount() instead .getChildCount()
and use .getItemAtIndex() instead .getChildAt().
I hope this solves the issue.
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
}
I am trying to Develop a custom List menu with a unique Icon on the left a title and a small description underneath the title. I tried a few variations but none of them seem to work.
Here is what I did
item_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="15dp"
android:paddingLeft="10dp"
android:paddingBottom="15dp" >
<ImageView
android:id="#+id/item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/union_europea" />
<TextView
android:id="#+id/year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/item_icon"
android:layout_toRightOf="#+id/item_icon"
android:text="Small Text"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/countryName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/year"
android:layout_alignParentTop="true"
android:text="Large Text"
android:textSize="18dp"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/continent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Medium Text"
android:paddingRight="10dp"
android:textSize="12dp"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
then I did the main_activity.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"
tools:context=".MainActivity" >
<ListView
android:id="#+id/countryList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
then I did the Countries.java
public class Countries {
private String country;
private int year;
private int iconID;
private String continent;
public Countries (String country, int year, int iconID, String continent){
super();
this.country = country;
this.year = year;
this.iconID = iconID;
this.continent = continent;
}
public String getCountry() {
return country;
}
public int getYear() {
return year;
}
public int getIconID() {
return iconID;
}
public String getContinent() {
return continent;
}
}
then I did the MainActivity.java
public class MainActivity extends Activity {
private List<Countries> myCountries = new ArrayList<Countries>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateCountryList();
populateListView();
}
private void populateCountryList() {
myCountries.add(new Countries("European Union", 2014, R.drawable.union_europea, "Europe"));
myCountries.add(new Countries("Spain", 2015, R.drawable.espania, "Europe"));
myCountries.add(new Countries("Finland", 2016, R.drawable.finlandia, "Europe"));
myCountries.add(new Countries("France ", 2017, R.drawable.francia, "Europe"));
myCountries.add(new Countries("Ireland ", 2018, R.drawable.irlanda, "Europe"));
myCountries.add(new Countries("Italy", 2014, R.drawable.italia, "Europe"));
myCountries.add(new Countries("Monaco ", 2014, R.drawable.monaco, "Europe"));
myCountries.add(new Countries("Portugal", 2014, R.drawable.portugal, "Europe"));
myCountries.add(new Countries("Russia", 2014, R.drawable.rusia, "Europe"));
myCountries.add(new Countries("Malta", 2014, R.drawable.malta, "Europe"));
}
private void populateListView() {
ArrayAdapter<Countries> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.countryList);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<Countries>{
public MyListAdapter(){
super(MainActivity.this, R.layout.item_view, myCountries);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View itemView = convertView;
// make sure we have a view to work with
if(itemView == null){
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
// find country
Countries currentCountry = myCountries.get(position);
// fill the view
ImageView imageView = (ImageView) itemView.findViewById(R.id.item_icon);
imageView.setImageResource(currentCountry.getIconID());
TextView countryText = (TextView) itemView.findViewById(R.id.countryName);
countryText.setText(currentCountry.getCountry());
TextView yearText = (TextView) itemView.findViewById(R.id.year);
yearText.setText("" + currentCountry.getYear());
TextView continentText = (TextView) itemView.findViewById(R.id.continent);
continentText.setText(currentCountry.getContinent());
return itemView;
}
}
}
I have a listView with icon on the left, a title, and a description .
My question is how do I make it so when a user clicks on 1 of the list items and opens an individual activity that corresponds to that list item. ????
I think you need some modification in your class. There can be several way but I think this one will fine for you.
Change your MyListAdapter to below code.
public MyListAdapter(Context context, List<Countries> country_list, ListView list_view) {
super(MainActivity.this, R.layout.item_view, myCountries);
if (list_view != null) {
list_view.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// YOU CAN START YOUR ACTIVITY HERE.
Intent my_activity_intent = new Intent(context, my_activity.class);
startActivity(my_activity_intent);
}
});
}
}
Change
private void populateListView() {
ArrayAdapter<Countries> adapter = new MyListAdapter(this, myCountries, list);
ListView list = (ListView) findViewById(R.id.countryList);
list.setAdapter(adapter);
}
you can create "setOnItemClickListener" in your main activity also. Only change will be while creating activity "Intent my_activity_intent = new Intent(MainActivity.this, my_activity.class);" need to do for activity intent.
If you have any doubt you can ask. Its all about basics and your programming style. Try to learn such things. :)
my solution is only applicable if you are having limited number of list items.
list_view.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
switch(arg2)
{
case 0:
startActivity(new Intent(context,Activity0.class));
break;
case 1:
startActivity(new Intent(context,Activity1.class));
break;
//Implement cases for all list items
}
}
});
And if you are having more number items then another possible solution is to pass all the data of selected item i.e image,text,description and display it in next activity.
You can ask if you have any further problems :)