This is my xml, this is located inside a fragment that appears in my activity.
<FrameLayout android:id="@+id/frame1" android:layout_width="wrap_content" android:layout_height="115dp" android:layout_margin="2dp" android:layout_weight="0.33"> <ImageView android:id="@+id/whoamiwith" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="fitCenter" android:src="@drawable/default_image" /> </FrameLayout>
And this is my java code :
@Override public void onClick(View click) { if (click == profileBtn) { whoamiwith.setBackgroundResource(R.drawable.image_i_wanna_put); } }
I am trying to change the image source of the image view. There are no syntax errors but when I click the button the emulator is giving me a force close and on the logcat it says:
java.lang.NullPointerException
It's pointing to the line:
whoamiwith.setBackgroundResource(R.drawable.loginbtn);
Using setBackgroundResource() method: myImgView. setBackgroundResource(R.
With a FrameLayout you can place a text on top of an image view, the frame layout holding both an imageView and a textView.
Displays image resources, for example Bitmap or Drawable resources. ImageView is also commonly used to apply tints to an image and handle image scaling.
To make a View clickable so that users can tap (or click) it, add the android:onClick attribute in the XML layout and specify the click handler. For example, you can make an ImageView act like a simple Button by adding android:onClick to the ImageView . In this task you make the images in your layout clickable.
Set different image inside imageview on button click dynamically in android app. Imageview image can be easily replaceable through MainActivity.java coding file because sometimes app developer want to change the imageview image on any button click. So here is the complete step by step tutorial for Change image in imageview programmatically android.
Select the path of the image file on your computer and click “ OK “. After that set, the “ Qualifier type ” and “ value ” of the image file according to your need and click “ Next ” then “ Import “. Drag the ImageView class in the activity area, a pop-up dialogue box will appear which contains your imported image file.
Below is the example code in which we set the source of a imageview lion which is saved in drawable folder. We can also set the source image at run time programmatically in java class. For that we use setImageResource () method as shown in below example code.
For adding an image from Android Studio, Drag the ImageView widget to the activity area of the application, a pop-up dialogue box will open choose from the wide range of drawable resources and click “ OK “. Click on the “ Resource Manager ” tab on the leftmost panel and select the “ Import Drawables ” option.
whoamiwith.setImageResource(R.drawable.loginbtn);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With