I have listactivity app forming many rows , one row is images Slideshow , when you click
the row open activity showing ImageView , also there is optionmenu of one item which is( slideshow animation setting ), when you click it , it open checkbox preference
animations screen with multiple checkboxes each one apply different animation to images
slideshow ,where user determine either to slide images with many animations available by
check its checkbox animation name or when uncheck all the checkboxs so the slideshow activity
must show images in viewpager pattern .
android:defaultValue="true" for first animation which is fade_in animation.
BUT: when you open slideshow activity its open the images in imagepager pattern ,and ignoring android:defaultValue="true" for fade_in checkbox,
then after go to preference screen to choose another animation then back to slideshow
activity , it doesn't apply the new animation , i have to press back button many times
till finish all images scrolled in pager then it apply the next animation ,
and sometimes it stuck on image pager and freeze's ,the normal behavior is applying
the next animation once press back button which return to slideshow .
another thing when i was in image viewpager pattern and scroll it ,
it scroll a few number of images then back to first image then i scroll images again
and suddenly it back to first image one and so on .
whole project can be downloaded from here
any help will be appreciated.
SlideShow.java
public class SlideShow extends Activity {
public int currentimageindex=0;
Timer timer;
TimerTask task;
ImageView slidingimage;
private int[] IMAGE_IDS = {
R.drawable.day_one_1, R.drawable.day_one_2, R.drawable.day_one_3,
R.drawable.day_one_4, R.drawable.day_one_5, R.drawable.day_one_6,
R.drawable.day_one_7, R.drawable.day_one_8, R.drawable.day_one_9,
R.drawable.day_one_10, R.drawable.day_one_11, R.drawable.day_one_12,
R.drawable.day_one_13, R.drawable.day_one_14, R.drawable.day_one_15,
R.drawable.day_one_16,R.drawable.day_one_17,R.drawable.day_one_18,
R.drawable.day_one_19,R.drawable.day_one_20
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide);
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 1000; // delay for 1 sec.
int period = 8000; // repeat every 4 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
mHandler.post(mUpdateResults);
}
}, delay, period);
}
private void AnimateandSlideShow() {
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
boolean animation = getPrefs.getBoolean("animation", true);
boolean animation_one = getPrefs.getBoolean("animation_one", false);
boolean animation_two = getPrefs.getBoolean("animation_two", false);
boolean animation_three = getPrefs.getBoolean("animation_three", false);
boolean animation_four = getPrefs.getBoolean("animation_four", false);
boolean animation_five = getPrefs.getBoolean("animation_five", false);
if (animation == true) {
slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.custom_anim);
slidingimage.startAnimation(rotateimage);
}else if(animation_one == true) {
slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.fade_in);
slidingimage.startAnimation(rotateimage);
}else if (animation_two == true) {
slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.fade_out);
slidingimage.startAnimation(rotateimage);
}else if (animation_three == true) {
slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.bounce);
slidingimage.startAnimation(rotateimage);
}else if(animation_four == true) {
slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.fade_in_2);
slidingimage.startAnimation(rotateimage);
}else if (animation_five == true) {
slidingimage = (ImageView)findViewById(R.id.ImageView_slide);
slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);
currentimageindex++;
Animation rotateimage = AnimationUtils.loadAnimation(this, R.anim.flip);
slidingimage.startAnimation(rotateimage);
}else if(animation == false && animation_one == false && animation_two == false){
Intent intent = new Intent(SlideShow.this, ImagePager.class);
startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_settings:
Intent p = new Intent("com.test.test.SETTING");
startActivity(p);
break;
}
return false;
}
}
ImagePager.java
public class ImagePager extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter(this, imageArra);
ViewPager myPager = (ViewPager) findViewById(R.id.myimagepager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
private int imageArra[] = { R.drawable.day_one_1, R.drawable.day_one_2, R.drawable.day_one_3,
R.drawable.day_one_4, R.drawable.day_one_5, R.drawable.day_one_6,
R.drawable.day_one_7, R.drawable.day_one_8, R.drawable.day_one_9,
R.drawable.day_one_10, R.drawable.day_one_11, R.drawable.day_one_12,
R.drawable.day_one_13, R.drawable.day_one_14, R.drawable.day_one_15,
R.drawable.day_one_16,R.drawable.day_one_17,R.drawable.day_one_18,
R.drawable.day_one_19,R.drawable.day_one_20
};
public class ImagePagerAdapter extends PagerAdapter {
Activity activity;
int[] imageArray;
public ImagePagerAdapter(Activity act, int[] imgArra) {
imageArray = imgArra;
activity = act;
}
public int getCount() {
return imageArray.length;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater)collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_pager, null);
ImageView im=(ImageView) layout.findViewById(R.id.pager_imageView);
im.setImageResource(imageArray[position]);
((ViewPager) collection).addView(layout, 0);
return layout;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_settings:
Intent p = new Intent("com.test.test.SETTING");
startActivity(p);
break;
}
return false;
}
}
Please post the project to be work out a proper solution mean while try using this
First of all as you have declared the ImageView slidingimage; as an instance variable, declare the Animation rotateimage as an instance variables and use it as
rotateimage = AnimationUtils.loadAnimation(this, R.anim.custom_anim);
Now once you add the animation to imageview call the invalidate() method inside the if loops
slidingimage.startAnimation(rotateimage)
slidingimage.invalidate();
And in your imagePager class make ViewPager myPager as static instance variable private static ViewPager myPager and add this code to the class
public static void refreshPager(){
if(myPager != null)
myPager.invalidate();
}
And in your settings class call this method on the onBackPressed() event
#Override
public void onBackPressed() {
ImagePager.refreshPager();
super.onBackPressed();
}
EDIT
All you just need to do is this, add this code in your Slide.java file after the setContentView(R.layout.main); and before final Handler mHandler = new Handler();
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
if(getPrefs.getBoolean("Initialization", false) == false){
SharedPreferences.Editor edit = getPrefs.edit();
edit.putBoolean("animation_one", true);
edit.putBoolean("Initialization", true);
edit.commit();
}
Like this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences getPrefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
if(getPrefs.getBoolean("Initialization", false) == false){
SharedPreferences.Editor edit = getPrefs.edit();
edit.putBoolean("animation_one", true);
edit.putBoolean("Initialization", true);
edit.commit();
}
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateResults = new Runnable() {
public void run() {
AnimateandSlideShow();
}
};
int delay = 1000; // delay for 1 sec.
int period = 8000; // repeat every 4 sec.
Timer timer = new Timer
// Some more code............
The preference file was not created only ;)
EDIT 2
In you Slide.java file declare a boolean like this
public boolean loaded ;
and code your else if like this
else if(animation_one == false && animation_two == false && animation_three == false
&& animation_four == false && animation_five == false){
Intent intent = new Intent(Slide.this, ImagePager.class);
if(loaded)
startActivity(intent);
loaded = true;
}
Create a static variable in Slide.java public static TimerTask task; and in your ImagePager.java add this code if(imageArra.length-1 == position)Slide.task.cancel(); in instantiateItem() method like this
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater)collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_pager, null);
ImageView im=(ImageView) layout.findViewById(R.id.myimage);
im.setImageResource(imageArray[position]);
((ViewPager) collection).addView(layout, 0);
if(imageArra.length-1 == position)
Slide.task.cancel();
return layout;
}
Hope this works
Related
I have a Button, TextView(number) and an ImageView. Every time I press the button the number will increment. It will increment a lot faster when I hold the button.
I want to show an image at a specific number using ImageView at the same time making the button visible to INVISIBLE for a while to stop the increment.
The problem: If I press the button one click at a time then the below code functions well but as I hold down the button, the image appears for a very short while and continue with the numbers. And although the button is set invisible for 5 seconds, the numbers still increases(as the button is still hold).
MAIN CLASS
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
ImageView imageView;
int i=0;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=findViewById(R.id.imageView);
textView=findViewById(R.id.textView);
button = findViewById(R.id.button);
button.setOnTouchListener(new RepeatListener(400, 100, new View.OnClickListener() {
#Override
public void onClick(View view) {
setText();
setImage();
}
}));
}
public void setText(){
imageView.setVisibility(View.INVISIBLE);
textView.setText(""+i);
i++;
}
public void setImage(){
if(i==10){
imageView.setImageResource(R.drawable.kitten);
imageView.setVisibility(View.VISIBLE);
buttonInvi();
}
}
public void buttonInvi(){
button.setVisibility(View.INVISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
button.setVisibility(View.VISIBLE);
}
}, 5000); // where 1000 is equal to 1 sec (1 * 1000)
}
}
RepeatListener CLASS
public class RepeatListener implements OnTouchListener {
private Handler handler = new Handler();
private int initialInterval;
private final int normalInterval;
private final OnClickListener clickListener;
private View touchedView;
private Runnable handlerRunnable = new Runnable() {
#Override
public void run() {
if(touchedView.isEnabled()) {
handler.postDelayed(this, normalInterval);
clickListener.onClick(touchedView);
} else {
// if the view was disabled by the clickListener, remove the callback
handler.removeCallbacks(handlerRunnable);
touchedView.setPressed(false);
touchedView = null;
}
}
};
public RepeatListener(int initialInterval, int normalInterval,
OnClickListener clickListener) {
if (clickListener == null)
throw new IllegalArgumentException("null runnable");
if (initialInterval < 0 || normalInterval < 0)
throw new IllegalArgumentException("negative interval");
this.initialInterval = initialInterval;
this.normalInterval = normalInterval;
this.clickListener = clickListener;
}
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
handler.removeCallbacks(handlerRunnable);
handler.postDelayed(handlerRunnable, initialInterval);
touchedView = view;
touchedView.setPressed(true);
clickListener.onClick(view);
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handler.removeCallbacks(handlerRunnable);
touchedView.setPressed(false);
touchedView = null;
return true;
}
return false;
}
}
How about checking the visibility before increasing the counter
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
if(view.getVisibility() == View.VISIBLE){
handler.removeCallbacks(handlerRunnable);
handler.postDelayed(handlerRunnable, initialInterval);
touchedView = view;
touchedView.setPressed(true);
clickListener.onClick(view);
}
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if(view.getVisibility() == View.VISIBLE){
handler.removeCallbacks(handlerRunnable);
touchedView.setPressed(false);
touchedView = null;
}
return true;
}
return false;
}
Try this line
button.setVisibility(View.GONE);
instead of
button.setVisibility(View.INVISIBLE);
Just set your listener to null when you reach a specific number and show imageview and make button invisible then after 5 seconds again set your listener and make button visible
I trying to run a timer to switch Backgrounds of two relative layouts in loop if user set or unset it while app is running.
Not enough I tried to work with drawable_image.setAlpha(x) to let the Background vanish slowly while the relative layout 2 behind has an other image (afterwords switch position).
My method private void switchBackground(){} do it right well. BUT it is too much work for the device and I lose a lot of frames (15-39) so that the "slow vanish" by .setAlph(x) sometimes totally fail and not working (the pics switch just by time, like the onTick() method do not exists anymore).
I think one reason for this is the countDownTimer itself and a second that the method is (should) running in the main Activity Class. May be the third reason is the problem that I choose "setBackground" of relative Layouts instead of image showing stuff?!
I tried adding a new Class to do the "switchBackground .."- method outside, but this failed cause of "nullpointerexception" and "non-static / static" problems.
Which classes and methods would be better, so as not to lose too much frames / memory.
//"/---/" short up stuff which isn't important, but still much do there
public class MainActivity extends AppCompatActivity {
//class value
//private static final String TAG = "App";
private RelativeLayout layout_behind;
private RelativeLayout layout_front;
private CountDownTimer myCountdown;
private final int[][] matrix = new int[9][9];
private EditText sumNum;
private MediaPlayer music;
private SoundPool multiTon;
private int whoopId;
private int failId;
private int winId;
private boolean soundOn =WelcomeScreen.soundCheck;
//class MathThing, Welcome_Screen exists too
private final int[][] detected = MathThing.detected;
private final ArrayList<int[][]> returnArr = new ArrayList<>();
private int switch_draw=0;
private boolean switchDraw;
private Drawable image_2;
private Drawable image_1;
private Drawable image_3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Music
multiTon = new SoundPool(1,AudioManager.STREAM_MUSIC,0);
whoopId = multiTon.load(this, R.raw.whoop,1);
failId = multiTon.load(this, R.raw.fail, 1);
winId = multiTon.load(this, R.raw.win,1);
music = MediaPlayer.create(MainActivity.this, R.raw.backgroundmusic);
if(WelcomeScreen.musicCheck) {
music.setVolume(1, 1);
music.setLooping(true);
music.start();
}
//create/initialize some stuff and initialize layouts and images
hideAndCreate();
//switch Background
switchBackground(); switchDraw=true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// . . . settings in Toolbar
int id = item.getItemId();
switch(id){
case R.id.bla: //just cut some here to do it shorter
break;// /.../
}
return super.onOptionsItemSelected(item);
}
private void hideAndCreate(){
// /----/ create a lot of edittexts / textviews/ buttons
//initialize layouts / images
}
protected void onPause(){
super.onPause();
if(switchDraw){
myCountdown.cancel();}
music.release();
finish();
}
//method with CountDownTimer
private void switchBackground(){
//Layout Background
switch_draw=0;
layout_behind.setBackground(image_2);
int duration=15000;
int tick=250;
myCountdown = new CountDownTimer(duration, tick){
int a = 255;
public void onTick(long millisUntilFinished) {
if(switch_draw==0){
image_1.setAlpha(a);
layout_front.setBackground(image_1);
if(a>=4){a=a-4;}
}else if(switch_draw==1){
image_2.setAlpha(a);
layout_front.setBackground(image_2);
if(a>=4){a=a-4;}
}else{
image_3.setAlpha(a);
layout_front.setBackground(image_3);
if(a>=4){a=a-4;}
}
}
public void onFinish() {
if(switch_draw==0){
image_2.setAlpha(255);
layout_front.setBackground(image_2);
image_3.setAlpha(255);
layout_behind.setBackground(image_3);
switch_draw=1;
}else if(switch_draw==1){
image_3.setAlpha(255);
layout_front.setBackground(image_3);
image_1.setAlpha(255);
layout_behind.setBackground(image_1);
switch_draw=2;
}else{
image_1.setAlpha(255);
layout_front.setBackground(image_1);
image_2.setAlpha(255);
layout_behind.setBackground(image_2);
switch_draw=0;
}
a=255;
start();//loop stuff
}
}.start();
}
public void StartOnClick(View v){
//do something when the button is clicked
if(v.getId()==R.id.button1){
/---/
}else if(v.getId()==R.id.button2){
/---/
}else if(v.getId()==R.id.buttonw1){
/---/
}else if(v.getId()==R.id.buttonw2){
/---/
}else if(v.getId()==R.id.buttonw3){
/---/
}
}
private void setReset(){
/---/ //clear all
}
private void againRestart(){
/---/ //reset entries only
}
// main Method
private void numInput(){
int[][]found;
int n = 81;
int mini=1;
while(mini==1 && n>0){
TextView text;
Button but1;
int[][]nul=new int[2][81];
int[][]value=new int[3][81];
int i=-1;
int j=-1;
int a=0;
int b=0;
for(int idN=0; idN<81; idN++) {
int iDn=idN +1;
String editTextId = "editText" + iDn;
int resID = getResources().getIdentifier(editTextId, "id",
getPackageName());
sumNum=((EditText)findViewById(resID) );
if(idN%9 == 0){
i=i+1;
j=0;
}else{
j=j+1;
}if(!TextUtils.isDigitsOnly(sumNum.getText()) ||
sumNum.getText ().toString().equals("0") ){
sumNum.setText("");
}
if(sumNum.getText().toString().trim().length()==0){
matrix[i][j]= 0;
nul[0][a]=i;
nul[1][a]=j;
a=a+1;
}else {
matrix[i][j] = Integer.parseInt(sumNum.getText().toString());
value[0][b]=i;
value[1][b]=j;
value[2][b]=matrix[i][j];
b=b+1;
}
}
//copy array
int[][]nuL=new int[2][a];
int[][]val=new int[3][b];
for(int u=0;u<b;u++){
val[0][u]=value[0][u];
val[1][u]=value[1][u];
val[2][u]=value[2][u];
}
for(int nu=0;nu<a;nu++){
nuL[0][nu]=nul[0][nu];
nuL[1][nu]=nul[1][nu];
}
n = nuL[0].length;
// matrix check
if(MathThing.matrixIsGood(val) && n>0){
//method matrixCheck
found = MathThing.matrixCheck(matrix, nuL);
//cut method
found = MathThing.zeroCut(found, n);
// method
int[] min = MathThing.minSearch(found);
mini = min[0];
if(min[0]==1 && n>0) {
/---/
}else if(min[0]==2 && n>0 ){
/---/
}else if(min[0]>2 && n>0 || n==81){
/---/
}else if(min[0]==0 && n>0) {
/---/
}}else if(n!=0){
/---/
}
if(n==0){
/---/
}
}
}
I am trying to compare 2 scores that I have made oldScore and best_score(both in Main_Screen). I think the problem is that the ints are not saving properly. There are no errors but if the best_Score is lower than the old_score it still changes it in the textview even though the best_score should be higher than the old_score. Hopefully I can learn from this :)
Main_Screen
public class Main_Screen extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
getSupportActionBar().hide();
//SETS CUSTOM FONT
TextView main_screen_titleone = (TextView)findViewById(R.id.main_screen_titleone);
TextView main_screen_titletwo = (TextView)findViewById(R.id.main_screen_titletwo);
TextView best_score_tv = (TextView)findViewById(R.id.best_score_tv);
TextView best_score_number_tv = (TextView)findViewById(R.id.best_score_number_tv);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/LemonMilk.otf");
main_screen_titleone.setTypeface(myCustomFont);
main_screen_titletwo.setTypeface(myCustomFont);
best_score_tv.setTypeface(myCustomFont);
best_score_number_tv.setTypeface(myCustomFont);
//******************;
int best_score = retrieveInt("BEST_SCORE");
int oldScore = Integer.valueOf(best_score_number_tv.getText().toString());
if (best_score > oldScore){
best_score_number_tv.setText(best_score + "");
}
}
public void startTheGame(View view){
Intent intent = new Intent(this, press_screen.class);
startActivity(intent);
}
public int retrieveInt(String key){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
return sp.getInt(key, 0);
}
Press_Screen
public class press_screen extends ActionBarActivity {
private int time_left;
private int amountOfTapsNumber;
private int bestScore;
TextView amountOfTaps;
TextView timeLeftNumber;
TextView time_left_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_press_screen);
getSupportActionBar().hide();
amountOfTaps = (TextView)findViewById(R.id.amount_of_taps);
timeLeftNumber = (TextView)findViewById(R.id.time_left_number_tv);
time_left_tv = (TextView)findViewById(R.id.time_left_tv);
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/LemonMilk.otf");
amountOfTaps.setTypeface(myCustomFont);
timeLeftNumber.setTypeface(myCustomFont);
time_left_tv.setTypeface(myCustomFont);
timer.start();
}
//Create Timer
CountDownTimer timer = new CountDownTimer(21000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftNumber = (TextView) findViewById(R.id.time_left_number_tv);
time_left = Integer.valueOf(timeLeftNumber.getText().toString()) - 1;
timeLeftNumber.setText(time_left + "");
}
#Override
public void onFinish() {
if(amountOfTapsNumber > bestScore){
bestScore = amountOfTapsNumber;
saveInfo("BEST_SCORE", bestScore);
}
TextView best_score_number_tv = (TextView)findViewById(R.id.best_score_number_tv);
Intent goBackToMainActivity = new Intent(press_screen.this, Main_Screen.class);
startActivity(goBackToMainActivity);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_press_screen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void triggerTapOnMainButton(View view) {
amountOfTaps = (TextView) findViewById(R.id.amount_of_taps);
amountOfTapsNumber = Integer.valueOf(amountOfTaps.getText().toString()) + 1;
amountOfTaps.setText(amountOfTapsNumber + "");
}
public void saveInfo(String key, int bestScore){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putInt("BEST_SCORE", bestScore);
edit.commit();
}
}
When your timer finishes, you send your tapsNumber on the Intent to MainActivity, like this:
Intent goBackToMainActivity = new Intent(press_screen.this, Main_Screen.class);
Bundle bundle = new Bundle();
bundle.putInt("lastScore", amountOfTapsNumber);
goBackToMainActivity.putExtras(bundle);
startActivity(goBackToMainActivity);
Then, in your MainActivity onCreate(), check if your Intent has the oldScore. If it does, compare it to the best_score.
int lastScore = 0;
if(getIntent() !=null && getIntent().getIntExtra("lastScore",0)>0)
lastScore = getIntent().getIntExtra("lastScore",0);
//comparing the lastScore with the bestScore
if (lastScore > best_Score){
best_score_number_tv.setText(lastScore + "");
}
else{
best_score_number_tv.setText(best_Score + "");
}
This way your bestScore will be updated if your lastScore is higher than your old best_score.
I have the ArrayList...
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
and I want it so that when the user closes the app or leaves the app, all the ColorSaver objects in the ArrayList will be there when the user reopens the app. I would prefer to use the SharedPreferences but I can't do that because the list is a custom object...
I have looked around and found out that I can do a serializable but I tried that and failed horribly, so if somebody could guide me through the serializable deal that would be great. Oh and where do I put the code, like in onCreate() in my mainActivity or in the activity that is displaying the ArrayList
My mainActivity class
public class MainActivity extends Activity {
ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
private static final String TAG = "Main Activity";
public static final String PREFS_NAME = "MyPrefsFile";
final Intent intent = new Intent();
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
final NumberPicker rednp = (NumberPicker) findViewById(R.id.redNumberPicker1);
final NumberPicker bluenp = (NumberPicker) findViewById(R.id.blueNumberPicker);
final NumberPicker greennp = (NumberPicker) findViewById(R.id.greenNumberPicker);
switch(item.getItemId())
{
case R.id.save:
Log.i(TAG, "Save item clicked!");
Intent intent = new Intent(this, SaveActivity.class);
intent.putExtra("RedValue", rednp.getValue());
intent.putExtra("BlueValue", bluenp.getValue());
intent.putExtra("GreenValue", greennp.getValue());
intent.putExtra("temparray", tempList);
startActivity(intent);
return true;
case R.id.recall:
Log.i(TAG, "Recall item clicked!");
Intent intent2 = new Intent(this, RecallActivity.class);
intent2.putExtra("temparray", tempList);
startActivity(intent2);
return true;
default:
return super.onOptionsItemSelected(item);
}//End Switch
}
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ArrayList<ColorSaver> tempList = new ArrayList<ColorSaver>();
Bundle extras = getIntent().getExtras();
final SurfaceView sView = (SurfaceView) findViewById(R.id.surfaceView1);
final NumberPicker np = (NumberPicker) findViewById(R.id.redNumberPicker1);
np.setMaxValue(255);
np.setMinValue(0);
final NumberPicker np2 = (NumberPicker) findViewById(R.id.greenNumberPicker);
np2.setMaxValue(255);
np2.setMinValue(0);
final NumberPicker np3 = (NumberPicker) findViewById(R.id.blueNumberPicker);
np3.setMaxValue(255);
np3.setMinValue(0);
if( extras != null )
{
np.setValue(extras.getInt("savedRValue"));
//np.setValue(intent.getIntExtra("savedRValue", 255));
np2.setValue(extras.getInt("savedGValue"));
//np2.setValue(intent.getIntExtra("savedGValue", 255));
np3.setValue(extras.getInt("savedBValue"));
//np3.setValue(intent.getIntExtra("savedBValue", 255));
tempList = (ArrayList<ColorSaver>) extras.getSerializable("array");
sView.setBackgroundColor(Color.argb(255, np.getValue(), np2.getValue(), np3.getValue()));
}
else
{
Log.i(TAG, "I just don't get it...WTF");
}
np.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
//GREEN NUMBERPICKER LISTENER
np2.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
np3.setOnValueChangedListener( new NumberPicker.
OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
int rednum, greennum, bluenum;
rednum = np.getValue();
greennum = np2.getValue();
bluenum = np3.getValue();
sView.setBackgroundColor(Color.argb(255, rednum, greennum, bluenum));
}
});
}//End onCreate()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}//END onCreateOptionsMenu()
}//END CLASS
My saveActivity, where the user saves their color combo to the ArrayList...
public class SaveActivity extends Activity implements Serializable {
private static final String TAG = "Save Activity";
public ArrayList<ColorSaver> savedColors = new ArrayList<ColorSaver>();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save);
// Show the Up button in the action bar.
setupActionBar();
Bundle extras = getIntent().getExtras();
final Intent intent1 = new Intent(this, MainActivity.class);
Button saveButton = (Button) findViewById(R.id.saveButton1);
final EditText nameField = (EditText) findViewById(R.id.colorNameField);
//final Intent intent = new Intent();
savedColors = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Making sure the savedColors arrayList has something in it.
if( savedColors.isEmpty() )
{
ColorSaver temp = new ColorSaver("Rockies Purple", 180, 80, 255);
savedColors.add(temp);
}
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Bundle extras = getIntent().getExtras();
int redcolor, greencolor, bluecolor;
redcolor = extras.getInt("RedValue");
greencolor = extras.getInt("GreenValue");
bluecolor = extras.getInt("BlueValue");
String colorName = nameField.getText().toString();
//Build the new color and add it to the arrayList
ColorSaver saver = new ColorSaver(colorName, redcolor, greencolor, bluecolor);
savedColors.add(saver);
intent1.putExtra("array", savedColors);
Log.i(TAG, savedColors.get(savedColors.size()-1).getColorName());
startActivity(intent1);
}
});
}//END OnCreate()
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.save, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}//END CLASS
My recallActivity where the user recalls their color combos...
public class RecallActivity extends SaveActivity {
private static final String TAG = "Recall Activity";
ArrayList<ColorSaver> colorsArray = new ArrayList<ColorSaver>();
SaveActivity sActivity = new SaveActivity();
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recall);
// Show the Up button in the action bar.
setupActionBar();
final Intent intent1 = new Intent(this, MainActivity.class);
final Spinner colorList = (Spinner) findViewById(R.id.colorsSpinner);
Button grabButton = (Button) findViewById(R.id.grabButton);
Bundle extras = getIntent().getExtras();
colorsArray = (ArrayList<ColorSaver>) extras.getSerializable("temparray");
//Load the spinner with the saved colors
addColorNames(colorsArray);
grabButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
ColorSaver selectedItem = (ColorSaver) colorList.getSelectedItem();
int redValue, greenValue, blueValue;
String name;
redValue = selectedItem.getRedValue();
greenValue = selectedItem.getGreenValue();
blueValue = selectedItem.getBlueValue();
name = selectedItem.getColorName();
intent1.putExtra("savedRValue", redValue);
intent1.putExtra("savedGValue", greenValue);
intent1.putExtra("savedBValue", blueValue);
intent1.putExtra("savedName", name);
intent1.putExtra("array", colorsArray);
startActivity(intent1);
}//END onClick
});
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.recall, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}// END onOptionsItemSelected(MenuItem item)
public void addColorNames(ArrayList<ColorSaver> colorsArray1)
{
colorsArray = colorsArray1;
//if( !colorsArray.isEmpty() )
//{
Spinner colorsSpinner = (Spinner) findViewById(R.id.colorsSpinner);
ArrayAdapter<ColorSaver> dataAdapter
= new ArrayAdapter<ColorSaver>
(RecallActivity.this, android.R.layout.simple_spinner_item, colorsArray);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
colorsSpinner.setAdapter(dataAdapter);
Log.i(TAG, savedColors.get(savedColors.size() - 1).toString());
//}
//else
//{
// Log.i(TAG, "colorsSpinner came out to be null....WTF???");
//}
}//End addColorNames()
}//END CLASS
I am greatful of any help!
Take a look at Android's Parcelable implementation.
So, I'm just guessing on your ColorSaver class since it wasn't posted, but you would implement it the following way:
ColorSaver.java
public class ColorSaver implements Parcelable {
private String mName;
private int mRed;
private int mGreen;
private int mBlue;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(mName);
out.writeInt(mRed);
out.writeInt(mGreen);
out.writeInt(mBlue);
}
public static final Parcelable.Creator<ColorSaver> CREATOR
= new Parcelable.Creator<ColorSaver>() {
public ColorSaver createFromParcel(Parcel in) {
return new ColorSaver(in);
}
public ColorSaver[] newArray(int size) {
return new ColorSaver[size];
}
};
private ColorSaver(Parcel in) {
mName = in.readString();
mRed = in.readInt();
mGreen = in.readInt();
mBlue = in.readInt();
}
}
MyActivity.java
public class MyActivity extends Activity {
private static final String COLOR_SAVER_LIST = "com.example.android.ColorSaverList";
private List<ColorSaver> colorSaverList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(COLOR_SAVER_LIST)) {
colorSaverList = new ArrayList<ColorSaver>();
colorSaverList = savedInstanceState.getParcelableArrayList(COLOR_SAVER_LIST);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(COLOR_SAVER_LIST, colorSaverList);
}
}
I am following this tutorial.
there are 3 tabs in my App. in tab3 I m making changes to some views (like buttons and EditText spinners etc) and on the behalf of these changes i have to perform some actions in tab2. Simply you can say that i Change some values in tab3 and effect takes places in tab2. I know how to do this. I just want that my values of view becomes resets every time to default values when switching between the tab2 and tab3
My question is that how can i save the states of my views. so that on resuming the tabs i must get the default look of my views as i had left previously.
One thing more i tell you that i m doing all the work in onCreateView() methos. is this correct way. like this.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Toast.makeText(getActivity(), "onCreateView", Toast.LENGTH_SHORT)
.show();
if (container == null) {
return null;
}
View vi = inflater.inflate(R.layout.settings, container, false);
btnInsert = (Button) vi.findViewById(R.id.btnInsert);
btnInsert.setOnClickListener(this);
btnPosition = (Button) vi.findViewById(R.id.btnPosition);
btnPosition.setOnClickListener(this);
txtPosition = (TextView) vi.findViewById(R.id.txtPosition);
txtLogo = (TextView) vi.findViewById(R.id.txtLogo);
imgLogoPreview = (ImageView) vi.findViewById(R.id.imgLogoPreview);
imgLogoPreview.setOnClickListener(this);
edTxtUserText = (EditText) vi.findViewById(R.id.edTxtPreview);
relLogo = (RelativeLayout) vi.findViewById(R.id.RelLogo);
relText = (RelativeLayout) vi.findViewById(R.id.RelText);
logoWheel = (WheelView) vi.findViewById(R.id.wheelLogo);
logoWheel.setAdapter(new ArrayWheelAdapter<String>(logoWheelList));
logoWheel.setVisibleItems(4);
logoWheel.setCurrentItem(1);
positionWheel = (WheelView) vi.findViewById(R.id.wheelPosition);
positionWheel.setAdapter(new ArrayWheelAdapter<String>(
positionWheelTextList));
// LogoWheel changed listener
changedListenerLogo = new OnWheelChangedListener() {
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!wheelScrolled) {
}
}
};
logoWheel.addChangingListener(changedListenerLogo);
// Wheel scrolled listener
scrolledListenerLogo = new OnWheelScrollListener() {
public void onScrollStarts(WheelView wheel) {
wheelScrolled = true;
}
public void onScrollEnds(WheelView wheel) {
wheelScrolled = false;
btnInsert.setText(logoWheelList[wheel.getCurrentItem()] + "");
wheel.setVisibility(View.INVISIBLE);
if (wheel.getCurrentItem() == 2) {
txtPosition.setVisibility(View.INVISIBLE);
btnPosition.setVisibility(View.INVISIBLE);
relText.setVisibility(View.INVISIBLE);
relLogo.setVisibility(View.INVISIBLE);
} else if (wheel.getCurrentItem() == 1) {
relText.setVisibility(View.VISIBLE);
relLogo.setVisibility(View.INVISIBLE);
txtPosition.setVisibility(View.VISIBLE);
btnPosition.setVisibility(View.VISIBLE);
btnPosition.setText("Top");
positionWheel.setAdapter(new ArrayWheelAdapter<String>(
positionWheelTextList));
positionWheel.setVisibleItems(4);
positionWheel.setCurrentItem(1);
} else if (wheel.getCurrentItem() == 0) {
relLogo.setVisibility(View.VISIBLE);
relText.setVisibility(View.INVISIBLE);
txtPosition.setVisibility(View.VISIBLE);
btnPosition.setVisibility(View.VISIBLE);
btnPosition.setText("Top Left");
positionWheel.setAdapter(new ArrayWheelAdapter<String>(
positionWheelLogoList));
positionWheel.setVisibleItems(4);
positionWheel.setCurrentItem(1);
}
}
};
logoWheel.addScrollingListener(scrolledListenerLogo);
// /////////////////////Positon Wheel Listners///////////
// LogoWheel changed listener
changedListenerPosition = new OnWheelChangedListener() {
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!wheelScrolled) {
}
}
};
positionWheel.addChangingListener(changedListenerPosition);
// Wheel scrolled listener
scrolledListenerPosition = new OnWheelScrollListener() {
public void onScrollStarts(WheelView wheel) {
wheelScrolled = true;
}
public void onScrollEnds(WheelView wheel) {
wheelScrolled = false;
String btnStatus = btnInsert.getText().toString();
if (btnStatus.equals("Logo")) {
btnPosition.setText(positionWheelLogoList[positionWheel
.getCurrentItem()] + "");
} else if (btnStatus.equals("Text")) {
btnPosition.setText(positionWheelTextList[positionWheel
.getCurrentItem()] + "");
}
wheel.setVisibility(View.INVISIBLE);
}
};
positionWheel.addScrollingListener(scrolledListenerPosition);
return vi;
}
at what point i must save the states and at what point i should retrieve the savedstates?
Please tell me the how to implement the lifecycle of fragment in simple words.
i also tried the saveInstance() method of fragment. but not called.
Thanks
If I understand you correctly then this might be useful. Instead of recreating Fragments each time you can hide and show them.
This of course preserves your Fragments so is possibly only something you'd do it you had a few tabs. The advantage of this is that
You don't need to worry about saving data and recreating the fragment
Changes are available immediately to the user as soon as the relevant tab is selected.