I have a problem. I started a few weeks ago learning Android. I am trying to create an adapter for a list. But the lists doesn't show up AT ALL. Any ideas why? The items are objects type Verb. Here is my code:
///my main activity///
public class Verbs extends Activity {
private ListView listViewVerbs;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verbs);
//instantiate Verb
Verb[] VerbData=new Verb[3];
VerbData[0] = new Verb("machen","mache","machen","mache","machen","mache","machen");
VerbData[1] = new Verb("machen","mache","machen","mache","machen","mache","machen");
VerbData[2] = new Verb("machen","mache","machen","mache","machen","mache","machen");
//pass data to adapter
VerbAdapter adapter = new VerbAdapter(this,R.layout.row_verbs,VerbData);
listViewVerbs = (ListView)findViewById(R.id.list);
listViewVerbs.setAdapter(adapter);
listViewVerbs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String wasClicked = view.findViewById(R.id.nameVerb).toString();
Toast.makeText(Verbs.this,
"You clicked: " + wasClicked, Toast.LENGTH_LONG)
.show();
}
});
}
}
//class for an item of the list
public class Verb {
public String verbname;
public String fpersg;
public String fperspl;
public String sperssg;
public String sperspl;
public String tperssg;
public String tperspl;
//constructor
public Verb(String s, String s1, String s2, String s3, String s4, String s5,String s6){
this.verbname = s;
this.fpersg = s1;
this.fperspl = s2;
this.sperssg = s3;
this.sperspl = s4;
this.tperssg = s5;
this.tperspl = s6;
}
//setters
public void setVbName(String vbName){
this.verbname = vbName;
}
public void setFpersg(String fpersg){
this.fpersg = fpersg;
}
public void setFperpl(String fperpl){
this.fperspl = fperpl;
}
public void setSpersg(String spersg){
this.sperssg = spersg;
}
public void setSperspl(String sperpl){
this.sperspl = sperpl;
}
public void setTpersg(String tpersg){
this.tperssg = tpersg;
}
public void setTperpl(String tperpl){
this.tperspl = tperpl;
}
//getters
public String getVerbname(){
return this.verbname;
}
public String getFpersg(){
return this.fpersg;
}
public String getFperpl(){
return this.fperspl;
}
public String getSpersg(){
return this.sperssg;
}
public String getSperpl(){
return this.sperspl;
}
public String getTpersg(){
return this.tperssg;
}
public String getTperspl(){
return this.tperspl;
}
}
//the adapter
public class VerbAdapter extends ArrayAdapter<Verb>{
Context mContext;
int layoutResourceId;
Verb data[] = null;
public VerbAdapter(Context mContext, int layoutResourceId, Verb[] data){
super(mContext, layoutResourceId, data);
this.mContext = mContext;
this.layoutResourceId =layoutResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if (convertView == null){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId,parent, false);
}
TextView textView0 = (TextView) convertView.findViewById(R.id.nameVerb);
TextView textView1 = (TextView) convertView.findViewById(R.id.firstpersonsg);
TextView textView2 = (TextView) convertView.findViewById(R.id.firstpersonpl);
TextView textView3 = (TextView) convertView.findViewById(R.id.secondpersonsg);
TextView textView4 = (TextView) convertView.findViewById(R.id.secondpersonpl);
TextView textView5 = (TextView) convertView.findViewById(R.id.thirdpersonsg);
TextView textView6 = (TextView) convertView.findViewById(R.id.thirdpersonpl);
Verb verb = data[position];
textView0.setText(verb.verbname);
textView1.setText(verb.fpersg);
textView2.setText(verb.fperspl);
textView3.setText(verb.sperssg);
textView4.setText(verb.sperspl);
textView5.setText(verb.tperssg);
textView6.setText(verb.tperspl);
return convertView;
}
}
------and two XML files named activity_verbs where the list is declared and row_verbs where the layout of each item is declared-----
row_verbs.xml ------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/nameVerb"
android:text="#string/nameVerb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#7663d5"
android:textColor="#f8f8f8"
android:padding="10dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="0dp"
android:textStyle="bold" />
<TextView
android:id="#+id/firstpersonsg"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:text="#string/firstsg"
android:layout_below="#+id/nameVerb"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#cacaca"
android:textColor="#7663d5" />
<TextView
android:id="#+id/firstpersonpl"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:text="#string/firstpl"
android:padding="5dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="2dp"
android:background="#FFCACACA"
android:textColor="#7663d5"
android:layout_below="#+id/nameVerb"
android:layout_toRightOf="#+id/firstpersonsg"/>
<TextView
android:id="#+id/secondpersonsg"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:text="#string/secondsg"
android:layout_below="#+id/firstpersonsg"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#FFCACACA"
android:textColor="#7663d5" />
<TextView
android:id="#+id/secondpersonpl"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:text="#string/secondpl"
android:padding="5dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="2dp"
android:background="#FFCACACA"
android:textColor="#7663d5"
android:layout_below="#+id/firstpersonpl"
android:layout_toRightOf="#+id/secondpersonsg"/>
<TextView
android:id="#+id/thirdpersonsg"
android:layout_width="182dp"
android:layout_height="wrap_content"
android:text="#string/thirdsg"
android:layout_below="#+id/secondpersonsg"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"
android:padding="5dp"
android:background="#FFCACACA"
android:textColor="#7663d5" />
<TextView
android:id="#+id/thirdpersonpl"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:text="#string/thirdpl"
android:padding="5dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="2dp"
android:background="#FFCACACA"
android:textColor="#7663d5"
android:layout_below="#+id/secondpersonpl"
android:layout_toRightOf="#+id/thirdpersonsg"/>
</RelativeLayout>
and the other one activity_verbs.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="${relativePackage}.${activityClass}"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textSize="20sp"
android:padding="10dp"
android:background="#7663d5"
android:textColor="#f8f8f8"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lessonId"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#292929"
android:textColor="#f0f0f0"
android:padding="10dp"/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/lessonId"/>
</RelativeLayout>
I copied your code with only one change:
I removed
tools:context="${relativePackage}.${activityClass}"
from activity_verbs and it works like a charm for me:
I uploaded my test-project with your code to DropBox, feel free to download it:
https://www.dropbox.com/s/8fcdab3rmx8zb57/ElaPinkSO.zip?dl=0
P.S. Very well structured question, good job!
Related
I am creating a weather forecast aplication. For this I want to use RecyclerView to show items. The problem is that my RecyclerView is showing only one item instead of all. I am using the OpenWeatherMap API forecast.
This is my layout:
<LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/weather_background2"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/txt_close_weather"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="end"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:background="#drawable/circle"
android:gravity="center"
android:text="X"
android:textColor="#color/blackTransparent"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"
android:orientation="vertical">
<TextView
android:id="#+id/city_country_weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="0dp"
android:text="KOTA"
android:textColor="#color/blackTransparent"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="2dp"
android:text="Today"
android:textColor="#color/blackTransparent"
android:textSize="16dp" />
<TextView
android:id="#+id/current_date_weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="4dp"
android:textColor="#color/blackTransparent"
android:textSize="16dp" />
<ImageView
android:id="#+id/weather_icon"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_gravity="center|center_horizontal"
android:layout_marginTop="8dp"
android:contentDescription="#string/app_name"
android:src="#drawable/img_02d" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:weightSum="3">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/tv_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hummidity"
android:textColor="#color/blackTransparent"
android:textSize="14dp"
android:textStyle="bold" />
<TextView
android:id="#+id/wind_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="#string/app_name"
android:textColor="#color/blackTransparent"
android:textSize="14dp" />
<TextView
android:id="#+id/temperature_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="#string/app_name"
android:textColor="#color/blackTransparent"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:gravity="center_horizontal"
android:background="#color/whiteTr"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2.5"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/weather_daily_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="horizontal"
android:scrollbars="none" />
</LinearLayout>
</LinearLayout>
This my code in activity :
public class DialogWeather extends android.app.DialogFragment {
public static final int WIDTH = 60;
public static final int HEIGHT = 80;
public static final String DATE_FORMAT_WITHOUT_TIME = "dd/MM";
private static final String ICON_PREFIX = "img_";
private static final String API_KEY = "2fc56d498a3b4d87ba298c232e65e6b0";
private static final String UNITS = "metric";
final String q = "Jakarta";
PopupWindow myPopupWindow;
Dialog myDialog;
DialogWeather dialogWeather;
private TextView txtCloseWeather, txtCityCountry,
txtCurrentDate, tvDescription, tvWindResult, tvTemperatureResult;
private ImageView weatherIcon;
private RecyclerView mRecyclerViewWeather;
DialogWeatherAdapter dialogWeatherAdapter;
private ArrayList<Example2> weathers = new ArrayList<>();
Example2 example2List;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_dialog_weather,
container, false);
getDialog().getWindow().setBackgroundDrawable(new
ColorDrawable(Color.TRANSPARENT));
tvDescription = rootView.findViewById(R.id.tv_description);
tvWindResult = rootView.findViewById(R.id.wind_result);
tvTemperatureResult = rootView.findViewById(R.id.temperature_result);
weatherIcon = rootView.findViewById(R.id.weather_icon);
txtCityCountry = rootView.findViewById(R.id.city_country_weather);
txtCityCountry.setTypeface(Typeface.DEFAULT_BOLD);
txtCurrentDate = rootView.findViewById(R.id.current_date_weather);
txtCloseWeather = rootView.findViewById(R.id.txt_close_weather);
txtCloseWeather.setTypeface(Typeface.DEFAULT_BOLD);
Fragment fragment = this;
txtCloseWeather.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Button Close",
Toast.LENGTH_LONG).show();
getActivity().getFragmentManager().beginTransaction()
.remove(fragment).commit();
}
});
mRecyclerViewWeather = rootView.findViewById(R.id.weather_daily_list);
LinearLayoutManager layoutManager = new
LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
mRecyclerViewWeather.setLayoutManager(layoutManager);
mRecyclerViewWeather.setHasFixedSize(true);
dialogWeatherAdapter = new DialogWeatherAdapter(weathers);
mRecyclerViewWeather.setAdapter(dialogWeatherAdapter);
loadWeathers(q, API_KEY, UNITS);
return rootView;
}
private void loadWeathers(String q, String apiKey, String units) {
ApiServicesWeather weather = InitRetrofitWeather.getServicesWeather();
Call<Example2> exampleCall = weather.getDetailWeather(q, apiKey, units);
exampleCall.enqueue(new Callback<Example2>() {
#Override
public void onResponse(Call<Example2> call, Response<Example2>
response) {
if (response.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Success",
Toast.LENGTH_LONG).show();
example2List = response.body();
weathers.addAll(Collections.singleton(example2List));
loadSetView();
dialogWeatherAdapter.updateList(weathers);
dialogWeatherAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<Example2> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Gagal " +
t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private void loadSetView() {
txtCityCountry.setText(weathers.get(getId()).getCity().getName());
txtCurrentDate.setText(Util.formatDate(weathers
.get(getId()).getList().get(getId()).getDtTxt(), "EEE MMM dd, yyyy"));
weatherIcon.setImageResource(Util
.getDrawableResourceIdByName(getApplicationContext(),ICON_PREFIX + weathers
.get(getId()).getList().get(getId()).getWeather().get(getId()).getIcon()));
tvDescription.setText(weathers.get(getId()).getList().get(getId())
.getWeather().get(getId()).getDescription());
tvWindResult.setText("Wind : " +
weathers.get(getId()).getList().get(getId()).getWind().getSpeed() + " m/s");
double mTemperature = (double)
weathers.get(getId()).getList().get(getId()).getMain().getTemp();
tvTemperatureResult.setText(String.valueOf(weathers
.get(getId()).getList().get(ge
tId()).getMain().getTemp()) + " °C");
}
#Override
public void onResume() {
super.onResume();
ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes();
params.width = 700;
params.height = 1100;
getDialog().getWindow().setAttributes((WindowManager.LayoutParams)
params);
}
this My Adapter :
public class DialogWeatherAdapter extends
RecyclerView.Adapter<DialogWeatherAdapter.DialogViewHolder> {
ArrayList<Example2> data;
Context context;
Activity c;
public DialogWeatherAdapter(ArrayList<Example2> data, Context context,
Activity c) {
this.data = data;
this.context = context;
this.c = c;
}
public DialogWeatherAdapter(ArrayList<Example2> weathers) {
this.data = weathers;
}
#Override
public DialogViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
LayoutInflater layoutInflater = (LayoutInflater)
parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.item_weathers, parent,
false);
return new DialogViewHolder(view);
}
#Override
public void onBindViewHolder(DialogViewHolder holder, int position) {
if (holder instanceof DialogViewHolder) {
final DialogViewHolder viewHolder = (DialogViewHolder) holder;
if (data != null) {
for (int i = 0; i < data.size(); i++) {
viewHolder.tvCurrentDateItem.setText(Util.formatDate(data
.get(position).getList()
.get(position).getDtTxt(), "dd/MM"));
viewHolder.ivIconItem.setImageResource(Util
.getDrawableResourceIdByName(getApplicationContext(), ICON_PREFIX + data
.get(getId()).getList().get(getId()).getWeather().get(getId()).getIcon()));
viewHolder.tvDescriptionItem.setText(data.get(position)
.getList().get(position).getWeather().get(position).getDescription());
viewHolder.tvTemperatureItem.setText(String.valueOf(weathers
.get(getId()).getList
().get(getId()).getMain().getTemp()) + " °C");
}
}
}
}
#Override
public int getItemCount() {
return data.size();
}
public void updateList(ArrayList<Example2> weathers) {
this.data = weathers;
}
public class DialogViewHolder extends RecyclerView.ViewHolder {
TextView tvCurrentDateItem, tvDescriptionItem, tvTemperatureItem;
ImageView ivIconItem;
public DialogViewHolder(View itemView) {
super(itemView);
tvCurrentDateItem = itemView.findViewById(R.id.current_date_weather_item);
tvDescriptionItem = itemView.findViewById(R.id.description_item);
tvTemperatureItem = itemView.findViewById(R.id.temperature_item);
ivIconItem = itemView.findViewById(R.id.icon_weather_item);
}
}
}
enter image description here
The reason for this is -
The Item file (R.layout.item_weathers) has height match parent. Change it to wrap_content as shown -
<LinearLayout 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:layout_width="match_parent"
android:layout_height="wrap_content"/>
and it will show all the items.
The following is my layout for a custom row in a listview.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/layoutTop"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Well Hello Motherfucker"
android:id="#+id/geventProfileName"
android:textSize="20sp"
android:paddingLeft="50dp"/>
</RelativeLayout>
<FrameLayout
android:id="#+id/layoutBottom"
android:layout_width="match_parent"
android:layout_height="300dp"
android:alpha="1"
android:layout_below="#+id/layoutTop"
android:layout_alignParentStart="true">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/no_picture"
android:id="#+id/geventEventPhoto"
android:layout_gravity="top|left"
android:alpha="1"/>
<TextView
android:layout_width="350dp"
android:layout_height="wrap_content"
android:text="asfda"
android:layout_gravity="center|left"
android:textSize="35sp"
android:textColor="#FFF"
android:textAllCaps="true"
android:id="#+id/geventTitle"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read More"
android:textColor="#color/black"
android:id="#+id/geventReadMoreButton"
android:background="#drawable/readtab"
android:paddingTop="10dp"
android:paddingLeft="20dp"
android:layout_gravity="bottom|right"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="20dp"
android:id="#+id/geventDescription"
android:text=""
android:textColor="#color/black"
android:layout_gravity="top|left"/>
<TextView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/geventDetails"
android:text=""
android:textSize="20sp"
android:textColor="#FFF"
android:layout_gravity="bottom|left"
/>
</FrameLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/layoutBottom"
android:orientation="horizontal"
android:background="#9E9E9E"
android:padding="5dp"
android:layout_marginTop="5dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="100"
android:id="#+id/numberOfLikesGEvent"
android:textColor="#color/black"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/numberOfLikesGEvent"
android:id="#+id/likeTextViewGEvent"
android:layout_marginLeft="10dp"
android:textColor="#color/black"
android:text="Like"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/dislikeTextViewGEvent"
android:layout_marginRight="10dp"
android:id="#+id/numberOfDislikesGEvent"
android:textColor="#color/black"
android:text="200"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dislikeTextViewGEvent"
android:text="Dislike"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="0dp"
android:textColor="#color/black"/>
</RelativeLayout>
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/profile_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/photo"
app:civ_border_width="2dp"
app:civ_border_color="#FFF"/>
And this is my CustomAdapter
public class CustomAdapter extends ArrayAdapter<GEvent> {
boolean hasLiked;
boolean hasDisliked;
FirebaseUser fbUser;
ArrayList<String> uids;
ArrayList<String> dUids;
GEvent currentEvent;
private TextView likeTextView;
private TextView numberOfLikes;
private TextView dislikeTextView;
private TextView numberOfDislikes;
private TextView readMoreButton;
private TextView eventDetails;
private TextView titleGevent;
private ImageView eventPhoto;
private TextView profileName;
private TextView descriptionGevent;
private String description;
private String titleForGEvent;
private String detailsGEvent;
private boolean hasLoaded=true;
private de.hdodenhof.circleimageview.CircleImageView circleImageView;
private Context mContext;
private boolean wantsToReadMore=false;
String profilePhotoLink;
PopupWindow pw;
public CustomAdapter(Context context, GEvent[] resource) {
super(context, R.layout.custom_row , resource);
this.mContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
final View customView = inflater.inflate(R.layout.example,parent,false);
final GEvent gEvent = getItem(position);
currentEvent = gEvent;
firebaseAuth = FirebaseAuth.getInstance();
uid = firebaseAuth.getCurrentUser().getUid();
titleGevent = (TextView) customView.findViewById(R.id.geventTitle);
descriptionGevent = (TextView) customView.findViewById(R.id.geventDescription);
profileName = (TextView) customView.findViewById(R.id.geventProfileName);
likeTextView = (TextView) customView.findViewById(R.id.likeTextViewGEvent);
numberOfLikes = (TextView) customView.findViewById(R.id.numberOfLikesGEvent);
numberOfDislikes =(TextView) customView.findViewById(R.id.numberOfDislikesGEvent);
dislikeTextView = (TextView) customView.findViewById(R.id.dislikeTextViewGEvent);
readMoreButton = (TextView) customView.findViewById(R.id.geventReadMoreButton);
eventPhoto = (ImageView) customView.findViewById(R.id.geventEventPhoto);
eventDetails = (TextView)customView.findViewById(R.id.geventDetails);
circleImageView = (CircleImageView) customView.findViewById(R.id.profile_image);
description = gEvent.getDescription();
detailsGEvent = gEvent.getgEventDate()+"\n"+gEvent.getgEventTime()+"\n"+gEvent.getVenue1()+"\n"+gEvent.getVenue2()+"\n"+gEvent.getContactEmail()+"\n"+gEvent.getContactPhoneNumber();
titleForGEvent = gEvent.getTitle();
if(gEvent.isHasPhoto()){
hasLoaded= false;
readMoreButton.setText("Loading");
}
readMoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(hasLoaded) {
Log.i("CA","Entered hasLoaded Function");
readMoreFunction();
}
else
Toast.makeText(mContext,"Loading....",Toast.LENGTH_LONG).show();
}
});
titleGevent.setText(gEvent.getTitle());
String uuid = gEvent.getUuid();
Boolean hasPhoto = gEvent.isHasPhoto();
profileName.setText(gEvent.getProfileUsername());
if(hasPhoto) {
final long ONE_MEGABYTE = 1024 * 1024 * 5;
pathRef.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
Bitmap picturel = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
ImageView imageView = (ImageView) customView.findViewById(R.id.geventEventPhoto);
Drawable d = new BitmapDrawable(mContext.getResources(),picturel);
imageView.setBackground(d);
Log.i("CA","Entered hasRetrieved Photo and update hasLoaded");
readMoreButton.setText("Read More");
hasLoaded=true;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Log.i("Error","Couldn't Download");
}
});
}
return customView;
}
public void readMoreFunction(){
Log.i("CA","Entered readMoreFunction Function");
if(wantsToReadMore){ //wants to read less now
Log.i("CA","Entered Read Less Function");
eventPhoto.setAlpha(1f);
descriptionGevent.setText("");
eventDetails.setText("");
readMoreButton.setText("Read More");
titleGevent.setText(titleForGEvent);
wantsToReadMore=false;
}
else{ //Wants to read more
Log.i("CA","Entered Read More Function");
eventPhoto.setAlpha(0.5f);
descriptionGevent.setText(description);
eventDetails.setText(detailsGEvent);
titleGevent.setText("");
readMoreButton.setText("Read Less");
wantsToReadMore=true;
}
So my problem is that whenever I am calling this CustomAdapter, when only one list Item is there it works perfectly, however whenever there are multiple list items, the adapter starts behaving strangely. For instance, whenever there are 2 items, If i press the " Read More " button for the first item, it triggers for the second item, even though in the logs it shows that data on which it is working is the first item itself.
If there are more than 2 items , then the above pattern is observed , i.e, whenever I click the "Read More" button of a given item, it triggers for the next item in the listview. Sometimes it is just stuck on "Loading " even after the image has loaded or the "Read More" button doesn't even respond.
I have been banging my head for the past two days , looking for the bug. Hope you guys can help me.Thanks in Advance.
PS:- The "Load More" Button is out of place, excuse me for that.
Inside GEvent class create a boolean field,
class GEvent {
private boolean readMoreClicked;
public boolean isReadMoreClicked(){
return readMoreClicked;
}
public void setReadMoreClicked(boolean readMoreClicked){
this.readMoreClicked = readMoreClicked;
}
}
Inside getView,
#Override
public View getView(int position, View convertView, ViewGroup parent) {
....
if(gEvent.isReadMoreClicked()) {
Log.i("CA","Entered More Less Function");
...
} else {
Log.i("CA","Entered Less More Function");
...
}
readMoreButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(hasLoaded) {
Log.i("CA","Entered hasLoaded Function");
// user has clicked Read More. Save the state
gEvent.setReadMoreClicked(!gEvent.isReadMoreClicked());
notifyDataSetChanged();
} else {
Toast.makeText(mContext,"Loading....",Toast.LENGTH_LONG).show();
}
}
});
...
}
It may need some editing. But I hope you get the idea. :)
For some reason tapping a row in my list view doesn't seem to work even if I have the correct listener code. There are only textviews in the template of the lists. I know there's been discussion about assigning a listener when there is a button in the template of a list view. see here.
Here is my code:
ScheduleActivity:
public class ScheduleActivity extends AppCompatActivity {
private String url;
JSONObject data = null;
Toolbar toolbar;
Intent intent;
String userId;
int eventId;
ListView scheduleListView;
ScheduleAdapter scheduleAdapter;
ArrayList<Schedule> scheduleList = new ArrayList<>();
DBManager dbManager = new DBManager(ScheduleActivity.this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.schedule_layout);
Log.d("Test", ">>>ScheduleActivity<<<");
Bundle extras = getIntent().getExtras();
userId = extras.getString("userId");
eventId = extras.getInt("eventId");
toolbar = (Toolbar) findViewById(R.id.schedule_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Schedules");
scheduleList = dbManager.getSchedules(eventId);
scheduleAdapter = new ScheduleAdapter(ScheduleActivity.this, scheduleList);
scheduleListView = (ListView) findViewById(R.id.scheduleListView);
scheduleListView.setAdapter(scheduleAdapter);
scheduleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.w("Test", scheduleList.get(position).toString());
intent = new Intent(ScheduleActivity.this, UpdateScheduleActivity.class);
intent.putExtra("userId", userId);
intent.putExtra("eventId", eventId);
startActivity(intent);
}
});
scheduleListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Log.w("Test", "Long click works");
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.schedule_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.new_schedule) {
intent = new Intent(ScheduleActivity.this, CreateScheduleActivity.class);
intent.putExtra("eventId", eventId);
startActivity(intent);
}else if(id == R.id.rankings){
Log.d("Test", "Rankings Activity clicked!");
}
return super.onOptionsItemSelected(item);
}
ScheduleAdapter:
public class ScheduleAdapter extends ArrayAdapter<Schedule>{
public ScheduleAdapter(Context context, List<Schedule> schedule) {
super(context, R.layout.schedule_list_row, schedule);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater eventInflater = LayoutInflater.from(getContext());
if (convertView == null) {
convertView = eventInflater.inflate(R.layout.schedule_list_row, parent, false);
}
Schedule singleSchedule = getItem(position);
//TODO implement ViewHolder pattern
TextView club1Code = (TextView) convertView.findViewById(R.id.club1TextView);
TextView club2Code= (TextView) convertView.findViewById(R.id.club2TextView);
TextView club1Score = (TextView) convertView.findViewById(R.id.club1ScoreTextView);
TextView club2Score = (TextView) convertView.findViewById(R.id.club2ScoreTextView);
TextView club1SpiritScore = (TextView) convertView.findViewById(R.id.club1SpiritScoreTextView);
TextView club2SpiritScore = (TextView) convertView.findViewById(R.id.club2SpiritScoreTextView);
TextView time = (TextView) convertView.findViewById(R.id.timeTextView);
TextView day = (TextView) convertView.findViewById(R.id.dayTextView);
club1Code.setText(singleSchedule.getClub1Id());
club2Code.setText(singleSchedule.getClub2Id());
day.setText("Day " + singleSchedule.getDay());
time.setText(singleSchedule.getStartTime() + " - " + singleSchedule.getEndTime());
club1Score.setText(Integer.toString(singleSchedule.getClub1Score()));
club2Score.setText(Integer.toString(singleSchedule.getClub2Score()));
club1SpiritScore.setText(Integer.toString(singleSchedule.getClub1SpiritScore()));
club2SpiritScore.setText(Integer.toString(singleSchedule.getClub2SpiritScore()));
return convertView;
}
}
Activity Layout:
<?xml version="1.0" encoding="utf-8"?>
<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="com.kennanseno.ultimate_scoreboard_app.Activity.ScheduleActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/schedule_toolbar"
android:minHeight="?attr/actionBarSize"
android:background="#2196F3"
android:title="#string/event_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
</android.support.v7.widget.Toolbar>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/scheduleListView"
android:layout_centerHorizontal="true"
android:layout_below="#+id/schedule_toolbar" />
</RelativeLayout>
Row Template:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/club1_name_text"
android:id="#+id/club1TextView"
android:textAlignment="textStart"
android:layout_above="#+id/club1SpiritScoreTextView"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/club2_name_text"
android:id="#+id/club2TextView"
android:layout_gravity="right"
android:textAlignment="textEnd"
android:layout_below="#+id/dayTextView"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/score_divider"
android:id="#+id/score_divider"
android:textSize="50sp"
android:layout_below="#+id/timeTextView"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/club1_score_text"
android:id="#+id/club1ScoreTextView"
android:textSize="50sp"
android:layout_marginEnd="22dp"
android:layout_below="#+id/timeTextView"
android:layout_toStartOf="#+id/score_divider"
android:textAlignment="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/club2_score_text"
android:id="#+id/club2ScoreTextView"
android:textSize="50sp"
android:layout_marginStart="22dp"
android:layout_below="#+id/timeTextView"
android:layout_toEndOf="#+id/score_divider"
android:textAlignment="center" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/start_time_text"
android:id="#+id/timeTextView"
android:textAlignment="center"
android:layout_below="#+id/dayTextView"
android:layout_alignEnd="#+id/club2ScoreTextView"
android:layout_alignStart="#+id/club1ScoreTextView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/club1_spirit_score_text"
android:id="#+id/club1SpiritScoreTextView"
android:textAlignment="textStart"
android:textSize="30sp"
android:layout_alignTop="#+id/club2SpiritScoreTextView"
android:layout_alignStart="#+id/club1TextView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/club2_spirit_score_text"
android:id="#+id/club2SpiritScoreTextView"
android:textAlignment="textEnd"
android:textSize="30sp"
android:layout_below="#+id/club2TextView"
android:layout_alignEnd="#+id/club2TextView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/schedule_day_text"
android:id="#+id/dayTextView"
android:textAlignment="center"
android:layout_alignParentTop="true"
android:layout_alignEnd="#+id/club2ScoreTextView"
android:layout_alignStart="#+id/club1ScoreTextView" />
</RelativeLayout>
In Row Template xml:
android:clickable="true"
causing issue because RelativeLayout is clickable with match_parent height-width.
if you want to get click event for whole row then no need to make parent layout clickable just set setOnItemClickListener to ListView otherwise you need to set onClickListener for RelativeLayout in ScheduleAdapter class.
After googling alot i never found any helpful answer, so i'm posting my issue here. My problem is as follows :
I've a nested fragment (MainActivity calls SettingsFragment and that fragment calls another fragment named as ContactFragment) that uses a listview in it. I'm setting data in adapter but and call adapter.notifyDataSetChanged(); it adds an item with in ListView but show only images not TextViews. I debugged my code line by line each variable has its values but list items are not displaying it. Below is my Code.
ContactsFragment extends Fragment {
public static List<ContactItem> contactList;
private ContactsItemAdapter adapter;
private ListView lvContacts;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_contacts, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
lvContacts = (ListView) getView().findViewById(R.id.lvContacts);
contactList = new ArrayList<ContactItem>();
contactList.add(new ContactItem(R.drawable.ic_action_overflow, "OverFlow", "Testing", SOS.CONTACT_TYPE_SMS));
adapter = new ContactsItemAdapter(getActivity(), R.layout.contact_item, contactList);
lvContacts.setAdapter(adapter);
}
Following is a Click Event for adding an item to the list
private void btnAddOnClick(int type){
contactList.add(new ContactItem(R.drawable.ic_action_call, "ABC", "123", "SMS"));
adapter.notifyDataSetChanged();
}
}
Following is fragment_contacts.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:gravity="center_horizontal"
android:orientation="vertical" >
<ListView
android:id="#+id/lvContacts"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" >
</ListView>
</LinearLayout>
By Calling btnAddOnClick adds item in listview but empty like this
here you can see it shows call icon but not showing text views values. Please tell me what i'm doing wrong.
Here is adapter
public class ContactsItemAdapter extends ArrayAdapter<ContactItem> {
private LayoutInflater mInflater;
public ContactsItemAdapter(Context context, int resource,
List<ContactItem> contactList) {
super(context, resource, contactList);
mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView tvName;
TextView tvValue;
ImageView ivIcon;
ContactItem rowData = ContactsFragment.contactList.get(position);
if (null == convertView) {
convertView = mInflater.inflate(R.layout.contact_item, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
tvName = holder.getName();
tvName.setText(rowData.getName());
tvValue = holder.getValue();
tvValue.setText(rowData.getValue());
ivIcon = holder.getIcon();
ivIcon.setImageResource(rowData.getIcon());
return convertView;
}
public class ViewHolder {
private View mRow;
private TextView tvName = null;
private TextView tvValue = null;
private ImageView ivIcon = null;
public ViewHolder(View row) {
mRow = row;
}
public TextView getName() {
if (null == tvName) {
tvName = (TextView) mRow.findViewById(R.id.tvName);
}
return tvName;
}
public TextView getValue() {
if (null == tvValue) {
tvValue = (TextView) mRow.findViewById(R.id.tvValue);
}
return tvValue;
}
public ImageView getIcon() {
if (null == ivIcon) {
ivIcon = (ImageView) mRow.findViewById(R.id.icon);
}
return ivIcon;
}
}
}
ContactItem Class
public class ContactItem {
private int icon;
private String name;
private String value;
private String contactType;
public ContactItem() {
icon = R.drawable.ic_action_call;
name = "";
value = "";
contactType = "";
}
public ContactItem(int icon, String nameString, String valueString,
String type) {
this.icon = icon;
this.name = nameString;
this.value = valueString;
this.contactType = type;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getContactType() {
return contactType;
}
public void setContactType(String contactType) {
this.contactType = contactType;
}
}
contact_item.xml
<?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="55dp"
android:background="#color/holo_gray_light"
android:gravity="center_vertical" >
<ImageView
android:id="#+id/icon"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:contentDescription="#string/desc_list_item_icon"
/>
<View
android:id="#+id/divider"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_alignParentBottom="true"
android:background="#android:color/darker_gray" />
<ImageView
android:id="#+id/ivCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:src="#drawable/ic_action_cancel" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/divider"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/ivCancel"
android:layout_toRightOf="#+id/icon"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:id="#+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.49"
android:gravity="center_vertical"
android:paddingRight="40dp"
android:ellipsize="end"
android:text="Nauman Zubair"/>
<TextView
android:id="#+id/tvValue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.49"
android:paddingRight="40dp"
android:ellipsize="end"
android:gravity="center_vertical"
android:text="+92 123 1234567"/>
</LinearLayout>
</RelativeLayout>
Your code should work, I think the problem is your contact_item.xml layout. Somehow your design is hiding the text. Use a simpler layout design to see if it shows the text, try getting rid of the LinearLayout:
<?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="55dp"
android:background="#color/holo_gray_light"
android:gravity="center_vertical" >
<ImageView
android:id="#+id/icon"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:contentDescription="#string/desc_list_item_icon" />
<View
android:id="#+id/divider"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_alignParentBottom="true"
android:background="#android:color/darker_gray" />
<ImageView
android:id="#+id/ivCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:src="#drawable/ic_action_cancel" />
<TextView
android:id="#+id/tvName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/ivCancel"
android:layout_toRightOf="#+id/icon"
android:gravity="center_vertical"
android:paddingRight="40dp"
android:ellipsize="end"
android:text="Nauman Zubair"/>
<TextView
android:id="#+id/tvValue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#+id/ivCancel"
android:layout_toRightOf="#+id/icon"
android:paddingRight="40dp"
android:ellipsize="end"
android:gravity="center_vertical"
android:text="+92 123 1234567"/>
</RelativeLayout>
I have a custom list View that contains 7 text views..I have created a custom linear layout for that..And then I'm populating it...What i want to do is set a custom color...When the user clicks on the list item and keep it highlighted till he clicks another item...How will i do that??...
This is the custom layout for listitems...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LLtv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/colors"
android:cacheColorHint="#00000000" >
<TextView
android:id="#+id/TvVLdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:paddingTop="8dp"
android:textColor="#000000"
android:textSize="15dp" />
<TextView
android:id="#+id/TvVLtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/TvVLdate"
android:paddingLeft="8dp"
android:paddingTop="8dp"
android:textColor="#000000"
android:textSize="15dp" />
<TextView
android:id="#+id/TvVLcardno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/TvVLtime"
android:paddingLeft="8dp"
android:paddingTop="8dp"
android:textColor="#000000"
android:textSize="15dp" />
<TextView
android:id="#+id/TvVLsaletext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/TvVLdate"
android:paddingLeft="8dp"
android:paddingTop="8dp"
android:text="Sale transaction:Rs"
android:textColor="#000000"
android:textSize="15dp" />
<TextView
android:id="#+id/TvVLamnt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/TvVLsaletext"
android:layout_toRightOf="#+id/TvVLsaletext"
android:paddingTop="8dp"
android:textColor="#000000"
android:textSize="15dp" />
<TextView
android:id="#+id/TvVLtexttip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/TvVLamnt"
android:layout_toRightOf="#+id/TvVLamnt"
android:paddingLeft="8dp"
android:paddingTop="8dp"
android:text="Tip:Rs"
android:textColor="#000000"
android:textSize="15dp" />
<TextView
android:id="#+id/TvVLtip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/TvVLtexttip"
android:layout_toRightOf="#+id/TvVLtexttip"
android:paddingTop="8dp"
android:textColor="#000000"
android:textSize="15dp" />
</RelativeLayout>
And my list layout..
<?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"
android:background="#E0E0E0"
android:orientation="vertical" >
<include
android:id="#+id/Hvoid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
layout="#layout/header" />
<RelativeLayout
android:id="#+id/RLvoid"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/Hvoid"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="12dp"
android:text="Main Menu"
android:textColor="#000000"
android:textSize="15dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:src="#drawable/ivoid" />
</RelativeLayout>
<View
android:id="#+id/Vvoidtop"
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_below="#+id/RLvoid"
android:background="#android:color/darker_gray" />
<ListView
android:id="#+id/Lvvoid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/Bconfirm"
android:layout_below="#+id/Vvoidtop"
android:background="#E0E0E0"
android:cacheColorHint="#00000000"
android:divider="#android:color/transparent"
android:dividerHeight="20dp" >
</ListView>
<Button
android:id="#+id/Bconfirm"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_above="#+id/Vvoidbot"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/cbconfirm" />
<View
android:id="#+id/Vvoidbot"
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_above="#+id/Tvfooter"
android:background="#android:color/darker_gray" />
<TextView
android:id="#+id/Tvfooter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:text="© India Transact Services Ltd."
android:textColor="#000000"
android:textSize="15dp" />
</RelativeLayout>
And the drawable colors xml file...
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selected Item -->
<item android:drawable="#android:color/darker_gray" android:state_selected="true"/>
<item android:drawable="#android:color/darker_gray" android:state_focused="true"/>
<!-- Default Item -->
<item android:drawable="#android:color/white" />
</selector>
And my code....
public class Void extends Activity {
ListView lmenu;
View Vlistselector;
String s;
View layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.voidlist);
Menu Menu_data[] = new Menu[] {
new Menu("29/09/2012", "05:40", "2234 xxxx xxxx 1990", "100",
"10"),
new Menu("09/12/2012", "00:34", "2234 xxxx xxxx 1990", "99",
"12"),
new Menu("29/09/2012", "12:20", "2234 xxxx xxxx 1990", "111",
"0"),
new Menu("31/01/2012", "13:40", "2234 xxxx xxxx 1990", "105",
"19"),
new Menu("13/10/2012", "01:40", "2234 xxxx xxxx 1990", "203",
"1"),
new Menu("23/11/2012", "07:40", "2234 xxxx xxxx 1990", "44",
"5") };
MenuAdapter adapter = new MenuAdapter(this, R.layout.voidlisttext,
Menu_data);
lmenu = (ListView) findViewById(R.id.Lvvoid);
lmenu.setAdapter(adapter);
// lmenu.setSelector(R.drawable.listcolorselector);
lmenu.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> ada, View v, int position,
long id) {
// TODO Auto-generated method stub
/*
* v.setSelected(true);
*/
v.setBackgroundColor(Color.parseColor("#FCD5B5"));
if (!(Vlistselector == null) && Vlistselector != v)
Vlistselector.setBackgroundColor(Color
.parseColor("#EEEEEE"));
Vlistselector = v;
Toast.makeText(getApplicationContext(),
String.valueOf(position + 1), Toast.LENGTH_LONG).show();
}
});
findViewById(R.id.BLogout).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
public class Menu {
public String date;
public String time;
public String cardno;
public String amnt;
public String tip;
public Menu() {
super();
}
public Menu(String date, String time, String cardno, String amnt,
String tip) {
super();
this.date = date;
this.time = time;
this.cardno = cardno;
this.amnt = amnt;
this.tip = tip;
}
}
public class MenuAdapter extends ArrayAdapter<Menu> {
Context context;
int layoutResourceId;
Menu data[] = null;
public MenuAdapter(Context context, int layoutResourceId, Menu[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MenuHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new MenuHolder();
holder.date = (TextView) row.findViewById(R.id.TvVLdate);
holder.time = (TextView) row.findViewById(R.id.TvVLtime);
holder.cardno = (TextView) row.findViewById(R.id.TvVLcardno);
holder.amnt = (TextView) row.findViewById(R.id.TvVLamnt);
holder.tip = (TextView) row.findViewById(R.id.TvVLtip);
row.setTag(holder);
} else {
holder = (MenuHolder) row.getTag();
}
Menu Menu = data[position];
holder.date.setText(Menu.date);
holder.time.setText(Menu.time);
holder.cardno.setText(Menu.cardno);
holder.amnt.setText(Menu.amnt);
holder.tip.setText(Menu.tip);
return row;
}
public class MenuHolder {
TextView date;
TextView time;
TextView cardno;
TextView amnt;
TextView tip;
}
}
}
What i want is instead of the color darker gray set a new custom color....
Have i done it the right way or is there any other way to do it?????
View listColor;//declare this at the top
Do it onclick of listviewitem
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
if(listColor!=null){
listColor.setBackgroundColor(Color.BLACK);
listColor=view;
}else{
listColor=view;
}
listColor.setBackgroundColor(Color.BLUE); //intead of blue you can change it to something you want like darkergray
//show toast on the clicked item
String selectedValue = (String) getListAdapter().getItem(position);
Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
}
For this scenario you should use setBackground() at runtime instead of relying on selector.