I have a view that does an animation and then should be removed or at least sent to the back so i can reuse it. I'm having trouble attaching a listener to it.
I've been stuck on this for about 2 weeks so any help at all is really appreciated.
I'm just trying to get the card to fling off the screen, disappear and then be deleted.
package com.example.trevorwood.biggles.study;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.example.trevorwood.biggles.R;
public class StudyActivity extends AppCompatActivity {
LinearLayout mFlipCardLinearLayout;
LinearLayout mCardFlippedButtons;
FrameLayout mCardFrame;
View mCurrentAnimCardContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_study);
Intent intent = getIntent();
// String value = intent.getStringExtra("key");
Toolbar toolbar = (Toolbar) findViewById(R.id.study_toolbar);
toolbar.setTitleTextColor(Color.WHITE);//0xAARRGGBB
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mFlipCardLinearLayout = (LinearLayout) findViewById(R.id.flip_card_linear_layout);
mCardFlippedButtons = (LinearLayout) findViewById(R.id.card_flipped_buttons);
mCardFrame = (FrameLayout) findViewById(R.id.card_frame);
final Drawable upArrow = getResources().getDrawable(R.drawable.ic_back_arrow);
upArrow.setColorFilter(getResources().getColor(R.color.colorWhite), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
makeNewCard();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/HomeFragment button
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
public void onCardClick(View view) {
flipCard();
}
public void onCardFlippedButtonsClick(View view) {
Integer numberPressed;
switch (view.getId()){
case R.id.color_button_1:numberPressed = 1;break;
case R.id.color_button_2:numberPressed = 2;break;
case R.id.color_button_3:numberPressed = 3;break;
case R.id.color_button_4:numberPressed = 4;break;
case R.id.color_button_5:numberPressed = 5;break;
default:numberPressed = 0;
}
saveCardStats(numberPressed);
flingCardAway();
resetForNewCard();
makeNewCard();
}
private void flipCard() {
FrameLayout cardFrame = (FrameLayout) findViewById(R.id.card_frame);
Integer childCount = cardFrame.getChildCount();
Log.d("Simple","childCount: "+childCount);
View cardContainer = findViewById(R.id.card_container);
View cardFace = findViewById(R.id.card_front);
View cardBack = findViewById(R.id.card_back);
FlipAnimation flipAnimation = new FlipAnimation(cardFace, cardBack);
if (cardFace.getVisibility() == View.GONE) {
mFlipCardLinearLayout.setVisibility(View.VISIBLE);
mCardFlippedButtons.setVisibility(View.GONE);
flipAnimation.reverse();
}else{
mFlipCardLinearLayout.setVisibility(View.GONE);
mCardFlippedButtons.setVisibility(View.VISIBLE);
}
cardContainer.startAnimation(flipAnimation);
}
private void saveCardStats(Integer numberPressed){
}
private void flingCardAway(){
mCurrentAnimCardContainer = findViewById(R.id.card_container);
ViewCompat.setTranslationZ(mCurrentAnimCardContainer, 1.0f);
AnimationSet anim = new AnimationSet(true);
RotateAnimation rotate1 = new RotateAnimation(0,-45, Animation.RELATIVE_TO_SELF,0.5f , Animation.RELATIVE_TO_SELF,0.5f );
rotate1.setStartOffset(100);
rotate1.setDuration(500);
anim.addAnimation(rotate1);
TranslateAnimation trans1 = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, -0.1f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
trans1.setDuration(600);
anim.addAnimation(trans1);
AlphaAnimation opacity1 = new AlphaAnimation(1.0f, 0.0f);
opacity1.setDuration(400);
opacity1.setStartOffset(200);
anim.addAnimation(opacity1);
mCurrentAnimCardContainer.setAnimation(anim);
mCurrentAnimCardContainer.setVisibility(View.VISIBLE);
final FrameLayout cardFrame = (FrameLayout) findViewById(R.id.card_frame);
anim.setAnimationListener(new Animation.AnimationListener(){
#Override
public void onAnimationStart(Animation arg0) {
}
#Override
public void onAnimationRepeat(Animation arg0) {
}
#Override
public void onAnimationEnd(Animation arg0) {
//The problem area, also this is not always called
// ((ViewGroup)mCurrentAnimCardContainer.getParent()).removeView(mCurrentAnimCardContainer);
// cardFrame.removeAllViews();
}
});
}
private void resetForNewCard(){
mFlipCardLinearLayout.setVisibility(View.VISIBLE);
mCardFlippedButtons.setVisibility(View.GONE);
}
private void makeNewCard(){
Integer childCount = mCardFrame.getChildCount();
Log.d("Simple","childCount: "+childCount);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.study_card, mCardFrame);
}
}
Is it just me or does making an Android app feel like you're constantly swimming against the current in a river.
Edit: If you want to see real improvement, explain why you think this is a bad question rather than just down voting.
I took out onAnimationEnd and just put the removeAllView method outside of it and it worked. Honestly I have no idea how this works. One would imagine that if you remove a View it cannot have an animation work on it.
private void flingCardAway(){
View currentAnimCardContainer = findViewById(R.id.card_container);
ViewCompat.setTranslationZ(currentAnimCardContainer, 1.0f);
AnimationSet anim = new AnimationSet(true);
RotateAnimation rotate1 = new RotateAnimation(0,-45, Animation.RELATIVE_TO_SELF,0.5f , Animation.RELATIVE_TO_SELF, 0.5f );
rotate1.setStartOffset(1);
rotate1.setDuration(400);
anim.addAnimation(rotate1);
TranslateAnimation trans1 = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, -0.0f, Animation.RELATIVE_TO_PARENT, -1.5f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -0.5f);
trans1.setStartOffset(1);
trans1.setDuration(550);
anim.addAnimation(trans1);
AlphaAnimation opacity1 = new AlphaAnimation(1.0f, 0.0f);
opacity1.setStartOffset(300);
opacity1.setDuration(600);
anim.addAnimation(opacity1);
currentAnimCardContainer.startAnimation(anim);
mCardFrame.removeAllViews();
}
Related
I built a view that contains a EditText as a submit button, therefore it's not focusable in touch mode, the text is centered and it has a background color. Then, I created a fragment with this button.
When this fragment is the first one to be placed in the container to be drawn, the text is centered in the edit text as expected. However, if use an click event to replace this fragment with another fragment that contains it's own submit button, the text is not centered, let alone aligned to the left or to the right. It's not aligned at all.
After put a Hander to add a delay for requesting the layout after 5ms where I create view to be placed in the fragment, the text get centered properly. I realize that for some reason the fragment transaction is needing an extra call for requestLayout.
I isolated the code that is causing the problem. By doing this I realized that the problem is somehow related with the way I handle typefaces in my TestTextField.java. I pasted right bellow.
What could be possibly causing that? Why? If it is something wrong with my code, why it works to the first fragment I placed in the screen, but it does not work with the other ones?
TestActivity.java
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import java.lang.reflect.Method;
/**
* Created by eduardoj on 2017-07-19.
*/
public class TestActivity extends Activity
implements TestFragmentA.Listener, TestFragmentB.Listener {
private FrameLayout fragmentContainer;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewGroup.LayoutParams matchParent = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
fragmentContainer = new FrameLayout(this);
fragmentContainer.setId(View.generateViewId());
fragmentContainer.setLayoutParams(matchParent);
fragmentContainer.setFocusableInTouchMode(true);
setContentView(fragmentContainer);
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(fragmentContainer.getId(), TestFragmentA.newInstance());
transaction.commit();
}
#Override
public void onASubmitButtonClick() {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(fragmentContainer.getId(), TestFragmentB.newInstance());
transaction.commit();
}
#Override
public void onBSubmitButtonClick() {
}
}
TestFragmentA.java
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
/**
* Created by eduardoj on 2017-07-19.
*/
public class TestFragmentA extends Fragment {
public interface Listener {
void onASubmitButtonClick();
}
private Listener listener;
public static TestFragmentA newInstance() {
Bundle args = new Bundle();
TestFragmentA fragment = new TestFragmentA();
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
/*
* This makes sure that the container context has implemented the
* callback interface. If not, it throws an exception.
*/
try {
listener = (Listener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement TestFragmentA.Listener");
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
FrameLayout layout = new FrameLayout(getActivity());
layout.setId(View.generateViewId());
layout.setLayoutParams(params);
layout.setBackgroundColor(Color.CYAN);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
600,
FrameLayout.LayoutParams.WRAP_CONTENT,
Gravity.CENTER
);
TestTextField view = new TestTextField(getActivity());
view.setId(View.generateViewId());
view.setLayoutParams(lp);
view.setText("Submit A");
view.setBackgroundColor(Color.MAGENTA);
view.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
view.setEnableTextEditing(false);
view.addListener(new TestTextField.Listener() {
#Override
protected void onClick(TestTextField textField, String text) {
super.onClick(textField, text);
listener.onASubmitButtonClick();
}
});
layout.addView(view);
return layout;
}
}
TestFragmentB.java
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
/**
* Created by eduardoj on 2017-07-19.
*/
public class TestFragmentB extends Fragment {
public interface Listener {
void onBSubmitButtonClick();
}
private Listener listener;
public static TestFragmentB newInstance() {
Bundle args = new Bundle();
TestFragmentB fragment = new TestFragmentB();
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
/*
* This makes sure that the container context has implemented the
* callback interface. If not, it throws an exception.
*/
try {
listener = (Listener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement TestFragmentA.Listener");
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
FrameLayout layout = new FrameLayout(getActivity());
layout.setId(View.generateViewId());
layout.setLayoutParams(params);
layout.setBackgroundColor(Color.LTGRAY);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
600,
FrameLayout.LayoutParams.WRAP_CONTENT,
Gravity.CENTER
);
TestTextField view = new TestTextField(getActivity());
view.setId(View.generateViewId());
view.setLayoutParams(lp);
view.setText("Submit B");
view.setBackgroundColor(Color.MAGENTA);
view.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
view.setEnableTextEditing(false);
view.addListener(new TestTextField.Listener() {
#Override
protected void onClick(TestTextField textField, String text) {
super.onClick(textField, text);
listener.onBSubmitButtonClick();
}
});
layout.addView(view);
return layout;
}
}
TestTextField.java
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
/*
* Created by eduardoj on 2017-07-13.
*/
public class TestTextField extends LinearLayout {
public static class Listener {
protected void onClick(TestTextField textField, String text) {}
}
private int BACKGROUND_COLOR = Color.MAGENTA;
private String HINT = "Enter text here";
private boolean isToUpdateMinHeight;
private EditText editText;
private Typeface textTypeface;
private Typeface hintTypeface;
private List<Listener> listeners;
public TestTextField(Context context) {
super(context);
listeners = new ArrayList<>();
/* Initializing text field */
initView();
bindListeners();
}
public void addListener(Listener listener) {
if (listener != null) {
listeners.add(listener);
}
}
public void setEnableTextEditing(boolean enable) {
editText.setFocusableInTouchMode(enable);
}
public void setHintTypeface(Typeface typeface) {
hintTypeface = typeface;
isToUpdateMinHeight = true;
updateTypeface();
}
public void setText(CharSequence text) {
editText.setText(text);
updateTypeface();
}
#Override
public void setTextAlignment(int textAlignment) {
editText.setTextAlignment(textAlignment);
}
public void setTypeface(Typeface typeface) {
isToUpdateMinHeight = true;
textTypeface = typeface;
updateTypeface();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
updateMinHeight();
}
private void initView() {
setOrientation(HORIZONTAL);
LayoutParams params = new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1);
editText = new EditText(getContext());
editText.setId(generateViewId());
editText.setLayoutParams(params);
editText.setHint(HINT);
editText.setBackgroundColor(Color.TRANSPARENT); // Removes underline
addView(editText);
updateTypeface();
setBackgroundColor(BACKGROUND_COLOR);
// Custom Typefaces: you have to set the custom typeset to reproduce the problem.
// setTypeface(G.Font.getVegurRegular(getContext()));
// setHintTypeface(G.Font.getVegurLight(getContext()));
/* This is the current work around for this Issue */
(new Handler()).postDelayed(new Runnable() {
#Override
public void run() {
requestLayout();
}
}, 15);
}
private void bindListeners() {
final TestTextField textFieldInstance = this;
editText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (Listener listener : listeners) {
listener.onClick(
textFieldInstance,
editText.getText().toString()
);
}
}
});
}
/**
* Updates the minimum height to the size of the considering the biggest
* typeface.
*/
private void updateMinHeight() {
if (!isToUpdateMinHeight) {
return;
}
Typeface original = editText.getTypeface();
editText.setTypeface(textTypeface);
editText.measure(0, 0);
int textHeight = editText.getMeasuredHeight();
editText.setTypeface(hintTypeface);
editText.measure(0, 0);
int hintHeight = editText.getMeasuredHeight();
int minHeight = textHeight > hintHeight ? textHeight : hintHeight;
editText.setMinimumHeight(minHeight);
editText.setTypeface(original);
isToUpdateMinHeight = false;
}
private void updateTypeface() {
boolean hasText = editText.length() > 0;
Typeface typeface = hasText ? textTypeface : hintTypeface;
editText.setTypeface(typeface);
}
}
I came to a solution that doesn't require to call an extra requestLayout, I believe this is the right way to solve this problem.
updateMinHeight and super.onMeasure are in the wrong order in the onMeasure method. The correct way is:
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
updateMinHeight();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
For me, this order above makes sense since updateMinHeight can actually change the measured size of the widget. Though this answer shows how to solve, I can't understand why the problem happens and how would this affect only the text position in very specific cases, such as to the first fragment displayed.
I deployed a splash screen in my application with an Internet code, everything is working but cannot set a time for this activity close and open the main application could help me. I've tried the shape of the handler but closes the application after time.
package com.packpage.application;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import com.packpage.application.FontelloTextView;
import com.packpage.application.KenBurnsView;
public class SplashScreensActivity extends Activity {
public static final String SPLASH_SCREEN_OPTION = "com.packpage.application.SplashScreensActivity";
public static final String SPLASH_SCREEN_OPTION_1 = "Option 1";
public static final String SPLASH_SCREEN_OPTION_2 = "Option 2";
public static final String SPLASH_SCREEN_OPTION_3 = "Option 3";
private KenBurnsView mKenBurns;
private FontelloTextView mLogo;
private TextView welcomeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE); //Removing ActionBar
setContentView(R.layout.activity_splash_screen);
mKenBurns = (KenBurnsView) findViewById(R.id.ken_burns_images);
mLogo = (FontelloTextView) findViewById(R.id.logo);
welcomeText = (TextView) findViewById(R.id.welcome_text);
mKenBurns.setImageResource(R.drawable.splash_screen_background);
String category = SPLASH_SCREEN_OPTION_1;
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey(SPLASH_SCREEN_OPTION)) {
category = extras.getString(SPLASH_SCREEN_OPTION, SPLASH_SCREEN_OPTION_1);
}
setAnimation(category);
}
/** Animation depends on category.
* */
private void setAnimation(String category) {
if (category.equals(SPLASH_SCREEN_OPTION_1)) {
animation1();
} else if (category.equals(SPLASH_SCREEN_OPTION_2)) {
animation2();
} else if (category.equals(SPLASH_SCREEN_OPTION_3)) {
animation2();
animation3();
}
}
private void animation1() {
ObjectAnimator scaleXAnimation = ObjectAnimator.ofFloat(mLogo, "scaleX", 5.0F, 1.0F);
scaleXAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
scaleXAnimation.setDuration(1200);
ObjectAnimator scaleYAnimation = ObjectAnimator.ofFloat(mLogo, "scaleY", 5.0F, 1.0F);
scaleYAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
scaleYAnimation.setDuration(1200);
ObjectAnimator alphaAnimation = ObjectAnimator.ofFloat(mLogo, "alpha", 0.0F, 1.0F);
alphaAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
alphaAnimation.setDuration(1200);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(scaleXAnimation).with(scaleYAnimation).with(alphaAnimation);
animatorSet.setStartDelay(500);
animatorSet.start();
}
private void animation2() {
mLogo.setAlpha(1.0F);
Animation anim = AnimationUtils.loadAnimation(this, R.anim.translate_top_to_center);
mLogo.startAnimation(anim);
}
private void animation3() {
ObjectAnimator alphaAnimation = ObjectAnimator.ofFloat(welcomeText, "alpha", 0.0F, 1.0F);
alphaAnimation.setStartDelay(1700);
alphaAnimation.setDuration(500);
alphaAnimation.start();
}
}
Take a look at this tutorial
http://www.androidhive.info/2013/07/how-to-implement-android-splash-screen-2/
Use Handler
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
SPLASH_TIME_OUT is time in milliseconds. Start your next activity inside run method
i am working on android app
in which i have an animated image.
my code is
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth()/2;
left = new TranslateAnimation(0, hight, width, hight);
left1= new TranslateAnimation( 480, 10, 0, 10);
left.setDuration(2000);
left.setAnimationListener(this);
b1 =(ImageView)findViewById( R.id.balloon);
b1.setOnClickListener(this);
b1.startAnimation(left);
#Override
public void onClick(View v) {
Toast.makeText(this, "Clicked", 27).show();
}
using this code i am able to animate ballon or my picture but i the onclick lisnter only works when animation is completed i want onclicklistner should work during animation how to do this.
sorry for bad english
Override onAnimationStart and onAnimationEnd functions in your AnimationListener. Keep a variable to check whether animation is playing when the image clicked.
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ImageView imageView;
private boolean animationPlaying;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TranslateAnimation animation = new TranslateAnimation( 480, 10, 0, 10);
animation.setDuration(2000);
animation.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
animationPlaying = true;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
animationPlaying = false;
}
});
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.startAnimation(animation);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(animationPlaying) {
Toast.makeText(getBaseContext(), "Click", Toast.LENGTH_SHORT).show();
} else {
Log.d("ANIMATION", "click missed because animation was not playing");
}
}
});
}
}
OK so I'm using xml to set this menu which is supported by the following java code
package starting.rt;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Menu extends Activity implements OnClickListener{
View.OnTouchListener gestureListener;
TextView display;
Button begin;
Button random;
Button game;
TextView counter;
Button next;
Button previous;
Button moreapps;
Button rate;
Random myRandom;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(starting.rt.R.layout.menu);
begin = (Button) findViewById(starting.rt.R.id.Begin);
random = (Button) findViewById(starting.rt.R.id.Random);
display = (TextView) findViewById(starting.rt.R.id.tvResults);
counter = (TextView) findViewById(starting.rt.R.id.tvCounter);
next = (Button) findViewById(starting.rt.R.id.Next);
previous = (Button) findViewById(starting.rt.R.id.Previous);
moreapps = (Button)findViewById(R.id.More);
rate = (Button) findViewById(R.id.rate);
game = (Button) findViewById(R.id.game);
// display.setOnTouchListener(this.gestureListener);
begin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent openStartingPoint = new Intent("starting.rt.RelationshipTipsActivity");
startActivity(openStartingPoint);
}});
moreapps.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goToMarket;
goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pub:\"Wompa\""));
startActivity(goToMarket);
}});
game.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent openStartingPoint = new Intent("starting.rt.GameView");
startActivity(openStartingPoint);
}});
rate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=" + getPackageName()));
startActivity(i);
}});}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Now what's supposed to be happening is when they click on the game which starts a new java class called GameView it crashes on clicked. Every other button works.
This is the code from GameView
package starting.rt;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private GameLoopThread gameLoopThread;
private List<Sprite> sprites = new ArrayList<Sprite>();
private List<TempSprite> temps = new ArrayList<TempSprite>();
private long lastClick;
private Bitmap bmpBlood;
public GameView(Context context) {
super(context);
gameLoopThread = new GameLoopThread(this);
getHolder().addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
gameLoopThread.setRunning(false);
while (retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
bmpBlood = BitmapFactory.decodeResource(getResources(), R.drawable.blood1);
}
private void createSprites() {
sprites.add(createSprite(R.drawable.bad1));
// sprites.add(createSprite(R.drawable.bad2));
// sprites.add(createSprite(R.drawable.bad3));
// sprites.add(createSprite(R.drawable.bad4));
// sprites.add(createSprite(R.drawable.bad5));
// sprites.add(createSprite(R.drawable.bad6));
// sprites.add(createSprite(R.drawable.good1));
// sprites.add(createSprite(R.drawable.good2));
// sprites.add(createSprite(R.drawable.good3));
// sprites.add(createSprite(R.drawable.good4));
// sprites.add(createSprite(R.drawable.good5));
// sprites.add(createSprite(R.drawable.good6));
}
private Sprite createSprite(int resouce) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
return new Sprite(this, bmp);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
for (int i = temps.size() - 1; i >= 0; i--) {
temps.get(i).onDraw(canvas);
}
for (Sprite sprite : sprites) {
sprite.onDraw(canvas);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (System.currentTimeMillis() - lastClick > 300) {
lastClick = System.currentTimeMillis();
float x = event.getX();
float y = event.getY();
synchronized (getHolder()) {
for (int i = sprites.size() - 1; i >= 0; i--) {
Sprite sprite = sprites.get(i);
if (sprite.isCollition(x, y)) {
sprites.remove(sprite);
temps.add(new TempSprite(temps, this, x, y, bmpBlood));
break;
}
}
}
}
return true;
}
}
The GameView calls a few other classes for things part of the game but it crashes before it can start. I think it's crashing because it's switching from xml layout to the java surfaceview. Help would be appreciated :) Thanks!
First of all, you should always post in your questions the stacktrace with the exception from the Logcat if your app crashes.
You can't start a SurfaceView directly, instead your custom SurfaceView must be embedded in an Activity like any other view in android. For example:
public class GameViewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(new GameView(this));
}
}
This is my first app and i need to start new activity when the animation ends. what do I need to do? My code:
package com.lineage.goddess;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
public class LineageSplashActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
startAnimation();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
private void startAnimation() {
// TODO Auto-generated method stub
TextView logo1= (TextView) findViewById(R.id.TextView1);
Animation fade1= AnimationUtils.loadAnimation(this, R.anim.fade_in);
logo1.startAnimation(fade1);
TextView logo2= (TextView) findViewById(R.id.TextView2);
Animation fade2= AnimationUtils.loadAnimation(this, R.anim.fade_in);
logo2.startAnimation(fade2);
TextView logo3= (TextView) findViewById(R.id.TextView3);
Animation fade3= AnimationUtils.loadAnimation(this, R.anim.fade_in);
logo3.startAnimation(fade3);
TextView logo4= (TextView) findViewById(R.id.TextView4);
Animation fade4= AnimationUtils.loadAnimation(this, R.anim.fade_in2);
logo4.startAnimation(fade4);}
public void onAnimationEnd() {
Intent i = new Intent( LineageSplashActivity.this, LineageMenuActivity.class );
LineageSplashActivity.this.startActivity( i );
;
}
}
Set an AnimationListener to the animation you want to use to start your Activity.
myAnimation.setAnimationListener(new AnimationListener() {
public void onAnimationStart(Animation animation) {}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
Intent i = new Intent( LineageSplashActivity.this, LineageMenuActivity.class );
LineageSplashActivity.this.startActivity( i );
}
}
So, your code will be like this:
package com.lineage.goddess;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
public class LineageSplashActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
startAnimation();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
private void startAnimation() {
// TODO Auto-generated method stub
TextView logo1= (TextView) findViewById(R.id.TextView1);
Animation fade1= AnimationUtils.loadAnimation(this, R.anim.fade_in);
logo1.startAnimation(fade1);
TextView logo2= (TextView) findViewById(R.id.TextView2);
Animation fade2= AnimationUtils.loadAnimation(this, R.anim.fade_in);
logo2.startAnimation(fade2);
TextView logo3= (TextView) findViewById(R.id.TextView3);
Animation fade3= AnimationUtils.loadAnimation(this, R.anim.fade_in);
logo3.startAnimation(fade3);
TextView logo4= (TextView) findViewById(R.id.TextView4);
Animation fade4= AnimationUtils.loadAnimation(this, R.anim.fade_in2);
face4.setAnimationListener(new AnimationListener() {
public void onAnimationStart(Animation animation) {}
public void onAnimationRepeat(Animation animation) {}
public void onAnimationEnd(Animation animation) {
Intent i = new Intent( LineageSplashActivity.this, LineageMenuActivity.class );
LineageSplashActivity.this.startActivity( i );
}
}
logo4.startAnimation(fade4);
}
}
Your code made my eye's bleed, so I fixed it as much as I could:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
public class LineageSplashActivity extends Activity implements AnimationListener {
private static final int NUMBER_OF_ANIMATIONS = 4;
private int animationFinishedCount = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
startAnimations();
}
private void startAnimations() {
Animation fade = AnimationUtils.loadAnimation(this, R.anim.fade_in);
fade.setAnimationListener(this);
findViewById(R.id.TextView1).startAnimation(fade);
findViewById(R.id.TextView2).startAnimation(fade);
findViewById(R.id.TextView3).startAnimation(fade);
findViewById(R.id.TextView4).startAnimation(fade);
}
#Override
public void onAnimationEnd(Animation animation) {
// When all animations have finished - start the next activity
if(++animationFinishedCount == NUMBER_OF_ANIMATIONS){
Intent intent = new Intent( this, LineageMenuActivity.class );
startActivity( intent );
}
}
#Override
public void onAnimationStart(Animation animation) {
// Nothing
}
#Override
public void onAnimationRepeat(Animation animation) {
// Nothing
}
}
And if it's not a mis-type and you actually need a different animation for the 4th textview you can remove the count check and just add the animation listener to that individual animation.