ImageView hiding and showing - java

I'm struggling to get my android app to show and hide imageView objects programmatically. Actually I'm struggling to get expected behavior from imageView objects full stop.
Following the answers to this question,
Here's what I'm testing with:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{
#Override
protected void onCreate(Bundle savedInstanceState) {
ImageView warn = (ImageView)findViewById(R.id.gpsStatusWarning);
warn.setImageResource(R.drawable.gps_error);
warn.getLayoutParams().height = 64;
warn.getLayoutParams().width = 64;
}
}
The above code is called in the parent activity's OnCreate method, and it does exactly what I expect: It changes the image of the object to be the one designated, and it sets the height and width of said object. However, what I can't seem to do is to set the object as INVISIBLE or GONE. I just can't make it vanish at all, in fact. I've tried both:
warn.setVisibility(View.INVISIBLE);
warn.setVisibility(View.GONE);
But the image is still visible. I've even tried changing it in the XML to
android:visibility="gone"
But even that hasn't helped. The image is still visible.
What am I doing wrong? Am I missing a call to some update method? Does setting the image resource force the image to be drawn?

Try :
warn.setImageResource(0);
Or : warn.setImageResource(android.R.color.transparent);

This is how you set the visibility of ImageView objects on Android programatically:
yourImage.setVisibility(View.VISIBLE);
yourImage.setVisibility(View.INVISIBLE);
yourImage.setVisibility(View.GONE);
You can also set the initial states of ImageView objects in XML layout files like this:
visibility="visible"
visibility="gone"
visibility="invisible"
You can follow the official documentation about ImageView controls to try it on yourself on this link below. Learn how to set the visibility state of a view.

imageView.setVisibility(View.GONE);
imageView.setVisibility(View.VISIBLE);

Related

How can I show image set in android java?

I am trying to add an image into my app with java so I googled how to do this and seen I had to add
Context mContext;
Drawable myImage = mContext.getDrawable(R.drawable.my_image);
(That was all of the code they said I had to add) But when I run it I don't see my image I set to it. So how I would be able to show the image I set to it?
For a image to be displayed, you need to give a view for that . ie - ImageView
Add a ImageView in your main-layout.
Initialize that ImageView in the on create of your activity like
ImageView appImage = findViewById(R.id.your_image_View_id);
3.Then set an image to the image view like
appImage.setImageResource(R.drawable.your_image);
Hope this helps.
You just initialize the imageview from layout like below,
ImageView appImage = findViewById(R.id.your_image_View_id);
appImage.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.drawable.ic_downarrow));
With new android API 22 getResources().getDrawable() is now deprecated. So now the best approach is to use only getDrawable() is using ContextCompat
Please follow the steps:
Step1: In your main_layout.xml, add an <ImageView ... tag give an id, let's say id is "imageView"
Step2: In your MainActivity.class onCreate() method, Initialize that ImageView as:
ImageView image = findViewById(R.id.imageView)
then,
Step3: assign your drawable as:
im.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.your_image_drawable));
If you are using a fragment, use:
im.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.your_image_drawable));
Hope it helps. Please update if it does.
ImageView appImage = findViewById(R.id.your_image_View_id);
In activity simply use setImageResource
appImage.setImageResource(R.drawable.ic_avatar);

How do I change the main xml file from another activity?

I am very new to Java. I am doing a school project at the moment and I have my main activity, then I have a settings activity. I am trying to modify the xml from the main activity with the settings activity. I am able to modify the settings xml file with the settings.java, but I would like to modify the main activity xml with settings.java
public class Settings extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// Get the Intent that started this activity and extract the string
Switch switchButton;
final RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.activity_settings);
final RelativeLayout mRelativeLayoutMain = (RelativeLayout) findViewById(R.id.activity_main);
switchButton = (Switch) findViewById(R.id.switch1);
switchButton.setChecked(true);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}
}
});
if (switchButton.isChecked()) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}}
public void toast1(View view) {
android.widget.Toast.makeText(this, "Created by Cody Walls and Tommy Serfas", android.widget.Toast.LENGTH_LONG).show();
}
/*public void switch1(View view) {
ScrollView mScrollView = (ScrollView) findViewById(R.id.scrollView);
mScrollView.setBackgroundColor(Color.GRAY);
}*/
}
In the Code I am trying to change the background of the main activity xml with :
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
and when I run the app and click the intent it will crash with the error:
"java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null
object reference"
I think the easiest way is to create an PreferenceManager.SharedPreferences, in which I recommend you to store current app data. This will help you not to loose any changes in app after you exit the it. Here is short instructions:
Create button in settings activity which will change something in main activity.
Create onClickListener for your button.
Use .SharedPreferences to store was you button clicked or not. (I recommend storing boolean variables, this way you can store was button clicked or not.)
I both of your activities in onCreate method call .getSharedPreferences to read saved app values. (I mean to read was the button clicked or not.)
Use app values you got from 4. to change any element in activity. (For example if you stored that button was clicked, then change some TextView text or etc.)
I hope you understood the idea.
Link to the Android developer tutorial about App key values storing & saving
Link to the StackOverflow much easier explanation & examples
There are a couple of ways of doing this (Some of which depends on how you are switching back and forth from each activity). It also depends on what things you are changing.
From your settings page, as you are changing different settings, you'll save this content within Preferences. (You can see more how to use Preferences here: https://examples.javacodegeeks.com/android/core/ui/settings/android-settings-example/ or by just Googling it).
On you main activity, depending on how you come back to it (onStart most likely), you can setup the things you need to programmatically.
So, you may need to do a little research on the Android lifecycle and how each cycle works (https://developer.android.com/guide/components/activities/activity-lifecycle.html), how to program the UI programmatically through Java (http://startandroid.ru/en/lessons/220-lesson-16-creating-layout-programmatically-layoutparams.html), and the Preferences Android library to save certain settings.
The xml isn't meant to be "altered". You can change the UI programmatically. It's possible to build an Android app without any xml. When Android was first built, it didn't use the xml to create the UI. It was all done through Java. It was then added to use xml to create your activities or fragments or any UI component. This made things easier for more static activities or activities with very little dynamic content.

A button which allows an image to be shown in Android Studio

I am building my application using Android Studio, this app can upload an image from raspberry to my emulator. It works fine. What I want to do now is uploading this image and showing it directly to the user without searching it in the gallery. I thought about creating another class and setting this image as a background image in my xml file, but this is too much like I have to create another class every time I want to upload an image from my raspberry.
Can someone help me please. Thank you
If I'm understanding your question correctly, you'd like to load an image from the Android filesystem into your app and display it to the user.
Drawable, Android's generalized image class, allows you to load from file via Drawable#createFromPath.
This SO question suggests Drawable#createFromPath doesn't work on paths beginning with file://, so depending on your use case you may want to precede that with Uri#parse/Uri#getPath.
Once you have a Drawable, you can display it in one of two ways: put an ImageView in your app and call its setImageDrawable method, or set the Drawable as your background image via View#setBackground (note that setBackground was only added in API 16 - in prior versions, you should call View#setBackgroundDrawable).
Putting all of this together, we end up with the following (untested):
private void loadImage(String imagePath) {
Uri imageUri;
String fullImagePath;
Drawable image;
ImageView imageDisplay;
imageUri = Uri.parse(imagePath);
fullImagePath = imageUri.getPath();
image = Drawable.createFromPath(fullImagePath);
imageDisplay = (ImageView) findViewById(R.id.imageDisplay);
/*if image is null after Drawable.createFromPath, this will simply
clear the ImageView's background */
imageDisplay.setImageDrawable(image);
/*if you want the image in the background instead of the foreground,
comment the line above and uncomment this bit instead */
//imageDisplay.setBackground(image);
}
You should be able to modify this to work with any View just by replacing imageDisplay's declared type with the appropriate View type and changing the cast on findViewById. Just make sure you're calling setBackground, not setImageDrawable, for a non-ImageView View.

Start an activity with a shared element from custom view

I want to create a animation between two Activities with a image as shared element, see Customize Activity Transitions
My problem: In the source activity the image is drawn on a canvas of a custom view :-(
Is there a way to use this image as a shared element or do I have to add a real ImageView?
You can't share the image only, but you can share the entire custom view. This means that the entire custom View would disappear from the calling Activity when the shared element is transferred to the launched Activity. If your custom View only has the image, that would be fine, but if it paints other things, that would be disastrous.
If you want to share only the image, you'll have to create a View (e.g. ImageView) and move the image to it and then share it. That way, when the shared element is transferred, it hides properly from the calling activity.
The shared elements don't actually move Views between Activities, they just share a 'snapshot' of the view as a bitmap and the position of the view. In the launched activity, the view with the given transition name will be laid out in that position. You can use the snapshot or not, depending on your needs. By default, the snapshot is not used.
So you'll need some code like this:
public void launchActivity(final Intent intent, final CustomView view) {
final Bitmap bitmap = view.getSharedImage();
ImageView imageView = new ImageView(view.getContext());
imageView.setBitmap(bitmap);
LayoutParams layoutParams = view.createSharedImageLayoutParams();
final ViewGroup parent = (ViewGroup)view.getParent();
parent.addView(imageView, layoutParams);
parent.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener() {
#Override
public boolean onPreDraw() {
parent.getViewTreeObserver().removeOnPreDrawListener(this);
customView.hideSharedImage();
ActivityOptions activityOptions = ActivityOptions.
makeSceneTransitionAnimation(this, imageView, "destName");
startActivity(intent, activityOptions.toBundle();
}
});
setExitSharedElementCallback(new SharedElementCallback() {
#Override
public void onSharedElementsArrived(List<String> sharedElementNames,
List<View> sharedElements, OnSharedElementsReadyListener listener) {
super.onSharedElementsArrived(sharedElementNames, sharedElements,
listener);
parent.removeView(imageView);
customView.showSharedImage();
}
});
}
I haven't specifically tried the above, but that's the essence of it. If you don't want to use the newer onSharedElementsArrived, you can create a custom ImageView that listens for onVisibilityChanged. If you have an exit transition, you can also listen for the end of it as well. You just need some trigger that will tell you to reset the state so that the ImageView is removed and your custom View should draw the image again.
In the example above, I placed the ImageView in the same parent as the custom View. You may get more flexibility by putting it into the DecorView, but you'll have to figure out what the global position is and it will also overlay everything on the screen. Alternatively, since I added the ImageView to the parent, that won't work for all parents (e.g. ListView, LinearLayout). You know your View hierarchy and you'll have to choose the best place to put it.
Or, you could change your custom View to be a custom ViewGroup and contain the sharable image as an ImageView! Sounds easier to me.

How to handle exception while clicking link using textview in android

I am working on an android project in which i have to add links i am following the given below example.. But when i am clicking on the link neither it is highlighting nor i am able to access the link. Clicking on the link is causing an exception which says
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
I want to open the link in the browser when i am clicking on the link.How to do it efficiently?. I am expecting an answer soon !Thank you
NB: i am using a dynamic textview in my actual project
public class StackOverflowActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView link = new TextView(getApplicationContext);
String linkText = "Visit the <a href='http://stackoverflow.com'>StackOverflow</a> web page.";
link.setText(Html.fromHtml(linkText));
link.setMovementMethod(LinkMovementMethod.getInstance());
}
Use android:autoLink="web" in your TextView xml. And if it does not work, try android:linksClickable="true"
Based on your error, if using dynamic TextView make sure you refer your view with this object as
TextView yourView = new TextView(this);
this refers to your Activity context where I think you might have made a little mistake.
You should not use getApplicationContext for creating a view with Activity context.
I believe you have to inflate the layout that contains your TextView before you can use it, like so:
getActivity().getLayoutInflater()

Categories