Changing layout of an ListView item when pressing it - android

when writing an app for me and my roommates to calculate our food-payments I got stuck on such problem:
when adding new payment, you:
1) select name from RadioGroup
2) give value
3) give description (or leave default 'opis')
then after pressing button "DODAJ" it shows as new item in ListView with certain format. Now the problem begins:
I want to make it so when I click on a Item in this list, i will slightly change format of this certain item (in NowaWplata class I got extra time to be displayed) which I got in another .xml layout file, and when pressing it again it should go back to 'normal' layout.
I tried 2 different approaches, one is commented in the bottom of my code (I tried it from this topic Change layout of selected list item in Android), and the other one is in overriden onItemClick method - neither of them worked
compiler says that the error is :
java.lang.NullPointerException
at com.example.lukasz.dom.MainActivity.onItemClick
in this line of code:
relativeLayoutInflate.addView(child);
in main activity (onClick only for 'lukasz', same for 'marcelina' and 'karolina'):
#Override
public void onClick(View v) {
if (v == addNewPaymentButton) {
//checking which button from RadioGroup is checked and adding new payment to certain person
int checkedRadioButtonId = members.getCheckedRadioButtonId();
switch (checkedRadioButtonId) {
//if Lukasz button is pressed, do:
case R.id.lukaszRadioButton:
if (lukaszRadioButton.isChecked()) {
//add value from addNewPaymentButton to tempLukasz
try {
tempLukasz += valueOf(newPaymentValue.getText().toString());
} catch (NumberFormatException e) {
}
//seting new value to money spent by lukasz
String sumaLukasza = getString(R.string.money_spent_by_lukasz);
sumaLukasza = String.format(sumaLukasza, tempLukasz);
moneySpentByLukasz.setText(sumaLukasza);
//adding new payment to list of all payments with flag 'int == 1' to set color to RED
NowaWplata newPayment = new NowaWplata(lukaszRadioButton.getText().toString(), newPaymentValue.getText().toString(), descriptionOfNewPayment.getText().toString(), 1);
NowaWplata.setWplaty(newPayment);
listView.setAdapter(new NewPaymentAdapter(this, R.layout.new_list_item_layout, NowaWplata.getWplaty()));
}
break;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView hourDate = (TextView) view.findViewById(R.id.hoursDateFieldInSelectedListItem);
TextView dayDate = (TextView) view.findViewById(R.id.daysDateFieldInSelectedListItem);
TextView name = (TextView) view.findViewById(R.id.nameFieldInSelectedListItem);
TextView value = (TextView) view.findViewById(R.id.valueFieldInSelectedListItem);
TextView description = (TextView) view.findViewById(R.id.descriptionFieldInSelectedListItem);
RelativeLayout relativeLayoutInflate = (RelativeLayout) view.findViewById(R.id.layoutOfSelectedListItem);
NowaWplata newPayment = (NowaWplata) listView.getItemAtPosition(position);
View child = getLayoutInflater().inflate(R.layout.selected_list_item, null);
relativeLayoutInflate.addView(child);
hourDate.setText("[" + newPayment.getHourDate() + "]");
dayDate.setText(newPayment.getDayDate());
name.setText(newPayment.getOsoba());
value.setText(newPayment.getWplata() + "zł");
description.setText(newPayment.getOpis());
}
}
//custom adapter class
class NewPaymentAdapter extends ArrayAdapter<NowaWplata> {
public LayoutInflater layoutInflater;
//custom adapter's constructor with values
public NewPaymentAdapter(Context context, int textViewResourceId, List<NowaWplata> wplaty) {
super(context, textViewResourceId, wplaty);
layoutInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
NowaWplata newPayment = getItem(position);
Holder holder = null;
// private int position;
// public void selectedItem(int position)
// {
// this.position = position;
// }
//if there are no items in list - add 1st item
if (view == null) {
view = layoutInflater.inflate(R.layout.new_list_item_layout, null);
TextView name = (TextView) view.findViewById(R.id.osobaWplata);
TextView value = (TextView) view.findViewById(R.id.kwotaWplata);
TextView description = (TextView) view.findViewById(R.id.opisWplata);
holder = new Holder(name, value, description);
view.setTag(holder);
}
// if there are items in list get holder tag
else {
holder = (Holder) view.getTag();
}
//setting text to a new list item
holder.osoba.setText("[" + newPayment.getDate() + "] " + newPayment.getOsoba());
holder.kwota.setText(newPayment.getWplata() + "zł");
holder.opis.setText(newPayment.getOpis());
//setting different color to Lukasz/Marcelina/Karolina text
if (newPayment.getFlag() == 1) {
holder.osoba.setTextColor(Color.RED);
} else if (newPayment.getFlag() == 2) {
holder.osoba.setTextColor(Color.BLUE);
} else if (newPayment.getFlag() == 3) {
holder.osoba.setTextColor(Color.GREEN);
}
//setting color to payment's value
holder.kwota.setTextColor(Color.BLACK);
// if (this.position == position) {
// View view2;
// view2 = layoutInflater.inflate(R.layout.selected_list_item, null);
//
// TextView hourDate = (TextView) view2.findViewById(R.id.hoursDateFieldInSelectedListItem);
// TextView dayDate = (TextView) view2.findViewById(R.id.daysDateFieldInSelectedListItem);
// TextView name = (TextView) view2.findViewById(R.id.nameFieldInSelectedListItem);
// TextView value = (TextView) view2.findViewById(R.id.valueFieldInSelectedListItem);
// TextView description = (TextView) view2.findViewById(R.id.descriptionFieldInSelectedListItem);
//
// hourDate.setText("[" + newPayment.getHourDate() + "]");
// dayDate.setText(newPayment.getDayDate());
// name.setText(newPayment.getOsoba());
// value.setText(newPayment.getWplata() + "zł");
// description.setText(newPayment.getOpis());
//
// return view2;
// }
return view;
}
}
this is the main XML part with the ListView
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#android:id/list"
android:layout_below="#+id/tableLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/newPaymentValue"
android:layout_alignRight="#+id/tableLayout"
android:layout_alignEnd="#+id/tableLayout"
android:choiceMode="none"
android:clickable="false"
android:padding="20dp"
android:transcriptMode="disabled"/>
this is the xml of a new item in list
<?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="wrap_content"
android:id="#+id/layoutOfSelectedListItem">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/hoursDateFieldInSelectedListItem"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="18dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/daysDateFieldInSelectedListItem"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="18dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/nameFieldInSelectedListItem"
android:layout_below="#+id/hoursDateFieldInSelectedListItem"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/daysDateFieldInSelectedListItem"
android:layout_toStartOf="#+id/daysDateFieldInSelectedListItem"
android:textSize="18dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/valueFieldInSelectedListItem"
android:layout_below="#+id/daysDateFieldInSelectedListItem"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textSize="22dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/descriptionFieldInSelectedListItem"
android:layout_below="#+id/nameFieldInSelectedListItem"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:textSize="14dp" />

I have done that by adding extra layout.
ListItem:
<--Your listItem view--!>
<RelativeLayout>
<--Your extra View--!>
<LinearLayout
android:tag="0"
android:visibility="gone">
</LinearLayout>
</RelativeLayout>
In your OnItemClickListener set the extra layout to visible and also set the tag accordingly to save the state of the extra view.

Related

How to change an ImageView, that is part of a list item?

I have a ListView that shows list items (duh). When you click on a list item, another Activity opens. Part of the list item layout is a grey star, an ImageView. When you click on this ImageView, I don't want to open another Activity, but I want to change the color of the star to green (= mark the item as favourite) or back (= mark it as not favourite). I managed to do that with an OnClickListener, loading another ImageView on Click, and refreshing the adapter. But for the ImageView to change, after clicking it I need to leave the Activity and enter again. It doesn't refresh instantly. Why, and how can I change that? I've tried lots of different versions, so far nothing works. My ListViewAdapter extends BaseAdapter. Thank you!
public class ListViewAdapterKeysAToZ extends BaseAdapter {
private ArrayList<KeyTagIntern> keyTags;
private ObservableArrayList<KeyTagIntern> list;
private Context context;
TextView name;
TextView place;
ImageView star, favoriteStar;
public ListViewAdapterKeysAToZ(Context context, ObservableArrayList<KeyTagIntern> list)
{
this.context = context;
this.list = list;
keyTags = new ArrayList<>();
for (KeyTagIntern keytag : list) {
keyTags.add(keytag);
}
//(....)
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
KeyTagIntern key = (KeyTagIntern) getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_keys, parent, false);
}
name = (TextView) convertView.findViewById(R.id.text_keylist_item);
name.setText(key.getName());
place = (TextView) convertView.findViewById(R.id.text_keylist_item_place);
place.setText(key.getPlace());
star = (ImageView) convertView.findViewById(R.id.right_icon_keylist_item);
favoriteStar = (ImageView) convertView.findViewById(R.id.right_icon_keylist_item_favorite);
if (key.isFavorite())
{
star.setVisibility(View.INVISIBLE);
favoriteStar.setVisibility(View.VISIBLE)
favoriteStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// This makes key.isFavourite() = false for the next time
Paper.book().delete(FAVORIT + String.valueOf(key.getKeyTagID()));
//Since notifyDataSetChanged() didn't work for me, I tried this - but no change
int index = list.indexOf(key);
list.remove(index);
list.add(index, key);
keyTags = new ArrayList<>();
for (KeyTagIntern keytag : list) {
keyTags.add(keytag);
}
notifyDataSetChanged();
}
});
}
// Then do the opposite for if (!key.isFavourite())
Und hier das xml:
<?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"
android:id="#+id/list_item_keys"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#color/MiddleDarkGrey">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/btn_list_item_keys"
android:layout_width="match_parent"
android:layout_height="#dimen/height_list_item"
android:layout_marginBottom="3dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="3dp"
android:background="#drawable/white_list_item"
android:paddingLeft="13dp"
android:paddingRight="10dp">
<ImageView
android:id="#+id/icon_keylist_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:visibility="visible"
app:srcCompat="#drawable/ic_key" />
<ImageView
android:id="#+id/icon_reserved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/chb_add_key"
android:layout_centerVertical="true"
android:visibility="invisible"
app:srcCompat="#drawable/ic_reservate_orange" />
<ImageView
android:id="#+id/icon_taken"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/chb_add_key"
android:layout_centerVertical="true"
android:visibility="invisible"
app:srcCompat="#drawable/ic_taken_red" />
<TextView
android:id="#+id/text_keylist_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_toEndOf="#+id/icon_keylist_item"
android:layout_toRightOf="#+id/icon_keylist_item"
android:gravity="center_vertical"
android:layout_centerVertical="true"
android:text="Text"
android:textColor="#color/DarkGrey"
android:textSize="#dimen/text_list_item" />
<TextView
android:id="#+id/text_keylist_item_place"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_keylist_item"
android:layout_alignLeft="#+id/text_keylist_item"
android:layout_marginLeft="2dp"
android:layout_marginBottom="5dp"
android:text="Where is the key?"
android:textColor="#color/DarkGrey"
android:textSize="#dimen/text_list_item_sub" />
<ImageView
android:id="#+id/right_icon_keylist_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
app:srcCompat="#drawable/ic_fav_green" />
<ImageView
android:id="#+id/right_icon_keylist_item_favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#drawable/ic_fav_chosen"
android:visibility="invisible"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
I think your approach should be something like this.
rather hiding and displaying an image just change source of it!
if (key.isFavorite())
{
favoriteStar.setImageResource(R.drawable.aaa);
favoriteStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
favoriteStar.setImageResource(R.drawable.bbb);
// and vice-versa
and I don't thing you will be needing notifyDataSetChanged(); as you are making no changes in the Listdata actually!
In the end the answer was rather stupid, as it is so often, and you guys couldn't have helped me since I excluded the code at the beginning of my adapter class (added it now). It actually worked the whole time, but I didn't see it, since the listitem at the very end of the list was changed, not the selected one. This was due to me declaring the variables at the beginning of the adapter class, rather than inside the getView method.
I changed it to this and now it works perfectly:
public class ListViewAdapterKeysAToZ extends BaseAdapter {
private ArrayList<KeyTagIntern> keyTags;
private ObservableArrayList<KeyTagIntern> list;
private Context context;
public ListViewAdapterKeysAToZ(Context context, ObservableArrayList<KeyTagIntern> list) {
this.context = context;
this.list = list;
keyTags = new ArrayList<>();
for (KeyTagIntern keytag : list) {
keyTags.add(keytag);
}
// (...)
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
KeyTagIntern key = (KeyTagIntern) getItem(position);
TextView name;
TextView place;
ImageView star, favoriteStar;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_keys, parent, false);
}
name = (TextView) convertView.findViewById(R.id.text_keylist_item);
name.setText(key.getName());
place = (TextView) convertView.findViewById(R.id.text_keylist_item_place);
place.setText(key.getPlace());
star = (ImageView) convertView.findViewById(R.id.right_icon_keylist_item);
favoriteStar = (ImageView) convertView.findViewById(R.id.right_icon_keylist_item_favorite);
if (key.isFavorite()) {
star.setVisibility(View.INVISIBLE);
favoriteStar.setVisibility(View.VISIBLE);
}else {
star.setVisibility(View.VISIBLE);
favoriteStar.setVisibility(View.INVISIBLE);
}
star.setOnClickListener(v -> {
key.setFavorite(true);
Paper.book().write(FAVORIT + String.valueOf(key.getKeyTagID()), true);
notifyDataSetChanged();
});
favoriteStar.setOnClickListener(v -> {
key.setFavorite(false);
Paper.book().delete(FAVORIT + String.valueOf(key.getKeyTagID()));
notifyDataSetChanged();
});

TextView size is showing different when custom listview is scrolled

In Listview adapter there is condition based textview text size is changing.
condition 1: if no value for discounted it must show only its price in (textview_price) and hide discounted value textview.(textview_price size= 18)
condition 2: if there is value for discounted price then it must show its price in (textview_price) and discounted value textview_discounted.(textview_price size= 15 and textview_discounted size=18).
As shown in above image i am setting visibility gone of textview_discount.
On first time it shows lsitview complete as i set textview size.But when i scroll lsitview its show as above in image not getting proper text size.and text size is=18 where text is big and some where textview size is 15.(problem in textView_price setTextSize not working properly)
adapter.java code:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.list_item_booking_slot_hours,parent ,false);
holder = new ViewHolder();
holder.tv_hours = (TextView) convertView.findViewById(R.id.tv_hour);
holder.textView_hour_am = (TextView) convertView.findViewById(R.id.textView_hour_am);
holder.textView_Price = (TextView) convertView.findViewById(R.id.textView_Price);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String stringPrice = "1500";
String stringDiscountedPrice = "1000"
if (entity.getPay().equals("0")) {
holder.textView_Price.setTextSize(TypedValue.COMPLEX_UNIT_PX, 18);
holder.textView_Price.setText("Rs." + stringPrice);
holder.textView_Discounted_Price.setVisibility(View.GONE);
} else if (entity.getPay().equals("1")){
holder.textView_Discounted_Price.setVisibility(View.VISIBLE);
holder.textView_Price.setTextSize(TypedValue.COMPLEX_UNIT_PX, 15);
holder.textView_Discounted_Price.setTextSize(TypedValue.COMPLEX_UNIT_PX, 18));
holder.textView_Discounted_Price.setText("Rs." + stringDiscountedPrice);
holder.textView_Price.setText("Rs." + stringPrice, TextView.BufferType.SPANNABLE);
}
return convertView;
}
layout.xml for row:
<RelativeLayout
android:id="#+id/relativeLayout_hour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true">
<TextView
android:id="#+id/tv_hour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerInParent="false"
android:layout_centerVertical="true"
android:paddingBottom="5dp"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:singleLine="true"
android:text="05:00"
android:textColor="#drawable/selector_booking_hour_text"
android:textSize="22sp" />
<TextView
android:id="#+id/textView_hour_am"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="false"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/tv_hour"
android:gravity="center_vertical"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:singleLine="true"
android:text=" pm"
android:textColor="#drawable/selector_booking_hour_am"
android:textSize="18sp"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/relativeLayout_hour">
<TextView
android:id="#+id/textView_Price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_toLeftOf="#+id/textView_Discounted_Price"
android:singleLine="true"
android:text="Rs.4000"
android:textColor="#drawable/selector_booking_hour_text"
android:textSize="#dimen/text_slot_price" />
<TextView
android:id="#+id/textView_Discounted_Price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="2dp"
android:layout_toLeftOf="#+id/imageView_slot_arrow"
android:singleLine="true"
android:text="Rs.3000"
android:textColor="#drawable/selector_booking_hour_text_discounted"
android:textSize="#dimen/text_slot_discount_price"
/>
<ImageView
android:id="#+id/imageView_slot_arrow"
android:layout_width="wrap_content"
android:layout_height="12dp"
android:layout_alignParentRight="true"
android:layout_centerInParent="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="2dp"
android:src="#drawable/next" />
</RelativeLayout>
</RelativeLayout>
any help is appreciated. Thank you.
try this modified code
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_booking_slot_hours,parent ,false);
holder = new ViewHolder();
holder.tv_hours = (TextView) convertView.findViewById(R.id.tv_hour);
holder.textView_hour_am = (TextView) convertView.findViewById(R.id.textView_hour_am);
holder.textView_Price = (TextView) convertView.findViewById(R.id.textView_Price);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (entity.getPay().equals("0")) {
holder.textView_Price.setVisibility(View.GONE);
} else if (entity.getPay().equals("1")) {
holder.textView_Price.setVisibility(View.VISIBLE);
}
String stringPrice = "1500";
String stringDiscountedPrice = "1000"
if(!hasDiscount)//flag means your item has no discount
holder.textView_Price.setTextSize(TypedValue.COMPLEX_UNIT_PX, 18);
holder.textView_Price.setText("Rs." + stringPrice);
holder.textView_Discounted_Price.setVisibility(View.GONE);
} else {
holder.textView_Discounted_Price.setVisibility(View.VISIBLE);
holder.textView_Price.setTextSize(TypedValue.COMPLEX_UNIT_PX, 15);
holder.textView_Discounted_Price.setTextSize(TypedValue.COMPLEX_UNIT_PX, 18));
holder.textView_Discounted_Price.setText("Rs." + stringDiscountedPrice);
holder.textView_Price.setText("Rs." + stringPrice, TextView.BufferType.SPANNABLE);
}
return convertView;
}
When I Logged textview_price text size by textView_Price.getTextSize()
I am getting some random position of row's "textview_price.getTextSize()=36" and "textview_discount_price.getTextSize()=36" and where only textView_Price is showing on that psotion row I am getting "textView_Price.getTextSize()=30" randomly when I am scrolling lsitview.
Note: I was getting textview size in form of textviewSize*2. example: if textview textSize=18 then 18*2 = 36.0. why I don't know.
So,finally in if{...}else{...} condition i change the code
if (entity.getPay().equals("0")) {
holder.textView_Price.setTextSize(TypedValue.COMPLEX_UNIT_PX, 18);
holder.textView_Price.setText("Rs." + stringPrice);
holder.textView_Discounted_Price.setVisibility(View.GONE);
if(holder.textView_Price.getTextSize()==30.0)
{
holder.textView_Price.setTextSize(TypedValue.COMPLEX_UNIT_PX, 18);
}
} else if (entity.getPay().equals("1")){
holder.textView_Discounted_Price.setVisibility(View.VISIBLE);
holder.textView_Price.setTextSize(TypedValue.COMPLEX_UNIT_PX, 15);
holder.textView_Discounted_Price.setTextSize(TypedValue.COMPLEX_UNIT_PX, 18));
holder.textView_Discounted_Price.setText("Rs." + stringDiscountedPrice);
holder.textView_Price.setText("Rs." + stringPrice, TextView.BufferType.SPANNABLE);
if(holder.textView_Price.getTextSize()==36.0)
{
holder.textView_Price.setTextSize(TypedValue.COMPLEX_UNIT_PX, 15);
}
}

How to change color of arraylist item in custom listview based on positive or negative value

Im new to android and Im building an app to show stock prices from an XML feed.
I have got an array list containing 3 items. However, I want to change the color of one of the items in the array list to red if its -ve or green if its +ve.
I dont know how to do this or where in my code is best to do it.
Please help....
My Adapter class:
public class TheAdapter extends ArrayAdapter<TheMetal>{
public TheAdapter(Context ctx, int textViewResourceId, List<TheMetal> sites) {
super(ctx, textViewResourceId, sites);
}
#Override
public View getView(int pos, View convertView, ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
Log.i("StackSites", "getView pos = " + pos);
if(null == row){
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_metal, null);
}
TextView dispNameTxt = (TextView)row.findViewById(R.id.displayNameText);
TextView spotPriceTxt = (TextView)row.findViewById(R.id.spotPriceText);
TextView changeTxt = (TextView)row.findViewById(R.id.changeText);
dispNameTxt.setText (getItem(pos).getDisplayName());
spotPriceTxt.setText(getItem(pos).getSpotPrice());
changeTxt.setText(getItem(pos).getChange());
return row;
}
My row_metal layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" >
<TextView
android:id="#+id/displayNameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_marginLeft="20dp" />
<TextView
android:id="#+id/spotPriceText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/displayNameText"
android:textSize="19sp"
android:textStyle="bold"
android:gravity="right"
android:layout_alignParentRight="true"
android:layout_marginRight="30dp" />
<TextView
android:id="#+id/changeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spotPriceText"
android:layout_toRightOf="#+id/displayNameText"
android:textSize="16sp"
android:gravity="right"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
/>
It is so simple. You just need to place these line within your getView() method:
if (Double.parseDouble(getItem(pos).getChange())>=0) {
row.setBackgroundColor(Color.parseColor("#00FF00");
changeTxt.setTextColor(Color.parseColor("#00FF00"));
} else {
row.setBackgroundColor(Color.parseColor("#FF0000");
changeTxt.setTextColor(Color.parseColor("#FF0000"));
}
Change your getView() method to this
#Override
public View getView(int pos, View convertView, ViewGroup parent){
if(convertView == null)
convertView = getLayoutInflater().inflate(R.layout.row_metal, null);
TextView dispNameTxt = (TextView) convertView .findViewById(R.id.displayNameText);
TextView spotPriceTxt = (TextView) convertView .findViewById(R.id.spotPriceText);
TextView changeTxt = (TextView) convertView .findViewById(R.id.changeText);
dispNameTxt.setText(getItem(pos).getDisplayName());
spotPriceTxt.setText(getItem(pos).getSpotPrice());
changeTxt.setText(getItem(pos).getChange());
if( Double.parseDouble(getItem(pos).getSpotPrice()) >= 0 )
convertView.setBackgroundColor(Color.GREEN);
else
convertView.setBackgroundColor(Color.RED);
return convertView;
}

TextView in ListView not being set from CustomAdapter

I have an app that retrieves data from a webservice in the form of an array. In the getView() of the adapter i set the TextViews to the elements in the array. The array is called recordItem and has various elements one of which is "status". Status is a String that can be either completed, ncr, or waiting. if i set the TextView in the listview directly with the value completed, ncr or waiting there's no problem.
I don't want to display the full string in the textview but rather display a C, NCR or W instead. I have a series of "if statements" that check the array element and then sets the textview to the respective character.
The problem is that no character is being displayed. why?
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rotarowlayout, parent,
false);
TextView startTime = (TextView) rowView
.findViewById(R.id.rowstarttime);
TextView duration = (TextView) rowView
.findViewById(R.id.rowduration);
TextView status = (TextView) rowView.findViewById(R.id.rowstatus);
TextView name = (TextView) rowView.findViewById(R.id.rowclientname);
String record = list.get(position).toString();
String[] itemsInRecord = record.split(",");
Log.e(TAG, "itemin record = " + itemsInRecord.length);
String[] recordItem = new String[itemsInRecord.length];
for (int x = 0; x < itemsInRecord.length; x++) {
recordItem[x] = itemsInRecord[x];
Log.e(TAG, "x = " + x);
}
String withoutBraket = recordItem[0].substring(11);
String withoutSecs = withoutBraket.substring(0, 6);
Log.e(TAG, "recordItem = " + recordItem[2]);
if(recordItem[2].toString().equalsIgnoreCase("Completed")){
statusField = "c";
}else if(recordItem[2].toString().equalsIgnoreCase("NCR")){
statusField = "NCR";
}else if(recordItem[2].toString().equalsIgnoreCase("Waiting")){
statusField = "W";
}
Log.e(TAG, "statusField = " + statusField);
startTime.setText(withoutSecs );
duration.setText( recordItem[1]);
status.setText( statusField);
name.setText( recordItem[3] + recordItem[4]);
callID = recordItem[5];
needName = recordItem[6];
return rowView;
}
.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp" >
<TextView
android:id="#+id/rowstarttime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:id="#+id/rowduration"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp" >
<TextView
android:id="#+id/rowstatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" />
<TextView
android:id="#+id/rowclientname"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
recordItem[2] needed trim() calling on it. .equals not picking the strings up because of this.

Centering 2 Textviews in LinearLayout, text only shown when scrolling

I'm trying to center two textViews that are in a LinearLayout. This LinearLayout is nested in another one, with a ListView-element.
I think my XML is pretty correct. I fill my textViews dynamically in my Adapterclass.
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">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<TextView android:layout_height="wrap_content"
android:id="#+id/atlVacaturesnummer"
android:layout_width="wrap_content"
android:textColor="#color/Accent"
android:text="x"
/>
<TextView android:layout_height="wrap_content"
android:id="#+id/atlVacatures"
android:layout_width="wrap_content"
android:text="y"
/>
</LinearLayout>
<ListView android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
<TextView android:layout_height="fill_parent"
android:id="#+id/android:empty"
android:layout_width="fill_parent"
android:text="Er zijn geen jobs die voldoen aan uw criteria..."
android:gravity="center"/>
</LinearLayout>
Adapterclass:
/*
* Klasse VacatureAdapter
*/
private class VacatureAdapter extends ArrayAdapter<Vacature>{
private ArrayList<Vacature> vacatures;
public VacatureAdapter(Context context, int textViewResourceId, ArrayList<Vacature> vacatures){
super(context, textViewResourceId, vacatures);
this.vacatures = getArray();
//System.out.println("Array vacatureadapter: " + v);
}
#Override
public View getView(int position, View convertview, ViewGroup parent){
View view = convertview;
if(view==null){
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.vacature_list_item, null);
//view.setBackgroundColor((position % 2) == 1? Color.LTGRAY: Color.WHITE);
}
TextView atlVacatures = (TextView)findViewById(R.id.atlVacatures);
TextView atlVacaturesnr = (TextView)findViewById(R.id.atlVacaturesnummer);
atlVacaturesnr.setText("" + arrVacatures.size());
atlVacatures.setText(" jobs op maat gevonden!");
Vacature vaca = vacatures.get(position);
if(vaca != null){
TextView tvNaam = (TextView) view.findViewById(R.id.vacatureNaam);
TextView tvWerkveld = (TextView) view.findViewById(R.id.vacatureWerkveld);
TextView tvRegio = (TextView) view.findViewById(R.id.vacatureRegio);
if(tvNaam != null){
tvNaam.setText(vaca.getTitel());
if(tvWerkveld != null){
tvWerkveld.setText("Werkveld: " + vaca.getWerkveld());
if(tvRegio!=null){
tvRegio.setText("Regio: "+vaca.getRegio());
}
}
}
}
return view;
}
}
The weird thing is that if my spinner runs, he shows the texts set in my XML correctly, if the spinner stops and fills my ListView it only shows one digit of my number and when I scroll once he shows my number completly plus the second TextView. I don't quite understand what's wrong, maybe some code needs te be put somewhere else?
I've solved my problem by putting my setText code in my Runnable method, after I dismiss my Dialog. Now It looks like this:
private Runnable returnRes = new Runnable(){
public void run(){
if (arrVacatures.size() == 0){
dialog.dismiss();
}
if(arrVacatures!=null && arrVacatures.size() > 0){
adapter.notifyDataSetChanged();
for(int i= 0; i< arrVacatures.size();i++){
adapter.add(arrVacatures.get(i));
}
dialog.dismiss();
TextView atlVacatures = (TextView)findViewById(R.id.atlVacatures);
TextView atlVacaturesnr = (TextView)findViewById(R.id.atlVacaturesnummer);
atlVacaturesnr.setText("" + arrVacatures.size());
atlVacatures.setText(" jobs op maat gevonden!");
adapter.notifyDataSetChanged();
}
}
};

Categories

Resources