Reference R.id. in custom class - android

I basically made a class, with this method:
void setResource(Context context, R.id resourceID) {
ImageView test = (ImageView) context.findViewById(resourceID);
}
The "findViewById" gives me a can't resolve method.
I have three ImageViews defined in XML, I would like to set the image associated to them programatically. in my main_activty I do so by using:
ImageView blah = (ImageView) this.findViewById(R.id.blah);
Then:
blah.setImageResource(R.drawable.pony);
HOWEVER, I would like to pass everything to my class I made and have it handle all that in the custom class, but when I try to pass everything (the code at the very top; "setResource") I get that findViewByID can't resolve method. Is there a way to do it that way?

I think you are trying to find the words to express what you are trying to do, and with some of the basic concepts. This is my best guess of what you are trying to accomplish...
The code below takes an id for drawable, loads it, and then puts it into an imageView in your layout. The ImageView must already be there in your layout, it does not create one for you dynamically.
void setResource(Context context, int resourceId) {
//resourceId = R.drawable.ponies (example)
Drawable drawable = context.getResources().getDrawable(resourceId);
//R.id.main_imageview is example imageView in a layout.
ImageView iv = findViewById(R.id.main_imageview);
iv.setImageDrawable(drawable);
}

Related

(Android Studio, Kotlin) Image in Imageview is not displaying when clicked

Hi all I have a problem in displaying image in ImageView when clicked, i made a function to display whenever the image was click I have already added the android:onClick="drops" in .xml in every imageview of my sample game, i used gridlayout(3x3) with 9 imageview
here is the code of the function.
fun drops(view: View){
val imageView = ImageView(this)
var player = 0;
if (player == 0){
imageView.setImageResource(R.drawable.yellow)
imageView.animate().alpha(1f).rotation(360f).setDuration(600)
player == 1
}else {
imageView.setImageResource(R.drawable.red)
imageView.animate().alpha(1f).rotation(360f).setDuration(600)
player == 0
}
}
I'm unsure in what class is this function contained, I suppose it is either in a Fragment or Activity. As you said, you're binding the image views with drops method in the xml layout.
What could be the problem is this line:
val imageView = ImageView(this)
From your question we cannot see which class is this method defined in, so expression this could be anything. You might me instantiating an ImageView from the whole Activity or Fragment object, and cannot work in way you would like to. So I suggest to rewrite this line to something like this:
val imageView = view as ImageView
The function drops receives a single View parameter, which is the image view the user clicked - but View class has no method called setImageResource, so you need to cast it to the desired subtype (ImageView is subclass of View). This should do the job.

android: one click listener on many imageviews in layout

I have the following scenario:
In a layout, I have imageviews aligned horizontally and vertically as shown in image.
First, which layout should be used for this purpose? RelativeLayout or FrameLayout? ListView inside the layout?
Also, instead of writing setOnClickListener for every imageview, how can I write just one click listener to get the clicked imageview?
A GridView is perfect for this. For more information on GridView, look here.
As for your onClickListener question: there is no easy way to do this, but what you can do is something like this:
Have an array containing every ImageView id like so:
public static final int[] IMAGE_VIEWS = {R.id.imageView1, R.id.imageView2, R.id.imageView3 /*etc*/}; //Make sure to list from the first imageview to the last image view in correct order
Define an onClickListener
private View.OnClickListener imageViewListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < IMAGE_VIEWS.length; i++) {
if (v.getId() == IMAGE_VIEWS[i]) {
doSomethingWithImageViewClick(i); //if ImageView 4 was clicked, variable 'i' will be 3 (because arrays start at index = 0).
}
}
}
}
Set the onClickListeners for all your imageViews:
final ImageView view1 = (ImageView) view.findViewById(R.id.imageView1);
view1.setOnClickListener(imageViewListener);
//etc
Use 'GridView' in the layout and use 'setOnItemClickListener' to handle click events,
You can find more details in below link
GridView.
GridView can achieve the effect. I think you can look at this Grid View.

ImageSwitcher load images from url

I'm trying to show images from a URL in a ImageSwitcher. I've tried with:
myImageSwitcher.setImageURI(Uri.parse("http://miurl.com/images/foto01.jpg"));
but it said me this "error":
I/System.outīš• resolveUri failed on bad bitmap uri: http://miurl.com/images/foto01.jpg
Thanks
I know it is late but because I found a better solution for this, would love to share it with all :)
I had to look at the source code of the default ImageSwitcher and know how it works. Whenever we use ImageSwitcher we set a ViewFactory to it. This ViewFactory creates Views which are then used in the ImageSwitcher. Usually we create an ImageView in the ViewFactory. This ImageView is then used in the ImageSwitcher class to draw the view with the image source specified. Below is the setImageResource() method of the ImageSwitcher class.
public void setImageResource(#DrawableRes int resid){
ImageView image = (ImageView)this.getNextView();
image.setImageResource(resid);
showNext();
}
Let's focus on the first and second line of the method.
ImageView image = (ImageView)this.getNextView();
image.setImageResource(resid);
this.getNextView() gets the view from the ViewFactory and casts the view into an ImageView. And then, the Drawable resource is set to it.
Solution
Now, with these information, let's get to the solution! I'm using Volley's NetworkImageView , but you can use Picasso or Glide too! You just have to change the code a bit.
We need to create a custom ImageSwitcher. Here's my code
MyImageSwitcher.java
public class MyImageSwitcher extends ImageSwitcher {
public MyImageSwitcher(Context context) {
super(context);
}
public MyImageSwitcher(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setImageUrl(String url) {
NetworkImageView image = (NetworkImageView) this.getNextView();
image.setImageUrl(url, AppController.getInstance().getImageLoader());
showNext();
}
}
Notice the setImageUrl() method. We cast the view we get from getNextView() to a NetworkImageView and set the Url to it. If you want to use Picasso, then just cast it into an ImageView and then use Picasso as it needs to be used.
Activity
MyImageSwitcher imageSwitcher = (MyImageSwitcher) findViewById(R.id.imageSwitcher);
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
public View makeView() {
NetworkImageView myView = new NetworkImageView(getApplicationContext());
myView.setScaleType(ImageView.ScaleType.CENTER_CROP);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(imageSwitcher.getLayoutParams()));
return myView;
}
});
If you want to use Picasso, then just use an ImageView.
Layout
<xyz.farhanfarooqui.loadingimages.MyImageSwitcher
android:id="#+id/imageSwitcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
AndroidManifest.xml
Don't forget to include android.permission.INTERNET to your AndroidManifest.xml
Done!
Whenever you want to change the image, do it this way,
imageSwitcher.setImageUrl("http://miurl.com/images/foto01.jpg");
I've solucionated this problem using SliderLayot (https://github.com/daimajia/AndroidImageSlider), but I'll try to do with ImageSwitcher too.
I was trying to achieve the same thing when I landed here. I know it's and old question, but since I don't see an answer, I'll tell you the solution that worked for me.
First of all, I downloaded the image/s that I wanted to show in the imageswitcher and return them as a Bitmap using this code:
InputStream in = new java.net.URL(url).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
Then I set the bitmap in the imageswitcher using imageSwitcher.setImageDrawable(new BitmapDrawable(getResources(), bitmap)).
To use java.net.URL(url).openStream(), you'll need to add <uses-permission android:name="android.permission.INTERNET"> to your AndroidManifest.xmlfile.
Have in mind that you could change the download code to make it better (checking for timeouts for example), but this is just a basic solutions to start from.
Another thing about what you were using, I think you can't use setImageURI() to set an internet resource in your ImageSwitcher. Acording to this post, this method is only for content URIs particular to the Android platform (Note that they are talking about an ImageView in that post, but I think the same goes to this case).

Set background of android activity without using XML file

I want to develop an application in which I want to set the background image which is in my drawable folder. I want when my activity will run, the back ground will be that image.And also no XML is to be used.
Thanks.
Without XML file,
Create an ImageView and set drawable to it. Now use setContentView(View view) of Activity..
Simple...
Dynamically,
//pseudo code only.. Implement in your way..
OnCreate()
{
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.android);
setContentView(imageView);
}
Try to use setBackgroundDrawable(R.drawable.yourImage) method for your layout.Suppose your main layout is LinearLayout
LinearLayout ll = (LinearLayout) findViewById(R.id.lineaLayout);
ll.setBackgroundDrawable(R.drawable.yourImage); // like this you can set image for your layout
Another Simple solution..
Use this in your onCreate() method of Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setBackgroundDrawableResource(R.drawable.background);
}
Get a handle to the root layout used, then set the background color or drawable on that. The root layout is whatever you called setContentView with.
setContentView(R.layout.main);
// Now get a handle to any View contained
// within the main layout you are using
View someView = findViewById(R.id.randomViewInMainLayout);
// Find the root view
View root = someView.getRootView()
// Set the color
root.setBackgroundColor(android.R.color.red);

Android - Gallery of ImageViews with background images?

I am new to Android development, but familiar with the concept of views, controls, objects, XML layouts, C#, etc.
I'm trying to create a horizontally scrolling "list" of images using as much native functionality as possible. (I'm not adverse to using custom components, but I'm trying to learn and optimize as much as possible before hacking something together.)
I currently have a Gallery with an adapter tied to it. The adapter is creating ImageViews as seen in many basic tutorials. On each pass of the adapter, I'm setting the background image for the ImageView. My hope was that I'd be able to position the foreground image to lay on top of the background image at a specific X/Y position. Unfortunately, I haven't made it past the point of getting the background image to behave the way I'd like it to.
Is this even possible with a simple Gallery and an ImageView? Or, do I need to build a custom control of some sort (possibly using nested layouts?) and use that control on each iteration of the adapter?
Any help will be greatly appreciated.
Here's what I'm seeing...
http://philaphan.com/public/stackoverflow/gallery1.png
...and what I'd like to see...
http://philaphan.com/public/stackoverflow/gallery2.png
Here's my code:
public class MyAdapter extends BaseAdapter
{
private Context mContext;
public MyAdapter(Context c)
{
mContext = c;
}
public int getCount()
{
return App.myList.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
String imagePath = App.myList.get(position).thumbnail;
ImageView i = new ImageView(mContext);
i.setLayoutParams(new Gallery.LayoutParams(150, 150));
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
i.setBackgroundResource(R.drawable.image_bk5);
//i.setBackgroundColor(Color.BLACK);
File f = new File(imagePath);
if (!f.exists())
{
i.setImageResource(R.drawable.image_missing);
}
else
{
Bitmap bmp = BitmapFactory.decodeFile(imagePath);
i.setImageBitmap(bmp);
}
return i;
}
}
I think you can use:
i.setPadding(50, 50, 50, 50); //setpadding(left,top,right,bottom)
Try to use this..
replace i.setScaleType(ImageView.ScaleType.CENTER_INSIDE); with i.setScaleType(ImageView.ScaleType.FIT_XY);
or check your background image . I think your background image width creating problem.
I was able to work around this by using a HorizontalScrollView with a LinearLayout nested within it. I then programmatically add two ImageViews -- one for the background and one for the foreground -- and I position the foreground at whatever X/Y that I choose.
I'd still be interested in knowing if this can be done within a Gallery control, if anyone sees this at a later date.
As a general rule, if you want to add a background image to any kind of inflated gallery or ArrayAdapter or BaseAdapter, then - Make sure that the background image is defined in the parent layout, or parent view, for example the main layout, using the attribute "android:background="#drawable/backupimage".
Do not set the background in the XML representing the custom-row/object-view of the repeating instances.
This way the background image will be displayed only once, appearing static behind all inflated objects, and not duplicated again and again on every single row/object.

Categories

Resources