I'm trying to create a listview with a static background image (i.e. not contained within the individual list cells, but fills the display and does not move when list is scrolled). I've found a couple references here and am trying to implement, but no joy. The first is;
Set a background for a listview
In particular, I'm trying this;
//set background to Drawable
listView.setBackgroundDrawable(myDrawable);
To create the "myDrawable" variable, I'm using a suggestion from;
How can I access an android drawable by a variable
Again, the particular code I'm trying is;
String icon="logo" + cnt;
int resID = getResources().getIdentifier(icon, "drawable", getPackageName());
logo.setImageResource(resID);
Here is the code I created;
ListView lv = getListView();
lv.setTextFilterEnabled(true);
String bg="football_turf_subtle";
int resID = getResources().getIdentifier(bg, "drawable", getPackageName());
myDrawable.setImageResource(resID);
lv.setBackgroundDrawable(myDrawable);
The problem I'm running into in my code is "myDrawable cannot be resolved"? If it's not obvious, I'm new to Android/Java.
Thanks in advance for any help!
Just do lv.setBackgroundResource(R.drawable.football_turf_subtle).
Related
My problem
I have some dynamically created imageViews in which I put a drawable (xml vector, SVG). Everything seems to be OK on the android emulator but when I load the app on my phone there is no image visible. I know the image is there because if I increment its size, the views on the right at on the left move to the side. So there is an image!
What I have tried
Check memory of the phone
Use android:src and app:sourceCompat for the imageViews
Convert Drawable into Bitmap
Load another image (which is doing well in another window)
Put the drawable file in another drawable-folder
Change the layout type from RelativeLayout to LinearLayout
Read all the similar posts... No one resolves my problem :(
My class RankingDialog extends from AlertDialog.Builder
My layout is a RelativeLayout but I don't think that this causes the issue...
Create the views
for (int i = 0; i < LocalNames.size(); i++){
LinearLayout layout = new LinearLayout(context);
layout.setLayoutParams(layoutParams);
TextView position = new TextView(context);
TextView name = new TextView(context);
TextView record = new TextView(context);
position.setTypeface(font);
name.setTypeface(font);
record.setTypeface(font);
position.setText(i+1 + ".");
position.setGravity(Gravity.CENTER);
name.setGravity(Gravity.CENTER);
record.setGravity(Gravity.CENTER);
position.setLayoutParams(tvPosParams);
layout.addView(position);
name.setText(LocalNames.get(i));
name.setLayoutParams(tvNameParams);
layout.addView(name);
//Here is where I create and load the imageView/image
ImageView flag = new ImageView(context);
flag.setLayoutParams(imageParams);
flag.setImageResource(context.getResources().getDrawable(R.drawable.myImage);
layout.addView(flag);
record.setText(LocalPoints.get(i));
record.setLayoutParams(tvPointsParams);
layout.addView(record);
mainLinear.addView(layout);
}
----------Emulator (How it should look like)
How it looks on any real device...
I'm stuck for a couple of weeks here. I can't understand why this is happening...
I will apreciate any help
I have an app that create a random image when the activity opens. There are like 30 images in the random image array. The image is generated, but what I want is to write the drawable name into a textview. It looks like this:
ImageView RImage= (ImageView) findViewById(R.id.image);
RImage.setImageResource(generator());
Drawable myDrawable = RImage.getDrawable();
TextView writeID = (TextView) findViewById(R.id.idtext);
writeID.setText(String.valueOf(generator()));
}
private int generator() {
TypedArray imgs = getResources().obtainTypedArray(R.array.list3);
int imgid = imgs.getResourceId(new Random().nextInt(imgs.length()), -1);
imgs.recycle();
return imgid;
}
Currently I receive numbers, and I cant figure out how can I convert the int to a string, or how can I use the generator to generate a string, display in the textview and then convert it to int to display it in the imageview.
I created an another activity where I can pick the image I want to see from a spinner, it simply send the selected option with string to the next activity on button press, and in the other activity i remove the .png and res/drawable/ from the string, and convert the string into an int to display the image.
Bundle extras = getIntent().getExtras();
String transportItemChosen = extras.getString("SpinnerValue");
transportItemChosen = transportItemChosen.replace(".png", "");
transportItemChosen = transportItemChosen.replace("res/drawable/", "");
String uri = ("#drawable/" + transportItemChosen);
int id = getResources().getIdentifier(uri, null, getPackageName());
ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.selectedimage);
mImageView.setImageResource(id);
So I need the generator to generate to string and then convert it to int. Thanks!
Change your code by converting your int ids into String names by Using the method
getResourceEntryName(int id);
Change the line:
writeID.setText(String.valueOf(generator()));
To Something like:
writeID.setText(getResources().getResourceEntryName(generator()));
And for Viceversa:
And if you are having a String lets assume this String you get from a textView or using above method to convert it back to an int id you do the following:
int id= getResources().getIdentifier("your_string_here", "drawable", getPackageName());
And if you are calling the code from a Fragment not an Activity remember to put getActivity() before calling getResources()or before calling getPackageName().
I have not tested the code as I am typing, but I am sure it will work (may be a typo) for more information consider visting the Documentation on Resources from this official link.
If I understand you correctly, what you need is to take a look at getResourceName(int) method - it returns resource name by its id. Also you can use getIdentifier(String,String,String) method to retrieve resource id by its name.
If you want to display name of the randomly picked image, you should save the generated resource id into the variable and get corresponding resource name for it instead of calling generator() method twice as you'll get two different ids.
I am making an Android app of Checkers based on XML widget (like imageview).
I made a table of 8X8 of imageviews and call their id like so (i00 , i01 etc).
I have two questions:
I've tried to make a reference of the imageviews in the code like this:
ImageView img = (ImageView) findViewById(R.id.i00);
and it gives me an error:
"i00 cannot be resolved or is not a field"
Is there any way of getting id by a string?
For example I have a imageview which id is i01, can I get it by:
String str = "i01"
and then give str as a parameter for some kind of method?
1: That call is correct, check this thread which talks further about that error: “id cannot be resolved or is not a field” error
2: Something like this should work:
String str = "i02";
int id = getResources().getIdentifier(str, "id", getPackageName());
ImageView img = (ImageView) findViewById(id);
Check this link for more information findViewById with String
Ok so i sucsessfully gotten my names from my database, and now i've stored them in the array result[], and at the end of the code i've written return result; now my question, how do i get the names from my result[] to appear in a listview? note: i do not want to have the connecting to mysql database on the same class as my listview one.
How would i go about doing this?
I also wish to know how i would go about making a custom listview with the names and a picture on the side. Also if you could tell me how i would go about adding pictures to listviews aswell, that'd be great :) i'm going to be using bmp, retriving them from database as byte[] and then convert them to bmp.
note: fairly new to java and android development
You can find a lot of examples on internet.
A simple example would be:
ListView listView = (ListView) findViewById(R.id.listOne);
String[] name={"HELLO","THIS","IS","NABIN"};
String[] phone={"12","24","36","48"};
ArrayList<HashMap<String,String>> obj= new ArrayList<HashMap<String,String>>();
for(int i=0;i<name.length;i++){
HashMap<String,String> toFill = new HashMap<String,String>();
toFill.put("name", name[i]);
toFill.put("phone", phone[i]);
obj.add(toFill);
}
//to define adapter
ListAdapter adapter = new SimpleAdapter(MainActivity.this, obj, R.layout.contact, new String[] {"name", "phone"},new int[] {R.id.etName,R.id.etPhone});
listView.setAdapter(adapter);
Edited:
For images to display:(Considering your images are in drawable folder)
You have to make a custom adapter
And for imageView of custom adapter do the following:
String imageName = ......// get text from your array which would be the name of image.
int resID = getResources().getIdentifier(imageName , "drawable", getPackageName());
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageResource(resId);
I am developing a chat application, where i have implemented image sending. So without the images everything works fine. But now I'm facing issues in displaying the images that are sent / received. For that what i've done is downloaded the image first and saved it in external storage. My idea was simple fetch the bitmap set it in an imageview on the getView method. Nothing wrong with fetching the image and displaying but listview ruins everthing.
This is my code-
ListView getView()
ViewHolder holder = null;
if(convertView == null ){
convertView = inflater.inflate(R.layout.chat_list, null);
holder = new ViewHolder();
holder.mMsg = (TextView) convertView.findViewById(R.id.text);
holder.mDate = (TextView) convertView.findViewById(R.id.text1);
holder.mLinLay=(LinearLayout) convertView.findViewById(R.id.linSide1);
holder.mRelLay=(RelativeLayout) convertView.findViewById(R.id.relSide);
holder.img=(ImageView)convertView.findViewById(R.id.image);
holder.progCircle=(ProgressBar)convertView.findViewById(R.id.pbHeaderProgress);
convertView.setTag(holder);
} else{
holder = (ViewHolder) convertView.getTag();
}
holder.position=position;
holder.img.setTag(position+"img");
HashMap<String, String> hm = list.get(position);
String date=hm.get("date");
long l = Long.parseLong(date);
long unixTime = System.currentTimeMillis();
CharSequence datedate=DateUtils.getRelativeTimeSpanString(l, unixTime, 1);
String status = hm.get("status");
String who = hm.get("who");
if(hm.get("message").contains("[[pic_message]]"))
{
String picName=hm.get("message").replace("[[pic_message]]", "");
final String picPath1=Environment.getExternalStorageDirectory()+"/App/sent_pics/"+picName+".jpg";
File file = new File(picPath);
if(file.exists())
{
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
Bitmap bm;
#Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
bm = decodeSampledBitmapFromResource(picPath1,100,100);
return bm;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (v.img.getTag().equals(position+"img")) {
v.img.setImageBitmap(result);
}
}
}.execute(holder);
}else{
holder.img.setImageBitmap(null);
}
}else{
holder.img.setImageBitmap(null);
Spannable msg =getSmiledText(getApplicationContext(),hm.get("message"));
holder.mMsg.setText(msg);
}
holder.mDate.setText(datedate);
return convertView;
What the problem is-
The listview shows up, but the images are displayed at random listview items. I searched a lot for this kind of problem, tried them but still no luck. The asyntask code is from Google- Use A Background Thread.. As you see from above i didn't set any holder.mMsg.setText(msg); but still whenever the images are shown they are accompanied by a msg, which is not desirable. Also the scrolling is kindda laggy when the images are shown. I have seen many messaging apps, they all run so smoothly, and the items are never mixed up. So what do they use.Also, while googling this problem, one answer suggested that we should remove the converView if else and then everything will be fine. But that will have performance issues which i don't want.
So my question is what should i do? How do the chat apps like, hangouts,bbm,whatsapp achieve this so smoothly?
EDIT
The pictures are displayed with no problem but the main problem is that they are diplayed at random orders.
Like this- i scroll till the image message, they are displayed. Then I again scroll and now the image is displayed in other listview item. My guess is that the same view(which originallly holds the image) is now being used by other, but the image stays there. How can i fix that ? And make the listview smooth (even with images) like the IM apps?
It's because Android ListView reuses Views, so while your Asynctask execute the donInBackground the user is already doing something else and you code don't know anything about it. (So it will put the image)
I would use Picasso to avoid the problem and let someone else handle your problem.
I handled this problem in my application (a contact phone) using:
A cache, to avoid to send multiple requests for the same image even when i already have in memory his image
I send a WeakReference<> to the Asynctask so when it's done check if the ImageView is still valid and put the bitmap inside it. Update the cache.
(Specific to me) Since sometimes i could happen that a contact don't have a photo i just created another List with all users without a photo (so i don't try to download it)
Everytime a .getview is called check if the image is inside the cache and if it's inside the cache put directly it, or start the asynctask.
Bitmap bitmap = cache.get(number);
if (bitmap == null) {
Log.d(TAG, "I will download image for " + name + ".");
// i set a dummy image to avoid to show the wrong picture
holder.contactPhoto.setImageResource(R.drawable.ic_action_person);
loadUserProfilePhoto(number, holder.contactPhoto);
}
else {
// show it directly
Log.d(TAG, "I already have " + name + " in cache.");
holder.contactPhoto.setImageBitmap(bitmap);
}
If you see, it could happen that it shows another picture instead of the user-photo while it's still loading it so i set a dummy picture instead of the old photo.
It's not the best implementation, but it's to show you that it could be very hard to implement it by yourself and do it right.
Read Picasso documentation and see how it could implement it in your code (it's simple, it's just one line.)
The issue is with listview which continuously keep refreshing it.
So your all code is fine, but just set default image in holder.img instead of making it null holder.img.setImageBitmap(null);
And may be in async too, you need set default_image while your image is being loaded.
If you want display images on the fly I think you should use SurfaceView. It is a lot faster and has a higher refresh rate. I made a video streaming application where I tried to display each video frame on the ImageView but that failed. But when I tried out SurfaceVIew it worked out fine.