I have a list which lists EXPENSES and INCOMES. I want ListViewer to automatically change background to either green for Incomes or red for Expenses, would this be possible?
final DbCon database = new DbCon(this);
final ListView Viewer = (ListView)findViewById(R.id.historyViewer);
//date1, time1, desc1, val1, cat1, type1
final SimpleAdapter La = new SimpleAdapter(this, database.GetMonths(), R.layout.mviewer, new String[] {"month"}, new int[] {R.id.month_name});
Viewer.setAdapter(La);
Without seeing any code, its hard to give any "real" help but it is possible. You can change the background color with something like
rowView.setBackgroundColor(Color.GREEN);
assuming rowView is your current View in the List. You can also change styles and themes depending on what you want.
Yes just put the logic in the getView method of your Adapter, e.g.:
public View getView(int position, View convertView, ViewGroup parent) {
View myView;
if(convertView == null) {
myView = new MyView();
} else {
myView = (MyView) convertView;
}
if(myList.get(position).isExpense) {
myView.setBackgroundColor(Color.RED);
} else {
myView.setBackgroundColor(Color.GREEN);
}
return myView;
}
edit:
Yes, I see that you are using a SimpleAdapter. That will not be sufficient to do what you want. You need to create your own adapter by subclassing BaseAdapter (or something similar) and overriding the necessary methods, e.g. getView as I showed above.
Related
I have a listview that is populated via an adapter. I need one of the items (which are just bits of text) in the listview to have a different background compared to the others (to mark it as the currently selected one).
I have all of the background logic, I just need a way to say listview.setBackgroundById(int position)
or something like that.
How do I do this?
This needs to be as simple as possible, 'cause all of the other things done in the Activity are currently working perfectly. :)
As asked, this is my Adapter that I'm using:
public class SampleAdapter extends ArrayAdapter<SampleItem> {
private String title;
public SampleAdapter(Context context) {
super(context, 0);
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_station, null);
}
TextView title = (TextView)convertView.findViewById(R.id.station_name);
font.setFont(title, 2, getActivity());
title.setText(getItem(position).title);
RelativeLayout info = (RelativeLayout)convertView.findViewById(R.id.info_relative_button);
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity.setCurrentTab(41);
MainActivity.setBackDisabled(true);
Log.e("current tab:",String.valueOf(MainActivity.getCurrentTab()));
Fragment fragment = new StationInfo();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
UserManager.getInstance().setStationId(getItem(position).id);
}
});
return convertView;
}
}
The SampleItem has 2 String fields, title and id, it's very simple.
You need to use a custom list adapter and have it return views with your desired background. Create a class extending ListAdapter or any of the existing SimpleAdapter etc and override getView to inflate a suitable view for your element, and add any logic you need to set the background of that view.
There is no way to tell the listview itself to decorate some of its elements by id or position.
Update: I just noticed you added the list adapter code.
Since you are already implementing getView, to change the background of your element simply call convertView.setBackgroundColor, or have two different views inflated depending on the situation.
(BTW it's really bad practice to call static methods on your activity like in your onClickListener.)
In ListView adapter:
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
if(view==null)
....
//for example every even list item to be grey, every odd to be white
if(((position+1)%2)==0)
view.setBackgroundColor(mContext.getResources().getColor(R.color.grey));
else view.setBackgroundColor(mContext.getResources().getColor(android.R.color.white));
Hope you get an idea...
I created an application for chat between two person
first of all i have to fetch all data from server by Jsonparser
there is a custom listview each row contains "shop,painter,datetime,comment,id"
if yourname is not empty means comment is yours and viseversa
i want to put a bubble background for comment that indicate the painter or shop
i dont know how to use getview when i have a custom listview with more than one textview and because my resource data that is contain all information comes from server and store it to the hashmap array... hashmap doesnt have position as it is in getview method...
.........some code .....
// adding HashList to ArrayList
AllCommentsList.add(map);
adapter = new SimpleAdapter(getApplicationContext(),
AllCommentsList, R.layout.list_row_order_comments,
new String[] { TAG_COMMENT_ID, TAG_SHOP, TAG_PAINTER,TAG_COMMENT, TAG_DATETIME },
new int[] { R.id.tvIdComments, R.id.tvShopSender,R.id.tvPainterSender, R.id.tvComment,R.id.tvDateTimeComments });
// updating listview
listViewComment.setAdapter(adapter);
this is my code but i want to dynamically change the background of Comment textview
how to put some code like this????
if (strPainter.equals("null")) {
tvComment.setBackgroundResource(R.drawable.bubble_green);
}
if (strShop.equals("null")) {
tvComment.setBackgroundResource(R.drawable.bubble_yellow);
}
Don't use SimpleAdapter. Create a custom adapter that overrides getView and make whatever manipulations that you want to the layout, background, etc based on the current item.
See /samples/android-8/ApiDemos/src/com/example/android/apis/view/List5.java in your Android SDK folder (download appropriate samples as necessary) for a simple example:
private class MyListAdapter extends BaseAdapter {
...
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if (convertView == null) {
tv = (TextView) LayoutInflater.from(mContext).inflate(
android.R.layout.simple_expandable_list_item_1, parent, false);
} else {
tv = (TextView) convertView;
}
tv.setText(mStrings[position]);
return tv;
}
...
}
i am trying to show the contents using a list activity in android.
I am getting a list from backend. now i want to fetch each list value and see whether that item is shown in red color or in green color. this value will also be set in customVO.
I tried refering to few article on internet like this. but here they are using List only but i need VO so that i can fetch the value to decide whether that menu item should be red or green.
P.S i am beginner in android so excuse me if my question seems to be bit stupid.
thanks in advance :)
Just override the getView method to set the background:
final ArrayAdapter<MyClass> adapter = new ArrayAdapter<MyClass>(
getActivity(),
R.layout.list_item,
myArray) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = super.getView(position, convertView, parent);
/* Set values of TextViews here */
MyClass currentItem = getItem(position);
if (currentItem.getColor() == MyVoClass.GREEN) {
convertView.setBackgroundColor(0x0000FF00);
} else if (currentItem.getColor() == MyVoClass.RED) {
convertView.setBackgroundColor(0x00FF0000);
} else {
convertView.setBackgroundColor(0x00FFFFFF);
}
return convertView;
}
};
I am trying to modify the sample code below. It currently populates a View that contains an imageview and a textview. I have added an additional textview to my XML layout and am trying to figure out how to replace the simple array with a hash map or even a multidimensional array to populate not just the imageview and the first textview but also the second one.
I would appreciate sample code that shows the entire process. Thanks!
public class DynamicDemo extends ListActivity {
TextView selection;
private static final String[] items={"lorem", "ipsum", "dolor",
"sit", "amet"}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new IconicAdapter());
selection=(TextView)findViewById(R.id.selection);
}
public void onListItemClick(ListView parent, View v,
int position, long id) {
selection.setText(items[position]);
}
class IconicAdapter extends ArrayAdapter<String> {
IconicAdapter() {
super(DynamicDemo.this, R.layout.row, R.id.label, items);
}
public View getView(int position, View convertView,
ViewGroup parent) {
View row=super.getView(position, convertView, parent);
ImageView icon=(ImageView)row.findViewById(R.id.icon);
if (items[position].length()>4) {
icon.setImageResource(R.drawable.delete);
}
else {
icon.setImageResource(R.drawable.ok);
}
return(row);
}
}
}
The easiest thing to do is use an ArrayAdapter<MyDataObject> where
public class MyDataObject {
public String string1;
public String string2;
// any other useful attributes
}
And then you would change items to a MyDataObject[] items stored in your class, and instead of doing super.getView(index) you'd do items[index] (which would yield a MyDataObject) and use that data instead.
Also, importantly: you should use the convertView. And possibly the ViewHolder pattern.
Edit: At OP's request, a little more elaboration. Note that this uses the convertView pattern but not the ViewHolder pattern (you should be able to adopt that fairly easily).
In your Adapter, you'd change getView() as follows:
public View getView(int position, View convertView,
ViewGroup parent) {
ViewGroup row;
if(convertView == null){
// create your view here.
row = getLayoutInflater().inflate(R.layout.row);
} else {
row = convertView;
}
// note: when you implement ViewHolder, the ViewHolder will
// hold this reference so that you don't need to look it up every time.
ImageView icon=(ImageView)row.findViewById(R.id.icon);
// here you're employing the "items" array that you were using
// before, except now it contains MyDataObjects. pick out the
// string (or other data you want to check) from the resulting MyDataObject,
// and see if it's longer than 4 characters.
MyDataObject objectAtThisPosition = items[position];
if (objectAtThisPosition.string1.length()>4) {
icon.setImageResource(R.drawable.delete);
}
else {
icon.setImageResource(R.drawable.ok);
}
// Do whatever else you want to with objectAtThisPosition.
return(row);
}
That's it for the easy way, and quite similar to what you have.
Some more detail; if you don't care, skip it. :)
I know that Adapters can seem magical, so in the interest of showing how ListView adapters work, here's an example using a List instead of an Array, so we can remove any magic that ArrayAdapter does with the array behind the scenes. I use a List because they can be more versatile for whatever you're trying to accomplish (ArrayList or LinkedList or what-have-you).
To use a List you'd have the following in your Activity:
private List<MyDataObject> myList = new ArrayList<MyDataObject>();
And instead of items[position] you'd use
MyDataObject objectAtThisPosition = myList.get(position);
If you want to change your data set dynamically, you should probably use this approach (keeping myList at the Activity level) instead of using an Array and an ArrayAdapter. That would mean you'd need to change from extending ArrayAdapter<String> to just extending BaseAdapter<MyDataObject> (most of the methods in BaseAdapter are trivial to implement) since our data size, for example, would be determined by our list, and not the ArrayAdapter's array.
I know that's kind of a fire hose, but let me know if you have any questions!
Use a separator in string, like \t.
Or use an array of straing arrays.
Or use an array of Pair<String, String>.
Or use an array of custom objects.
i work with sqlite and i fetch results from two columns(name,icon). i want to pass them to a custom adapter so as to set the name as the text of a (TextView) and then the icon as his drawableLeft with setCompoundDrawablesWithIntrinsicBounds.
first of all my insert in db are like this
"Fruit / Vegetables,R.drawable.ic_launcher",
"Meat / Fisth,R.drawable.ic_launcher"
in my listActivity i have this code after openning the db etc..
mShopCatCursor = mDbHelper.fetchShoppingCategories();
startManagingCursor(mShopCatCursor);
String[] names,icons;
while(mShopCatCursor.moveToNext()){
for(int i=-1,l=mShopCatCursor.getColumnCount(); ++i<l;){
names[i]= mShopCatCursor.getString(0);
icons[i]= mShopCatCursor.getString(1);
}
}
//this was taken from a tut
String[] from = new String[]{AppSQLite.KEY_NAME,AppSQLite.KEY_ICON};
TextViewWithDrawableListAdapter adap =
new TextViewWithDrawableListAdapter(this, from);
setListAdapter(adap);
what i want is to pass the names and the icons so the custom adapter do the following
public View getView(int position, View convertView, ViewGroup parent){
View v = convertView;
if(v == null){
LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.main_list_item, null);
}
TextView textView = (TextView) v.findViewById(R.id.main_menu_list_item);
i want this!!
for each list item to take the correct values.
textView.setText(names[0]);
textView.setCompoundDrawablesWithIntrinsicBounds(icons[0], 0, 0, 0);
return v;
}
i know namew[0] and icon are incorrect but i really cant find the way, even by searching the web for hours.
Fisrt of all i don't get clear about what you want. If you want to pass the names and icons array to you custom adapter class then you can use constructor in your custom adapter class to receive them. Or read this tutorial .