I have successfully set an image to an ImageButton using this code:
mGetClickTime.setImageResource(randomImageId);
But I'm trying to problematically change the image by calling a method which contains:
mGetClickTime.setImageResource(randomImageId);
(In which the randomImageId vraiable is different)
However the programmatic change is not working.
Do I need to remove the current image before setting a new one? If so, how do I do that?
EDIT
The problem seems to be that the above command stops working after another activity has been called and completed. After that happens the setImageResource just doesn't work.
I'm not sure why this could be. I've tried commenting out everything from the second activity apart from this
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
but the problem still occurs. Why?
Give this a try:
mGetClickTime.setBackgroundResource(randomImageId);
This will work in an onClick method. That might be your issue, but not 100% sure until I see the context of the code.
Related
I am writing this cause I was searching for days to get an answer on my question but I didn't find any answers . . .
I am like for a month using android studio and everything is going perfect but . . . I cant find an solution to something, I added some buttons into a layout and I wat that when I click on the button it redirects me to my Webview. I want to use only one Webview and every time when I click one of the buttons it had to go to another website in the Webview. I tried many of things I found on SO but couldn't find the right answer.
Could you please help me?
Call WebView's loadUrl() method inside the listeners of your buttons:
my_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
my_webView.loadUrl("www.some_url.com");
}
});
You can always change your webview's url to what you need depending on the button you clicked.
I fixed it.. I had to do this in the webview activity:
public class Webview extends Activity {
Sorry had the wrong activity at the end!
I have an ImageView on an Activity A, and a button on Activity B.
The ImageView is set to "invisible". I was wondering if i could make the ImageView visible when the button is pressed and keep visible forever (until the user uninstalls the app or resets it).
I found this piece of code that makes the ImageView turn visible:
example.setVisibility(View.VISIBLE);
i know i should use SharedPreferences to make it work, but i tried many times, without success.
Can somebody help me?
Thank you so much.
P.s. What i have to do is to create (or simply make visible) a tick so that the user knows which level he completed. If there's another way, and i know there is, let me know.
It seems you have set the visibility of your ImageView in XML using
android:visibility="invisible"
Instead of that always set the visibility in code using something like -
SharedPreferences sharedPreferences;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedPreferences = getSharedPreferences(getString(R.string.sp_key),
MODE_PRIVATE);
ImageView example = (ImageView) findViewById(R.id.example_image);
boolean visible = sharedPreferences.getBoolean(R.string.visible, false);
if (visible) {
example.setVisibility(View.VISIBLE);
} else {
example.setVisibility(View.INVISIBLE);
}
}
Then where the user clicks on a checkbox or something to show they want to make your ImageView visible, save this to the SharedPreferences.
Have a look at How to use SharedPreferences in Android to store, fetch and edit values for more details on SharedPreferences example.
I solved. Rnk's method is the key. It returned error because i was using findViewById with an object from another Layout and it returned null point. So i imported the layout where the imageView is, and i solved. THANK YOU.
I'm currently trying to learn to work with Views and states. I'm normally able to set its color in functions like in the following:
View mColorRegion = findViewById(R.id.color_region);
mColorRegion.setBackgroundColor(Color.CYAN);
However, I can't seem to be able to set the color in an onRestoreInstanceState(), as
mColorRegion.setBackgroundColor(savedInstanceState.getInt("color"));
However, working with the same View as a TextView, I'm able to restore text as in the following:
TextView mText = (TextView)findViewById(R.id.color_region);
mText.setText(savedInstanceState.getString("text");
What's the difference, and how I can set the background color in onRestoreInstanceState()?
EDIT: Since the original post, I've noticed two things:
1) mColorRegion.setBackgroundColor(Color.CYAN) doesn't seem to work in onCreate() either.
2) Even though the following function correctly changes the View color when a button is pressed, it doesn't work if I call it directly from onRestoreInstanceState():
public void centerButton1(View clickedButton) {
mColorRegion.setBackgroundColor(Color.CYAN);
}
Hmm...
So I found a "half-solution". If you add the following line to AndroidManifest.xml, it will preserve the color during orientation changes:
android:configChanges="orientation|screenSize"
However, this still doesn't answer why I can set the text but not the color in onRetoreInstanceState() or onCreate()...
Many people frown upon using android:configChanges="orientation|screenSize", like Google's Dianne Hackborn. For one, It will make the process of switching between multiple layouts for your app very difficult (for example, if you want one layout for landscape, and one for portrait) since you'll have to do all of the work that Android normally does automatically for you, in onConfigurationChanged().
Anyway, I also had this sort of problem. I was creating a DialogPreference, and upon rotation I couldn't change the progress of a SeekBar in onRestoreInstanceState(savedInstanceBundle)...so this is what I suggest if you cannot use onCreate(savedInstanceBundle) or onActivityCreated(savedInstanceBundle) (for fragments) to restore the state of your view objects:
1) Make a private class member called "mRestoredBGColor",
private int mRestoredBGColor = -1;
2) In onRestoreInstanceState():
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
mRestoredBGColor = savedInstanceState.getInt("key_you_used_in_onSaveInstanceState");
}
3) Then in onResume(), because onRestoreInstanceState() is called after onStart(), but before onResume()
#Override
public void onResume(){
super.onResume();
if(mColorRegion != null && mRestoredBGColor != -1){
mColorRegion.setBackgroundColor(mRestoredBGColor);
mRestoredBGColor = -1; //to make sure it only sets this once per rotation.
}
}
Hope this helps somebody. I believe there is always another way (except when you want quickly rotating WebViews...) than using android:configChanges="orientation|screenSize".
My app have two different layout for portrait and landscape mode which both encapsulate a webview and some buttons. Buttons are at bottom in portrait and at left in landscape so more reading space is available in webview.
The problem is, the activity is recreated on screen rotation and webview loads the first page which is not a wanted behavior.
I searched and found out using android:configChanges="orientation" in activity tag prevents recreating of the activity. But the porblem is it prevents the layout changing too as it happens in activity creation.
I want my program to work in 2.2, waht's the best way to this?
I tested fragments, but dealing with fragment makes things much more complex and the fragment itself needs saving and restoring which may not work in a webview which has javascript state, So I searched more and find a nice article somewhere and with some modification I came to a solution which I suggest:
First, add android:configChanges="orientation|screenSize|keyboard|keyboardHidden" to manifest so app handles the config change instead of android.
Make two different layout for lnadscape and portrait mode and put them in corresponding layout folders. In both layouts instead of webview place a LinerLayout which acts as a placeholder for webview.
In code define initUI method like this and put every thing related to UI initialization in this method:
public void initui()
{
setContentView(R.layout.main);
if (wv == null) wv = new WebView(this);
((LinearLayout)findViewById(R.id.webviewplace)).addView(wv);
findViewById(R.id.home).setOnClickListener(this);
}
If the webview doesn't exist, it will be created and after setContentView(R.layout.main) it will be added to the layout. Other UI customization came afterward.
and in onConfigurationChanged:
#Override
public void onConfigurationChanged(Configuration newConfig)
{
((LinearLayout)findViewById(R.id.webviewplace)).removeAllViews();
super.onConfigurationChanged(newConfig);
initUI();
}
In onConfigChange First the webview is removed from old place holder and initui will be called which will add it back to the new layout.
and in oncreate call initui so the ui will be initialized for the first time.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
initUI()
}
Could you not save the last loaded URL in the webview in onSaveInstanceState(Bundle outState) and then make sure to reload it onRestoreInstanceState(Bundle savedInstanceState) using myWebview.loadUrl(restoredUrl)?
edit I know that this might not work if the web page you are displaying requires a state to be kept. But if not it should be a solution to your problem.
From this document https://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange
I just edited manifest with android:configchanges so it works fine for me.
<activity android:name=".Webhtml"
android:configChanges="orientation|screenSize"/>
I have a problem that I can't seem to find the solution to.
I have an app that loads the main.xml file on startup, of course. In it are several buttons, and I want the buttons to take me to a different XML file. I just used setContentView(R.layout.newlayout.xml) method for that, and it works great.
The problem comes in after that. If I reference any of the buttons or other objects in the new layout, the app won't even finish loading before it errors out and closes on the emulator. However, if I take all references to objects out, the app runs fine.
I can navigate TO the new layouts, but their buttons can't do anything. Do I need to create a separate Java file for each layout? Or am I doing it all wrong? I'm trying to be as specific as I can. I suppose you could say I need to have different "pages" in my app as a website would.
I think what you are trying to do is best solved using multiple java files, each one defining it's own android Activity.
While it is possible to have multiple layouts/views in a single activity, this will generally make the code more complex and harder to read/debug in the future. By having each 'screen' in its own file, it will be a bit easier to manage all the different views you need to juggle.
The buttons and views only can refer to those mentioned in the current SetContentView() file..
u can test this by creating a button and initialising to an R.id... without setting the content view.. U will get a force close..
so if u change the XML file u shud initialise stuff again....
Ok, for anyone out there with the same problem and haven't figured out how to do it, as I said in my comment on ylebre, my Coworker and I have finally discovered how to do it. First off, we added
implements OnClickListener
to the class, after
extends Activity
then, we created a new java file, and at the beginning of the file it called
setContentView(R.layout.newlayout);
instead of main. Then, we made a button as follows:
Button button1 = (Button) findViewById(R.id.button01;
button1.setOnClickListener(this);
then later in the code:
public void onClick(View v) {
switch(v.getId()) {
case R.id.button01:
startActivity(new Intent(this, NEWJAVAFILE.class));
break;
}
}
And that's it! We just copied and pasted that code into NEWJAVAFILE, changed the names and such, and we were able to navigate freely back and forth. As ylebre said, all of the code for the new activity is in the NEWJAVAFILE.java. OH and don't forget to add the name of the java file to the manifest inside the tags:
<activity android:name=".NEWJAVAFILE">
</activity>
it all seems so simple now!