EDIT: Sorry I realise from your comment my question was not clear enough. I will post a new one. Sorry for this and thanks for your answers
I am populating a ListView from a Json file.
With my listadapter, I can easily assign appropriate json data to each row of my list. That works well for text, for example:
TextView tv = (TextView)ll.findViewById(R.id.descView);
tv.setText(i.desc);
With the above code, every row will be correctly populated by the good json data.
However, I don't manage to do the same thing for an image. I have tried to set the right image from my json data using this:
ImageView iv = (ImageView)ll.findViewById(R.id.imgView);
iv.setBackgroundDrawable(context.getResources().getDrawable(i.img));
I guess I am doing something wrong with the type of my parameters: "setBackgroundDrawable" requires a drawable parameter.
"getDrawable" requires an int.
I have set the type of my field img to int, but that doesn't work.
Any idea why?
My list adapter:
public class adapter extends ArrayAdapter<ListItems> {
int resource;
String response;
Context context;
//Initialize adapter
public ListItemsAdapter(Context context, int resource, List<ListItems> items) {
super(context, resource, items);
this.resource=resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
//Get the current object
ListItems i = getItem(position);
//Inflate the view
if(convertView==null)
{
ll = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li;
li = (LayoutInflater)getContext().getSystemService(inflater);
li.inflate(resource, ll, true);
}
else
{
ll = (LinearLayout) convertView;
}
//For the message
TextView tv = (TextView)ll.findViewById(R.id.descView);
tv.setText(i.desc);
// For the Img
ImageView iv = (ImageView)ll.findViewById(R.id.imgView);
iv.setBackgroundDrawable(context.getResources().getDrawable(i.img));
return ll;
}
my item class:
public class ListItems{
int id;
int img;
String desc;}
And a sample of my json file:
[{"id":10001,"img":e1,"desc":"desc1"},
{"id":10002,"img":e2,"desc":"desc2"},
{"id":10003,"img":e3,"desc":"desc3"}]
Try this
iv.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.img));
or
iv.setBackgroundResource(R.drawable.img);
Now as getDrawable and setBackgroundDrawable both are depricated you should set drawable as Background like this :
view.setBackground(ContextCompat.getDrawable(this, R.drawable.your_drawable));
and if you are targating minSdk below 16 then make a check like this :
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.your_drawable));
} else {
view.setBackground(ContextCompat.getDrawable(this, R.drawable.your_drawable));
}
If you want to change the ImageView image/src,
In Layout android:src="#drawable/img" or app:srcCompat="#drawable/img"
Programmatically imageview.setImageResource(R.drawable.img);
If you want to change the background of ImageView
In Layout android:background="#drawable/img"
programmatically selectimg.setBackgroundResource(R.drawable.circle_filled);
Here imageview is a ImageView and img is a drawable.
Here the new Method
recyclerView.setBackgroundResource(R.drawable.edit_text_button_shape);
don't use this it's an old method
recyclerView.setBackgroundDrawable(this.getResources().getDrawable(edit_text_button_shape));
Related
In Android ListView have always a single image repeated in all the titles. How can I reduce a copying of the images in code from x times to 1 time?
Such as the code given below:
public class Test1 extends AppCompatActivity {
ListView listView;
String[] fruitNames = {"Apple","Orange","Kiwi","Passion","Banana"};
int[] fruitImages = {R.drawable.ic_chevron_right,R.drawable.ic_chevron_right,R.drawable.ic_chevron_right,R.drawable.ic_chevron_right,R.drawable.ic_chevron_right};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test1);
In this code I am copying all the times the same image code, that is:
int[] fruitImages = {R.drawable.ic_chevron_right,R.drawable.ic_chevron_right,R.drawable.ic_chevron_right,R.drawable.ic_chevron_right,R.drawable.ic_chevron_right};
I want to set a number of repeats such as x (times the drawable image). Is it possible somehow?
The GitHub Project is available from LarnTech. In this project, my images are an arrow. I can do this by repeating the things but I am curious if it can be done in a lucid way.
Just pass your fruit array alone in the adapter's constructor and use imageView.setResource(R.drawable.ic_chevron_right) to set the drawable
public class SimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] fruitNames;
public MySimpleArrayAdapter(Context context, String[] fruitNames) {
super(context, -1, values);
this.context = context;
this. fruitNames = fruitNames;
}
#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.rowlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(fruitNames[position]);//fruitName
imageView.setImageResource(R.drawable.ic_chevron_right); //just set the image in the adapter
return rowView;
}
}
As I can see your github project, the images are different in the array.
But here, all the images are same.
If you don't want to create the array of same images, then you can use just one variable here. Like:
int fruitImage = R.drawable.ic_chevron_right;
and it can be used in getView() of CustomAdapter like
image.setImageResource(fruitImage);
But if you've to use different images in each views then you need to use array or go for ArrayList.
I'm trying to create section headers for my ListView in a way that some list rows have headers and some do not. So what i have is three xml layout files. fragment_listview.xml contains the <ListView>
row_listview.xml contains the content for ListView rows
header_listview.xml is for the section headers.
Feeds.java is my model class.
So in my adapter i have something like this:
public class FeedsArrayAdapter extends ArrayAdapter<Feeds> {
private Context context;
private List<Feeds> feeds;
private LayoutInflater vi;
FeedsArrayAdapter(Context c, List<Feed> ff){ //initializes all the class member fields }
public void getView(int position, View convertView, ViewGroup parent){
Feeds f = feeds.get(position);
if(f.headerNeeded()){
convertView = vi.inflate(R.layout.header_listview, null);
TextView textViewHeader = (TextView) convertView.findViewById(R.id.feed_header);
textViewHeader.setText(new SimpleDateFormat("dd/MM/yyyy").format(feed.date));
}
else {
convertView = vi.inflate(R.layout.row_listview, null);
TextView textViewfeedHeading = (TextView) convertView.findViewById(R.id.feed_heading);
TextView textViewfeedSubheading = (TextView) convertView.findViewById(R.id.feed_subheading);
TextView textViewfeedDate = (TextView) convertView.findViewById(R.id.textViewDate);
ImageView imageViewfeedIcon = (ImageView) convertView.findViewById(R.id.feed_icon);
ImageView imageViewfeedBanner = (ImageView) convertView.findViewById(R.id.feed_banner);
textViewfeedHeading.setText(feed.title);
textViewfeedSubheading.setText(feed.subtitle);
textViewfeedDate.setText(new SimpleDateFormat("dd/MM/yyyy").format(feed.date));
}
return convertView;
}
So this gives us something like this:
---header1----
---header2----
___Row 3_____
___Row 4_____
What i want is:
-----header 1------
_____Row 1_______
-----header 2------
_____Row 2_______
_____Row 3_______
_____Row 4_______
If i try to inflate row.listview in if(true) I get an exception.
Any approach how to resolve this.
you can use Sticky Header Library here
yourListView.addHeaderView(yourHeaderView);
See http://developer.android.com/reference/android/widget/ListView.html#addHeaderView%28android.view.View%29
use expandable listview with BaseExpandableAdapter
I have a list of textView that is programmed dynamically...
GridView layout = (GridView) context.findViewById(R.id.linearLayout1);
PrizeAdapter adapter = new PrizeAdapter(context, 0, 0, game.getPrizeList());
layout.setAdapter(adapter);
Adapter Class:
public class PrizeAdapter extends ArrayAdapter<String> {
private List<String> objects;
public PrizeAdapter(Context context, int resource, int textViewResourceId,
List<String> objects) {
super(context, resource, textViewResourceId, objects);
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView text = new TextView(getContext());
text.setId(position);
text.setText(objects.get(position));
text.setTextSize(12);
text.setPadding(0, 5, 0, 5);
text.setTextColor(Color.WHITE);
text.setBackgroundColor(Color.GRAY);
text.setGravity(Gravity.CENTER | Gravity.BOTTOM);
return text;
}
}
Supposedly, I have created a 10 TextView. How can i get the particular textView so i can color it differently.
I tried this
GridView layout = (GridView) context.findViewById(R.id.linearLayout1);
TextView view = (TextView) layout.findViewById(1);
view.setBackgroundColor(Color.YELLOW);
view.setTextColor(Color.RED);
But it doesn't work and just encountered a nullpointer exception.
Please help.
The reason for such behavior is you are doing it too early.
i.e even before the view are created with id 1 you are trying to access them.
So what is happening is, you ask adapter to inflate view and adapter takes control checking what is visible and what should be displayed.
and immediately after if ( before view are populated) you call findviewbyID(1) so this view is still not created hence you get null pointer.
The code will work if we try to use a button to do the task after grid is populated.
final GridView layout = (GridView) findViewById(R.id.linearLayout1);
PrizeAdapter adapter = new PrizeAdapter(this, 0, 0, objects2);
layout.setAdapter(adapter);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView view = (TextView) layout.findViewById(1);
view.setBackgroundColor(Color.YELLOW);
view.setTextColor(Color.RED);
// TODO Auto-generated method stub
}
});
So 2 solution
1) delayed handler post for changing color.
2) create a custom callback interface which will give you back result like view 1 loaded.
Use ViewGroup.getChildAt(position), which will return you the view at that position. Then Typecast it to TextView(as you are setting the TextView as direct item View) to set color.
One more thing you cannot use findViewById() when you are creating objects dynamically unless you set ID for the object.
i want to build an application with a listview or whatever.. that looks very attractive and have some images and many more.But i cant find a good way to have that. I exactly want my application's UI like this images:
(source: coenraets.org)
(source: coenraets.org)
i want to display my app like this images please suggest me how can i do this? please if u know some tutorials then give the links.
Yes. Just place one ImageView and TextView in one xml layout. And, inflate this layout into one layout which is having the ListView And, do the process there for getting images from webservice or locally stored
Here i provide some example links that may very useful to you -
Lazy load of images in ListView
ListView with images
How to display a list of images in a ListView in Android?
You need to build the layout you want in a XML file, the same way you would do for an Activity. Then just inflate the XML layout for each row in your ListView and set its values and images.
Example of one ArrayAdapter that I've inflated with my own view (picture, text and checkbox):
private class FriendListAdapter extends ArrayAdapter<User> {
public FriendListAdapter(Activity a, int textViewResourceId, List<User> items) {
super(a, textViewResourceId, items);
}
public class ViewHolder{
public TextView username;
public ImageView image;
public CheckedTextView ctv;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.invite_friend_row, null);
holder = new ViewHolder();
holder.username = (TextView) v.findViewById(R.id.username);
holder.username.setTypeface(tf);
holder.image = (ImageView) v.findViewById(R.id.image);
holder.ctv = (CheckedTextView) v.findViewById(R.id.checked);
v.setTag(holder);
}
else{
holder = (ViewHolder) v.getTag();
}
final User user = getItem(position);
if(user != null){
holder.username.setText(user.getName());
holder.ctv.setChecked(user.isChecked());
holder.image.setImageView(user.getImage());
}
return v;
}
}
You get the idea!
I'm trying to change the item colors of a listview in android, but I can't make it work. I want the colors to alternate... I've made my own adapter and inside the getView method I changed the color before returning the list view but it doesn't work I don't know why...
Here is my code:
public class EventoAdapter extends ArrayAdapter<Evento>{
Context context;
int layoutResourceId;
ArrayList<Evento> evento = null;
public EventoAdapter(Context context, int textViewResourceId,
ArrayList<Evento> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.layoutResourceId = textViewResourceId;
this.context = context;
this.evento = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
EventoHolder holder = null;
if(row == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new EventoHolder();
holder.nombre = (TextView)row.findViewById(R.id.nombreEvento);
holder.total = (TextView)row.findViewById(R.id.totalEvento);
holder.moneda = (TextView)row.findViewById(R.id.moneda);
holder.fecha = (TextView)row.findViewById(R.id.fecha);
row.setTag(holder);
}else{
holder = (EventoHolder)row.getTag();
}
Evento ev = evento.get(position);
holder.nombre.setText(ev.getNombre());
holder.total.setText(Integer.toString(ev.getTotal()));
holder.moneda.setText("$");
holder.fecha.setText("20/12/11");
if(position%2==0){
row.setBackgroundColor(R.color.colorPar);
}else{
row.setBackgroundColor(R.color.colorImpar);
}
return row;
}
static class EventoHolder{
TextView nombre;
TextView total;
TextView moneda;
TextView fecha;
}
}
Of course I have defined the colorPar and colorImpar inside my own colors.xml resource.
Any Idea why this is not working??
Thanks!
Looks like the default background for view is transparent. Try this and it should work..
if(position%2==0){
row.setBackgroundColor(new
ColorDrawable(context.getResources().getColor(R.color.colorPar)));
}else{
row.setBackgroundColor(new
ColorDrawable(context.getResources().getColor(R.color.colorImpar)));
}
Use setBackgroundResource() rather than setBackgroundColor().
setBackgroundResource() takes an integer resource index as parameter, and load whatever resource that index points to (for example; a drawable, a string or in your case a color).
setBackgroundColor(), however takes an integer representing a color. That is, not a color-resource, but a direct, hexadecimal, rgba value (0xAARRGGBB).
So, when you call setBackgroundColor() using a resource index (say 7f050001, which is the first color index), you always set your color to a:127 r:5 g:0 b:1.
In case you have more then just one or two properties you wish to change for an alternate or any other additional layout, the below post describes how to apply separated layouts based on the item index.
Just override the getViewTypeCount and getViewType Methods(or in Xamarin ViewTypeCount property and GetViewType Method)
links:
Android ListView with multiple layouts
https://developer.xamarin.com/api/property/Android.Widget.BaseAdapter.ViewTypeCount/