I'm relatively new to android and I'm working on a horizontal scroll view with drag and drop functionality. Right now everything is working perfectly fine I can drag the image and drop it in the drop zone with count of failed and successful drops. For now the image that is being dragged and its shadow looks the same. What I want is that when I drag an image the shadow that appears for that image is an image from drawables that I select.
Here is the code for shadow builder:
void dragAndDropImage(int imageId)
{
// int drawableid = getResources().getIdentifier("drawable/a1", "id", getPackageName());
final ImageView drag = (ImageView)findViewById(imageId);
drag.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent arg1) {
// TODO Auto-generated method stub
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadow = new View.DragShadowBuilder(drag);//I want the drawable id here View.DragShadowBuilder(drawableid)
v.startDrag(data, shadow, null, 0);
return false;
}
});
I want to get the id of one particular image from drawables and then I can use it in View.DragShadowBuilder(id of the image from drawables) to change the image of the shadow. Any help in this regard is appreciated.
It will be something like:
R.drawable.resourcename
Make sure you don't have the Android.R namespace imported as it can confuse Eclipse (if thats what you're using).
If that doesn't work, you can always use a context's getResources method ...
Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);
Where this.context is intialised as an Activity, Service or any other Context subclass.
Update:
If it's the name you want, the Resources class (returned by getResources()) has a getResourceName(int) method, and a getResourceTypeName(int)?
Update 2:
The Resources class has this method:
public int getIdentifier (String name, String defType, String defPackage)
Which returns the integer of the specified resource name, type & package.
(I have been seeing this post getting more views every time I log in and I solved this a long time ago but I'm going to post the solution in hopes that it helps someone else.)
In my case I had multiple images in Drawable that I wanted to use therefore
for (int j=1; j<10; j++)
{
setImages("drawable/img" +j);
// SetPopup(drag);
}
void setImages(final String draw)
{
int id12 = getResources().getIdentifier(draw, "id", "your_package_name");
drag1.setImageResource(id12);
I just posted the part of code that helped me access different images directly from drawables and use them as drag images on multiple imageViews.
String uri = "#drawable/yourdrawable";
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
Can you try this?
Try this,
final ImageView drag = (ImageView)findViewById(R.id.imageId);
drag.setImageResource(R.drawable.a1);
View.DragShadowBuilder shadow = new View.DragShadowBuilder(drag);
Assume you have several drawables in your Android resource folder and what to iterate over them. You use a certain naming schema and would like to use this to determine the resources ID’s.
The following steps shows how to get a resource ID based on the resource name:
// Name of resource
//Type
// Package of the app
int identifier = getResources().getIdentifier("pic1", "drawable", "android.demo");
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageResource(identifier);
Related
like the title said, i really want to get a drawable name from my current image view
Imageview img = findViewById(R.id.IMG);
and it set with image from drawable named "img001.png"
and I have a button that will change the image to "img002.png", and when clicked again it should be changed the image again to "img001".
i use code like this
if (myimg == "img001"){
myimg= "img002"
}else if (myimg == "img002"){
myimg= "img001"}
it not work since "myimg" is null at start, so i want "myimg" to check which image is already in use.
i ve googled some info how to get resource name but all I got is how to get resource id from its name.
Get the image name like is explained here:
Android: How to get Drawable Image name
Then compare the name by using equals():
if("img001".equals(imageName)) {
...
}
I would suggest using custom tags instead of finding resource name, changing tag for that imageview and checking that in if-else condition instead of taking image names. When you apply resource to image view, assign that resource id as tag to image view.
if(imgView != null) {
imgView.setImageResource(resourceId_1);
imgView.setTag(resourceId_1);
imgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(imgView.getTag != null) {
if(imgView.getTag() = resourceId_1) {
imgView.setImageResource(resourceId_2);
imgView.setTag(resourceId_2);
} else if(imgView.getTag() = resourceId_2) {
imgView.setImageResource(resourceId_1);
imgView.setTag(resourceId_1);
}
} else {
Log.v(TAG, "ImageView tag is null");
}
}
}
}
I have a standard chat display method for a Firebase chat:
private void displayChat() {
final ListView listOfMessage = findViewById(R.id.list_of_message);
final String DATABASE_URL = "https://firebasestorage.googleapis.com";
Query query = FirebaseDatabase.getInstance().getReference().child("messages").child(chatName).limitToLast(20);
FirebaseListOptions<Message> options = new FirebaseListOptions.Builder<Message>()
.setLayout(R.layout.list_item)
.setQuery(query, Message.class)
.setLifecycleOwner(this)
.build();
FirebaseListAdapter<Message> adapter = new FirebaseListAdapter<Message>(options) {
#Override
protected void populateView(View v, Message model, int position) {
//Get reference to the views of list_item.xml
TextView messageText, messageUser, messageTime;
ImageView img;
messageText = v.findViewById(R.id.message_text);
messageUser = v.findViewById(R.id.message_user);
messageTime = v.findViewById(R.id.message_time);
img = v.findViewById(R.id.imgView);
if (model.getMessageText().contains(DATABASE_URL)) {
messageText.setText("Image sent: ");
Picasso.with(getApplicationContext()).load(model.getMessageText()).into(img);
}
else {
messageText.setText(model.getMessageText());
}
messageUser.setText(model.getMessageUser());
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", (long)model.getMessageTime().get("timestamp")));
}
};
listOfMessage.setAdapter(adapter);
}
Chat is fully functional. However, when it comes to images, I have DATABASE_URL to determine that what's being received should be an image instead of text, so I load it in with Picasso as above:
if (model.getMessageText().contains(DATABASE_URL)) {
messageText.setText("Image sent: ");
Picasso.with(getApplicationContext()).load(model.getMessageText()).into(img);
}
However, when it is normal text, my:
else {
messageText.setText(model.getMessageText());
}
Will show the text as normal, but still display an image - always the most recent image displayed. I have tried adding img.setVisibility(View.INVISIBLE); into the else statement, as well as equivalent removals from Glide/Picasso but they all end up in every single image being removed and not displayed.
It is happening because You are reusing one type of layout. Every view which will be showed next will reuse the previous one. If You don't invalidate layout's views, it can happen situation where one of the views will contain old data.
This layout is just like a skeleton where You pin some elements. Then someone want to reuse Your skeleton. He gets it with Your stuff. So he has to remove all elements and after that he can pin own stuff. If You bend something in the skeleton, next guy will have to unbend otherwise he will have skeleton with bended element (i.e. setVisibility(INVISIBLE)->setVisibility(VISIBLE)).
As soon as You get the layout, reset values in all views.
I need set image resource by Send parameter (String src)
I have this code
public void getSource(View view , String src){
ImageView image = (ImageView)findViewById(R.id.img);
image.setImageURI(src);
}
How do I solve this problem ؟
// method to call to set image
private void setImage(int src) {
ImageView iv = findViewById(R.id.your_image_view);
iv.setImageResource(src);
}
//Pass your resource and use it like this :-
setImage(R.drawable.plus_active);
If you want to set image from local storage, then you have to get the uri of the image and use setImageUri like this:
public void getSource(View view , String srcImageUri){
ImageView image = (ImageView)findViewById(R.id.img);
image.setImageURI(Uri.parse(src));
}
If you have image in drawable folder , then you have to set image like this:
image.setImageResource(R.drawable.imageName);
And if you want to set image from web url, then you have to use libraries like picaso or fresco.
use getResources().getIdentifier(); (there you can pass the image name String as a parameter to getIdentifier() function) to get the resourceID of the named image and then use setImageResource(resourceID); to set the image to ImageView.
public void getSource(View view , String src){
int resID = getResources().getIdentifier( src, "drawable", Context.getPackageName());
ImageView image = (ImageView)findViewById(R.id.img);
image.setImageResource(resID);
}
you may need to pass the Context as a parameter to your getSource() function.
I am currently involved in a project about hotels and restaurants. My database contains hotel IDs(1,2,3,...) and I need to load the images(image1,image2,...) of the respective hotels/restaurants for which I have to give the image src through .java file.The code that I used is :
String icon="image" + h_id;
int resID = getResources().getIdentifier(icon, "drawable","testing.Image_Demo");
image.setImageResource(resID);
But, the problem is that the hotel image is not loading. I had gone through different questions in this site but the problem remains as it is. Does anyone have an idea to solve this? Thanks in advance!
I created the following sample activity, which works fine if I have a "image.png" image file in the drawable folder:
public class TestActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String icon = "image";
int resId = getResources().getIdentifier(icon, "drawable", getPackageName());
ImageView imgView = new ImageView(this);
imgView.setImageResource(resId);
setContentView(imgView);
}
}
Did you check that your package name is correct ?
I have a LinearLayout, and this LinearLayout will hold dynamically placed views. I need to find out what the width of the children of LinearLayout, however this has to be done in onCreate method. From researching I've found out that you can't use getWidth from this method. So instead I'm using onWindowFocusChanged, which works for the parent LinearLayout (returning me the actual size), but it doesn't work with its children.
Another thing I noticed is that when the screen is fading away and the screen is locked, I can see at the logs the actual width of the children being returned (I think the activity is being paused).
I'm really stuck and this is needed because I need to dynamically place those views depending on the children width.
You might be able to get with the below. But as others pointed out, this probably isn't a great idea.
LinearLayout.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
LinearLayout.getMeasuredWidth();
inside the onCreate , views still can't know the state of the nearby views and the children ,etc... so only after all is prepared and the layout process is done , you can get the size of views .
here's a quick code for getting the size of the view just before it's being drawn:
private static void runJustBeforeBeingDrawn(final View view, final Runnable runnable)
{
final ViewTreeObserver vto = view.getViewTreeObserver();
final OnPreDrawListener preDrawListener = new OnPreDrawListener()
{
#Override
public boolean onPreDraw()
{
Log.d(App.APPLICATION_TAG, CLASS_TAG + "onpredraw");
runnable.run();
final ViewTreeObserver vto = view.getViewTreeObserver();
vto.removeOnPreDrawListener(this);
return true;
}
};
vto.addOnPreDrawListener(preDrawListener);
}
alternatively , you can use addOnGlobalLayoutListener instead of addOnPreDrawListener if you wish.
example of usage :
runJustBeforeBeingDrawn(view,new Runnable()
{
#Override
public void run()
{
int width=view.getWidth();
int height=view.getHeight();
}
});
another approach is to use onWindowFocusChanged (and check that hasFocus==true) , but that's not always the best way ( only use for simple views-creation, not for dynamic creations)
EDIT: Alternative to runJustBeforeBeingDrawn: https://stackoverflow.com/a/28136027/878126
https://stackoverflow.com/a/3594216/1397218
So you should somehow change your logic.