Android - restart part from onCreate - java

In my program, I'm creating shapes which are filled with random colors from a list. The colors are set in onCreate. I don't want it to have determined colors, but to change the colors multiple times. How do I 'restart' the onCreate part, so the colors are allocated again?
public class MainActivity extends Activity implements OnGestureListener
{
private Paint paint = new Paint();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Canvas canvas = new Canvas(bg);
List<Integer> numbers = Arrays.asList(Color.RED, Color.BLUE, Color.GREEN, Color.YELLOW);
Collections.shuffle(numbers);
}
}

Here is the trick, call this method
loadColors();
in oncreate and anywhere else u want
public class MainActivity extends Activity implements OnGestureListener
{
private Paint paint = new Paint();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Canvas canvas = new Canvas(bg);
loadColors();
}
private void loadColors(){
List<Integer> numbers = Arrays.asList(Color.RED, Color.BLUE,
Color.GREEN, Color.YELLOW);
Collections.shuffle(numbers);
}
}

this may help you, just put in your onResume or the method you want to restart oncreate from
onCreate(new Bundle());
for example by clicking a button like this
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onCreate(new Bundle());
}
});

If you are trying to change the colors when you navigate from one activity to another then you can probably try wrapping up your code for changing the colors in a function and call that function in onResume() (one of the life cycle methods of an activity). onResume() will be called every time when your activity is loaded.

Related

sharing a specific image from slider made by viewpager

I have made image slider using viewPager and picasso. Images are loaded from my own(raw). I've put share button below image.
I want to make specific image be shared using share intent. I mean, if I'm in image of position 3 then only image of position 3 should be shared.
Activity where image slider is shown:
public class RajeshDaiActivity extends AppCompatActivity{
ViewPager viewPager;
private int[] imageUrls = new int[]{
R.drawable.oq,
R.drawable.oqqqq,
R.drawable.opt3
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rajesh_dai);
viewPager = findViewById(R.id.view_pager);
ViewPageAdapter adapter = new ViewPageAdapter(this, imageUrls);
viewPager.setAdapter(adapter);
ImageView ShareButton = findViewById(R.id.share);
ShareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent share = new Intent("android.intent.action.SEND");
//?? how??
}
});
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
}
From the code posted above, it looks like you need to implement an interface and capture the click event of the particular image and implement the logic for redirection in overridden implementation of the particular function in your fragment class. Hope this clarifies your question.

Closing a view class and opening another view class

I call a view class from my activity. Then the view class calls the same activity. Here is the problem, once the activity comes back up, it won't register any more button pushes.(I'm trying to call another view class. Here is some code:
View Class
public class AnimationView extends View {
Activity myActivity;
//...
public AnimationView(Context context, Activity activity) {
super(context);
//...
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//...
myActivity.setContentView(R.layout.activity_home);
}
}
Home Activity
public class HomeActivity extends AppCompatActivity {
private AnimationView mDrawViewA;
///...
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDrawViewA = new AnimationView(this,this);
start = (Button) findViewById(R.id.startButton);
//...
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//...
setContentView(mDrawViewA);
//calls more views
//......
});
}
I realize now maybe I should have been calling the view classes in different activities, but I would very much like a get all the view classes working within the same activity.
The problem is you're calling setContentView every time you press the "start" button. This method will overwrite the current layout (if any) with the new value you're setting.
What you can do to get the result you're expecting, which, from what I understand, is to add a new AnimationView to your current layout on every button click, you can try something like this:
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AnimationView animationView = new AnimationView(getApplicationContext());
// I'm using ConstraintLayout as an example, since I don't know exactly what layout you're using
ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
// Set the layout params the way you want
addContentView(animationView, params); // This is where the magic happens
}
});
In short, addContentView is the method you should use when you want to add new views into your activity's root layout.
PS.: It's a terribly bad practice to let the views "know" the activity controlling it. It's always the opposite way around: the activity/fragment knows the view(s) it's controlling.

How to get Button Value from another class on android studio

I have 2 class, which the first class i created Loop button
and second class i want to get button value from first class..
Here is my code
public class FirstClass extends AppCompatActivity {
public static Button[] btn = new Button[8];
#Override
protected void onCreate(Bundle savedInstanceState) {
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.rlid);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
for(int i=0; i<btn.length; i++)
{
btn[i] = new Button(this);
btn[i].setTextColor(Color.BLUE);
btn[i].setText((i + 0) + " ");
btn[i].setLayoutParams(lp);
relativeLayout.addView(btn[l]);
}
}
}
public class SecondClass extends Activity {
Button btn2= (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Button bb = FirstClass.btn[2]; //get button no 2 from 1st class
bb.setTextColor(Color.YELLOW); // try to change into yellow but nothing happen
}
});
Although bad practice of using views as static fields, your code should work.
Another problem is that you have created buttons in the first activity and done nothing with them. You should probably add them to some layout of the activity.
The good practice would be not to store buttons or any views in static fields, and get results using Intents. https://developer.android.com/training/basics/intents/result.html

how to use onSaveInstanceState button that change the background layout?

I'm new to android develop. i just stated this week.
i dont know if im asking stupid question but i want to learn.
i have created an app just click a button change the background color.
my layout is this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/background"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.seluhadu.colorpicker.MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="136dp"
tools:layout_editor_absoluteY="1dp"
android:elevation="8dp"
android:layout_alignBaseline="#+id/button3"
android:layout_alignBottom="#+id/button3"
android:layout_alignParentEnd="true"
android:layout_marginEnd="52dp"/>
</RelativeLayout>
and i have a class "java" like this
public class MainActivity extends AppCompatActivity {
Button button;
RelativeLayout relativeLayout;
Integer[] colors = {
R.color.color1,
R.color.color2,
R.color.color3,
R.color.color4,
R.color.color5,
R.color.color6,
R.color.color7,
R.color.color8,
R.color.color9,
R.color.color10,
R.color.color11,
R.color.color12,
R.color.color13,
R.color.color14,
R.color.color15,
R.color.color16,
R.color.color17,
R.color.color18,
R.color.color19,
R.color.color20
};
Random random;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
random = new Random();
relativeLayout = (RelativeLayout) findViewById(R.id.background);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
relativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(),
colors[random.nextInt(colors.length)]));
}
});
}
it just change the background color random.
when it change the color if i rotat the screen it change to default back.
my question is how to make a onSaveInstanceState and onRestoreInstanceState method to save the change color even if i reopen the app to stay the color that i change.
OR how can i do like that in other way?
thank you for your help!
When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system
passes your activity. Both the onCreate() and onRestoreInstanceState()
callback methods receive the same Bundle that contains the instance
state information.
Because the onCreate() method is called whether the system is creating
a new instance of your activity or recreating a previous one, you must
check whether the state Bundle is null before you attempt to read it.
If it is null, then the system is creating a new instance of the
activity, instead of restoring a previous one that was destroyed.
public class MainActivity extends AppCompatActivity {
Button button;
RelativeLayout relativeLayout;
Integer[] colors = {
R.color.color1,
R.color.color2,
R.color.color3,
R.color.color4,
R.color.color5,
R.color.color6,
R.color.color7,
R.color.color8,
R.color.color9,
R.color.color10,
R.color.color11,
R.color.color12,
R.color.color13,
R.color.color14,
R.color.color15,
R.color.color16,
R.color.color17,
R.color.color18,
R.color.color19,
R.color.color20
};
Random random;
Boolean backgroundChanged = false;
int colorIndex;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore background color from saved state
backgroundChanged = savedInstanceState.getBoolean("backgroundChanged", false);
colorIndex = savedInstanceState.getInt(colorIndex, 0);
}
random = new Random();
relativeLayout = (RelativeLayout) findViewById(R.id.background);
if(backgroundChanged) {
relativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), colors[colorIndex]));
}
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
backgroundChanged = true;
colorIndex = random.nextInt(colors.length);
relativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), colors[colorIndex]));
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean("backgroundChanged", backgroundChanged);
if(backgroundChanged) {
savedInstanceState.putInt("colorIndex", colorIndex);
}
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Update
Here's my code below, plugged into your posted example:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
random = new Random();
relativeLayout = (RelativeLayout) findViewById(R.id.background);
button = (Button) findViewById(R.id.button);
SharedPreferences settings = getSharedPreferences("myPrefs", 0);
int colorIndex = settings.getInt("colorIndex", 0);
updateBackground(colorIndex);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int colorIndex = random.nextInt(colors.length);
SharedPreferences settings = getSharedPreferences("myPrefs", 0);
settings.edit().putInt("colorIndex", colorIndex).apply();
updateBackground(colorIndex);
}
});
}
private void updateBackground(int colorIndex) {
relativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), colors[colorIndex]));
}
If you have to store the color even through app restarts, you should use SharedPreferences instead of using onSaveInstanceState().
In your onClick(), when you generate the random index for your color array, write that value to your SharedPreferences object. In onCreate() when you set everything up, read the value out of the SharedPreferences.
To write:
int colorIndex = random.nextInt(colors.length);
SharedPreferences settings = getSharedPreferences("myPrefs", 0);
settings.edit().putInt("colorIndex", colorIndex).apply();
To read:
SharedPreferences settings = getSharedPreferences("myPrefs", 0);
int colorIndex = settings.getInt("colorIndex", 0);

Extending a second GameView in Android

I'm making an application on Android which is to contain 2 games. I've done this but I've come across a problem that the two buttons that are supposed to extend to different GameViews are extending to the same GameViews. The classes both have different names and I've tried changing some of the content to specifically refer to the BallGameView class however it causes the program not to compile. I've had a look around to see if there's anything on extending to 2 separate GameViews in a single application but not came across anything so far.
EDIT: For clarity, the problem is that the buttons that should open different games are opening the same game. The game is compiling but not as I want it to. I'll post the code that's referring to the different games below.
public class BallGameActivity extends Activity {
GameView GV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ballgame);
GV = new GameView(this);
setContentView(GV);
To refer to Ball Game.
public class BallSplash extends Activity implements View.OnClickListener {
Button playBallButton;
Button guideButton;
Intent ballIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ball_splash);
playBallButton = (Button)findViewById(R.id.startBallGame);
guideButton = (Button)findViewById(R.id.guideButton);
playBallButton.setOnClickListener(this);
guideButton.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.startBallGame:
ballIntent = new Intent(this,BallGameActivity.class);
startActivity(ballIntent);
break;
case R.id.guideButton:
ballIntent = new Intent(this,Guide.class);
startActivity(ballIntent);
break;
}
}
To refer to Sprite Game
public class Splash extends Activity implements View.OnClickListener {
Button playButton;
Button instructionButton;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
playButton = (Button)findViewById(R.id.toPlay);
instructionButton = (Button)findViewById(R.id.toInstructions);
playButton.setOnClickListener(this);
instructionButton.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.toPlay:
intent = new Intent(this,GameActivity.class);
startActivity(intent);
break;
case R.id.toInstructions:
intent = new Intent(this,InstructionActivity.class);
startActivity(intent);
break;
}
}
Maybe the problem exists because you call setContentView() twice. You should remove the wrong one.
The correct way to do it is to call that class that you want to use as the view
BallGameView GV = new BallGameView(this);
setContentView(GV);
in your current code you are instantiating GameView but that isn't what you want for this Activity. You need to instantiate BallGameView GV instead. Since you are using
GV = new GameView(this);
setContentView();
in both Activities, you are seeing the same thing no matter which Activity you start. So the problem was never with starting an activity or extending anything.
Also, you can remove
setContentView(R.layout.activity_ballgame);
That line will set the Activity to use that layout. But since you are calling setContentView() again and using the class which extends SurfaceView then it will set the Activity to use that as the layout instead, making the above line useless.

Categories