I am using two activities, in first activity I am using the code below for starting second Activity
Intent i = new Intent(getBaseContext(), ViewPerson.class);
startActivity(i);
overridePendingTransition(Resource.Layout.trans_right_in, Resource.Layout.trans_right_out);
Finish();
Then in second activity onCreate Method I am using the code below for changing activity orientation
public void onCreate(Bundle savedInstanceState)
{
if(Parameters.Landscape) //Parameters is a static class
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
super.onCreate(savedInstanceState);
setContentView(R.layout.filters);
}
The problem is that in that case my animation doesn't work. It works only in PORTRAIT MODE.
I change the orientaion using the following code, and I have no issue.
private void Btn2_Click(object sender, System.EventArgs e)
{
RequestedOrientation = ScreenOrientation.Landscape;
}
private void Btn1_Click(object sender, System.EventArgs e)
{
RequestedOrientation = ScreenOrientation.Portrait;
}
Related
I want to let users choose background colors with animation in BackgroundActivity and saving that changed background color into MainActivity.
When a user clicks backgroundChange button on MainActivity, it moves to BackgroundActivity. Then there are a few different colors to choose. After a user click Save button after choosing color on BackgroundActivity, it is going back to MainAcitivity. My problem is I don't know how to save that changed background color from BackgroundAcivity to MainAcivity.
As a beginner, I cannot understand well how to use SharedPreferences.
I checked several videos and searching many questions for hours about it, but still, I cannot figure out how to use SharedPreferences correctly on my own code.
BackgroundAcivity is really long that I will only put the first part. Could you tell me how to save this background change?
MainActivity
public class MainActivity extends AppCompatActivity {
Button backgroundChange;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
backgroundChange = findViewById(R.id.backgroundChange);
backgroundChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, BackgroundActivity.class);
startActivity(intent);
}
});
}
}
BackgroundActivity
public class BackgroundActivity extends AppCompatActivity {
Button btn_blue, btn_purple, btn_orange, btn_save;
View holderBg, dynamicBg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_background);
btn_save = findViewById(R.id.btn_save);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BackgroundActivity.this, MainActivity.class);
startActivity(intent);
}
});
btn_blue = findViewById(R.id.btn_blue);
btn_purple = findViewById(R.id.btn_purple);
btn_orange = findViewById(R.id.btn_orange);
holderBg = findViewById(R.id.holderBg);
dynamicBg = findViewById(R.id.dynamicBg);
//set the first-time background
holderBg.setBackgroundResource(R.drawable.bg_blue);
holderBg.setScaleY(3);
holderBg.setScaleX(3);
//set the scale of button clicked
btn_blue.setScaleY(1.5f);
btn_blue.setScaleX(1.5f);
btn_blue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//scale animation
btn_blue.animate().translationY(20).scaleX(1.5f).scaleY(1.5f).setDuration(800).start();
//default the scale buttons
btn_purple.animate().translationY(0).scaleX(1).scaleY(1).setDuration(350).start();
btn_orange.animate().translationY(0).scaleX(1).scaleY(1).setDuration(350).start();
//change the background
dynamicBg.animate().scaleX(3).scaleY(3).setDuration(800).start();
dynamicBg.setBackgroundResource(R.drawable.bg_blue);
//change color of button
btn_save.setTextColor(Color.parseColor("#3498db"));
//timer for change the holderbg
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
holderBg.setScaleX(3);
holderBg.setScaleY(3);
holderBg.setBackgroundResource(R.drawable.bg_blue);
dynamicBg.setScaleX(0);
dynamicBg.setScaleY(0);
}
}, 850);
}
});
}
}
You can use a bundle to transfer your data across Activity.
Saving data
Intent intent = new Intent(context, YourActivity.class);
intent.putExtra(KEY, "your value here");
startActivity(intent);
Then to retrieve data.
Intent intent = getIntent();
if (intent != null ) { //Null Checking
String strData= intent.getStringExtra(KEY);
// do your work with `strData`
}
I'm making an Android whack a mole game. I have the main activity which is basically the launcher, when you press the Play button the game activity starts. This works fine as it shows the background image and all molehills but I don't know how to call the method to start the game.
I've tried to call it from inside onCreate() but this ends up "playing the game" itself.
I've tried to call it right after the startActivity(intent) but the app crashes. And also I've tried to create an instance of the game class and call the play() method after the start activity but it doesn't work aswell. I don't know how to start the game method once the game activity is loaded.
I hope I explained well, thank you.
public class MainActivity extends AppCompatActivity {
ImageButton btnStart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide TitleBar
try { this.getSupportActionBar().hide();}
catch (NullPointerException e){}
setContentView(R.layout.activity_main);
btnStart = (ImageButton)findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), GameView.class);
startActivity(intent);
}
});
}
And this is the code for the game_activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide TitleBar
try { this.getSupportActionBar().hide();}
catch (NullPointerException e){}
setContentView(R.layout.activity_game_view);
game();
}
The game() method is a typical game loop.
public void game() {
Random random = new Random();
int index;
/*
* Casting array to store all ImageView on the game
*/
imgViewArray[0] = (ImageView)findViewById(R.id.img1);
imgViewArray[1] = (ImageView)findViewById(R.id.img2);
imgViewArray[2] = (ImageView)findViewById(R.id.img3);
imgViewArray[3] = (ImageView)findViewById(R.id.img4);
imgViewArray[4] = (ImageView)findViewById(R.id.img5);
imgViewArray[5] = (ImageView)findViewById(R.id.img6);
imgViewArray[6] = (ImageView)findViewById(R.id.img7);
imgViewArray[7] = (ImageView)findViewById(R.id.img8);
imgViewArray[8] = (ImageView)findViewById(R.id.img9);
imgViewArray[9] = (ImageView)findViewById(R.id.img10);
int j=0;
while (j < 10) {
// Get a random image to animate
index = random.nextInt(10);
switch(index) {
case 0: imgViewArray[0].setImageResource(images[6]);
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
imgViewArray[0].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgViewArray[0].setImageResource(images[0]);
}
});
}
},
300 // The code executes after 300ms
);
break;
I think you should put the game() call inside onResume().
There are many ways to solve the problem:
Using EventBus
Send the start game Event from Main Activity and register for the Event in the Game activity.
This is my favorite way to handle the problem. It's because the simplicity and prevent us from tightly coupled code. The major problem with using EventBus is we will lost in the sea of Event if there are too much Event in the the app.
How to do:
First, create the Event. This is just a simple class:
public class StartGameEvent {
}
Second, register for the event in the game activity:
public class GameActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
EventBus.getDefault().register(this);
}
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
Third, subscribe for the event:
public class GameActivity extends Activity {
...
#Subscribe
public void onMessageEvent(StartGameEvent event) {
game();
}
}
Last, send the event from Main activity:
EventBus.getDefault().post(new StartGameEvent());
Using LocalBroadcastManager
You need to create the message and broadcast it in from your Main activity:
Intent intent = new Intent("playEvent");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Then, in the game activity, you need to register as receiver:
#Override
public void onCreate(Bundle savedInstanceState) {
// register for the event
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
new IntentFilter("playEvent"));
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
game();
}
};
#Override
protected void onDestroy() {
// Unregister here
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(mReceiver);
super.onDestroy();
}
I slightly modifying the code from How to use LocalBroadcastManager? for your case.
Using a static method in Game activity
This is the simplest way but highly discouraged. Because we can't ensure the state of the activity. Do not use this in production code. This is for learning sake only.
You can make the game() method as a static method like this:
public class GameActivity extends Activity {
...
public static void game() {
// game logic.
}
}
Then call the method when you want with:
GameActivity.game();
I have this Activity:
public class WelcomeActivity extends ActivityBase {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.welcome);
final OnClickListener Click = new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(WelcomeActivity.this, WelcomeDoneActivity.class);
startActivityForResult(intent, 0);
setResult(RESULT_OK);
finish();
}
};
((TitleBar)findViewById(R.id.theTitleBar)).setOnClickCloseListener(Click);
}
And this test:
#Test
public void clickingLogin_shouldStartLoginActivity() {
WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class);
activity.findViewById(R.id.theTitleBar).performClick();
Intent expectedIntent = new Intent(activity, WelcomeDoneActivity.class);
assertThat(shadowOf(activity).getNextStartedActivity(), equalTo(expectedIntent));
}
how come I get an assertion error?
java.lang.AssertionError:
Expected: <Intent { cmp=com.w/.profile.WelcomeDoneActivity }>
but: was null
Update
I have tried this as well but the startedIntent == null
ShadowActivity shadowActivity = shadowOf(activity);
Intent startedIntent = shadowActivity.getNextStartedActivity();
// ShadowIntent shadowIntent = shadowOf(startedIntent);
// String name = startedIntent.getIntentClass().getName();
// assertThat(shadowIntent.getIntentClass().getName(), equalTo(targetActivityName));
Change:
shadowOf(activity).getNextStartedActivity()
To:
shadowOf(activity).getNextStartedActivityForResult()
In the code you posted, you are setting the onClick on the TitleBar via setOnClickCloseListener.
It looks like your TitleBar is a custom view, and the setOnClickCloseListener to me implies there is a 'close' button or view on the TitleBar that performClick() should be called on, not the TitleBar itself, in order for Robolectric to behave the way you expect.
It's hard to tell without knowing the TitleBar and setOnClickCloseListener implementation, but:
1) If you just want to click the TitleBar to launch the new activity,
then change setOnClickCloseListener to setOnClickListener,
Or
2) If the TitleBar contains a view of the close button/view (or whatever "ClickClose" refers to in setOnClickCloseListener!), delve into the TitleBar layout to find the ID of this view, and call performClick on that, it should resolve your issue.
Hi so even though I have seen a couple of topics about linking activities or returning I can not get my return back to activity to work. I abit of back ground the the app when the user gets an answer wrong or runs out of time it goes to game over taking the score across with it and displaying it on the game over, here's the working code for that if it helps solve my issue:
Main Class:
public void fail(){
{
Intent myIntent = new Intent(MainActivity.this,gameover.class);
myIntent.putExtra("number", score);
MainActivity.this.startActivity(myIntent);
finish();
}
gameover class:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
re_run = (Button) findViewById(R.id.retry);
EndScore = (TextView) findViewById(R.id.show);
int getVal;
getVal = getIntent().getExtras().getInt("number");
String s = String.valueOf( getVal );
EndScore.setText(s);
}
Now the reason I shared the above working code because I have the feeling the intent that takes the user and score to the gameover screen, is messing with the retry/return code as shown below:
private void setButtonOnClickListeners(){
re_run.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent retry = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(retry);
}
});
}
From what I can find from those topics these seems to be the correct method. but when the code is run the re_run button does nothing. Any help?
You use "setButtonOnClickListeners()" to implement setOnClickListener and so override the onClick. But when did you call setButtonOnClickListeners?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover); re_run = (Button)
findViewById(R.id.retry);
EndScore = (TextView) findViewById(R.id.show);
int getVal;
getVal = getIntent().getExtras().getInt("number");
String s = String.valueOf( getVal );
EndScore.setText(s);
setButtonOnClickListeners();
}
You can maybe check that your OnClick is working correctly adding a log line in LogCat. Log.d("GameOver", "Retry onclick ok");
You are finding a view before it was inflated (R.id.retry).
Change the sequence of commands to:
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
re_run = (Button) findViewById(R.id.retry);
Also try changing the intent to:
Intent retry = new Intent(GameOver.this, MainActivity.class);
retry.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
I personally used startActivityForResult(Intent) to start the game over screen, and once the player inputted his name or pressed something or quit the activity with Back, then it returned a value to onActivityResult(..) in which I called finish().
EDIT:
Game ends, so I started activity using
Intent i = new Intent();
i.putExtra("Score", scoreCount);
i.setClass(context, HighScoreInputActivity.class);
context.startActivityForResult(i, 0);
Then when you insert the scores and stuff, you close the game screen in GameActivity with
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
this.finish();
}
I have three images with me and i want them to appear on first layout xml like a splash view so that they can be viewed only once i.e that activity will be called only once when app get's installed or if app get's a new update otherwise app should always start from the Second activity, i don't know how should i begin with this :
Can any one tell me any idea how this can be done.
To show splash for only once.
Next part of this question is here
Coding will be much appreciated.
Save a flag in the Preferences when you start up the application, after you've done the welcome screen stuff. Check for this flag before you show the welcome screen. If the flag is present (in other words, if it's not the first time), don't show it.
In your activity:
SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// second argument is the default to use if the preference can't be found
Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);
if (!welcomeScreenShown) {
// here you can launch another activity if you like
// the code below will display a popup
String whatsNewTitle = getResources().getString(R.string.whatsNewTitle);
String whatsNewText = getResources().getString(R.string.whatsNewText);
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(whatsNewTitle).setMessage(whatsNewText).setPositiveButton(
R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference
}
}
Try this :
public class MainActivity extends Activity {
private Thread mSplashThread;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
final MainActivity sPlashScreen = this;
mSplashThread = new Thread() {
#Override
public void run() {
try {
synchronized (this) {
wait(4000);
}
} catch (InterruptedException ex) {
}
finish();
Intent intent = new Intent();
intent.setClass(sPlashScreen, StartNewActivity.class);// <-- Activity you want to start after Splash
startActivity(intent);
}
};
mSplashThread.start();
} catch (Exception e) {
}
}
#Override
public boolean onTouchEvent(MotionEvent evt) {
try {
if (evt.getAction() == MotionEvent.ACTION_DOWN) {
synchronized (mSplashThread) {
mSplashThread.notifyAll();
}
}
} catch (Exception e) {
}
return true;
}
}
you put an Image in splash.xml to show
to do this you have to detect the first launch of your application. To do so you can store a boolean value as #Nirav suggested.
And for the splash screen, You can consider using Fragments and ViewPager to create an activity which will only be shown for the first time