Very new to Android and have researched this for a while now but can't quite find the answer. I'm sure there's a simple solution.
I'm getting a NullPointException which is connected to my View characterContainer = findViewById(R.id.icon_container);
As I understand it, it seems I'm trying to implement it in the onCreate() method and as such the layout is not fully ready yet causing characterContainer = null.
So I need to use it in onStart() or onResume() but I'm struggling. This is my code so far:
package harvest.life.game;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
public class HarvestLifeActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//find buttons on screen
Button up = (Button)findViewById(R.id.up);
up.setOnTouchListener(new UpListener());
Button down = (Button)findViewById(R.id.down);
down.setOnTouchListener(new UpListener()); // set as UpListener also for test reasons
Button left = (Button)findViewById(R.id.left);
left.setOnTouchListener(new UpListener()); // set as UpListener also for test reasons
Button right = (Button)findViewById(R.id.right);
right.setOnTouchListener(new UpListener()); // set as UpListener also for test reasons
}
//what up button does
private final class UpListener implements OnTouchListener {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//as long as up button is pressed it will keep moving character up
while (event.getAction() == MotionEvent.ACTION_DOWN)
{
View characterContainer = findViewById(R.id.icon_container);
Drawable walking = getResources().getDrawable(R.drawable.test_circle_red);
int startX = characterContainer.getLeft();
int startY = characterContainer.getTop();
int defaultWidth = characterContainer.getWidth();
int defaultHeight = characterContainer.getHeight();
//create new position for character 1 pixel closer to the top of screen
int newX = startX - 1;
int newY = startY;
//remove character
RelativeLayout view = (RelativeLayout) characterContainer;
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
//re make character in new position created above and assign background as walking forwards animation
RelativeLayout.LayoutParams characParams = new RelativeLayout.LayoutParams(defaultWidth,defaultHeight);
characParams.leftMargin = newY;
characParams.topMargin = newX;
characterContainer.setLayoutParams(characParams);
characterContainer.setBackgroundDrawable(walking);
}
break;
// when button is let go of
case MotionEvent.ACTION_UP:
RelativeLayout characterContainer = (RelativeLayout)
findViewById(R.id.icon_container);
Drawable standing =
getResources().getDrawable(R.drawable.test_circle);
//assign background back to standing animation
characterContainer.setBackgroundDrawable(standing);
default:
break;
}
return true;
}
}
public void onResume() { // what goes here?
}
}
Do I need to put a sort of function call in the onResume section or do I put the code for what the OnTouchListener does in here?
here's my main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/game_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="#FFFFFF">
<RelativeLayout
android:id="#+id/side_bar_right"
android:layout_width="50dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#000000">
<ImageView
android:contentDescription="#string/movement_button"
android:id="#+id/up"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="top"
android:src="#drawable/up" />
<ImageView
android:contentDescription="#string/movement_button"
android:id="#+id/down"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:src="#drawable/down" />
<ImageView
android:contentDescription="#string/movement_button"
android:id="#+id/right"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="#drawable/right" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/side_bar_left"
android:layout_width="50dp"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#000000">
<ImageView
android:contentDescription="#string/movement_button"
android:id="#+id/left"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="#drawable/left" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/icon_container"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#drawable/test_circle" >
</RelativeLayout >
</RelativeLayout>
Here's what I think you wanted:
package harvest.life.game;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
public class HarvestLifeActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//find buttons on screen
Button up = (Button)findViewById(R.id.up);
//up.setOnTouchListener(new UpListener());
Button down = (Button)findViewById(R.id.up);
//down.setOnTouchListener(new UpListener());
Button left = (Button)findViewById(R.id.up);
//left.setOnTouchListener(new UpListener());
Button right = (Button)findViewById(R.id.up);
//right.setOnTouchListener(new UpListener());
}
public void onDownButtonClick(View view){
while (event.getAction() == MotionEvent.ACTION_DOWN)
{
View characterContainer = findViewById(R.id.icon_container);
Drawable walking = getResources().getDrawable(R.drawable.test_circle_red);
int startX = characterContainer.getLeft();
int startY = characterContainer.getTop();
int defaultWidth = characterContainer.getWidth();
int defaultHeight = characterContainer.getHeight();
//create new position for character 1 pixel closer to the top of screen
int newX = startX - 1;
int newY = startY;
//remove character
RelativeLayout view = (RelativeLayout) characterContainer;
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
//re make character in new position created above and assign background as walking forwards animation
RelativeLayout.LayoutParams characParams = new RelativeLayout.LayoutParams(defaultWidth,defaultHeight);
characParams.leftMargin = newY;
characParams.topMargin = newX;
characterContainer.setLayoutParams(characParams);
characterContainer.setBackgroundDrawable(walking);
}
}
public void onUpButtonClicked(View view){
RelativeLayout characterContainer = (RelativeLayout)
findViewById(R.id.icon_container);
Drawable standing =
getResources().getDrawable(R.drawable.test_circle);
//assign background back to standing animation
characterContainer.setBackgroundDrawable(standing);
}
}
As you can see, I put your 'down' code in a function, and your 'up' code in another function. Then, in the xml, add android:onClick="onButtonDownClick" to the down button. Do the same (except with an 'onButtonUpClick') to your up button. This will cause those functions to be called on click. It's important to note that those functions take a View as an argument.
Related
What I essentially need is an action listener that notes if another touchable views have been clicked so that they can be set to enabled (i.e., if imageview1 is clicked, imageview2 can now be clicked whereas before it could not). I was looking around and found ActionListener and ActionEvents, but after importing all necessary packages, updating my SDK, and syncing my gradle files, Android Studio still doesn't recognize those options. I can't seem to find a way to get it to work. Is there something I'm missing in getting them to resolve, or is there another kind of listener I can use?
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="20dp"
android:id="#+id/sq2"
android:background="#color/preFocus"
android:onClick="imagePress"
android:layout_centerVertical="true"
android:nextFocusDown="#+id/sq3"
android:nextFocusUp="#+id/sq1"
android:nextFocusLeft="#+id/sq4"
android:nextFocusRight="#id/sq4"
/>
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="250dp"
android:background="#color/preFocus"
android:id="#id/sq4"
android:onClick="imagePress"
android:enabled="false"
android:layout_centerVertical="true"
android:nextFocusDown="#id/sq3"
android:nextFocusUp="#id/sq1"
android:nextFocusLeft="#id/sq2"
android:nextFocusRight="#id/sq2"
/>
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="400dp"
android:background="#color/preFocus"
android:id="#id/sq3"
android:onClick="imagePress"
android:enabled="false"
android:layout_centerHorizontal="true"
android:nextFocusDown="#id/sq1"
android:nextFocusUp="#id/sq1"
android:nextFocusLeft="#id/sq2"
android:nextFocusRight="#id/sq4"
/>
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="50dp"
android:background="#color/preFocus"
android:id="#id/sq1"
android:onClick="imagePress"
android:enabled="false"
android:layout_centerHorizontal="true"
android:nextFocusDown="#id/sq3"
android:nextFocusUp="#id/sq3"
android:nextFocusLeft="#id/sq2"
android:nextFocusRight="#id/sq4">
<requestFocus />
</ImageView>
</RelativeLayout>
Java:
package com.example.mcken.spinnertest;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.view.menu.MenuPopupHelper;
import android.util.Log;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.PopupMenu;
import java.lang.reflect.Field;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.activity_main);
final int childcount = rl.getChildCount();
for (int i = 0; i < childcount; i++){
final View square = rl.getChildAt(i);
final View nextSquare = rl.getChildAt(i+1);
square.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent click){
nextSquare.setEnabled(true);
}
});
}
}
public void clickableChange(){
//what am I trying to do
//set an actionlistener
//if this is clicked
//the "next" one is clickable
// RelativeLayout rl = (RelativeLayout) findViewById(R.id.activity_main);
// final int childcount = rl.getChildCount();
//
// for (int i = 0; i < childcount; i++){
// final View square = rl.getChildAt(i);
// final View nextSquare = rl.getChildAt(i+1);
// square.addActionListener(new ActionListener(){
// public void actionPerformed(ActionEvent click){
// nextSquare.setEnabled(true);
// }
// });
// }
}
public void imagePress(View test){
int id = test.getId();
ImageView picture = (ImageView) findViewById(id);
final int pictureId = id;
picture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popup = new PopupMenu(MainActivity.this, view);
popup.getMenuInflater().inflate(R.menu.popup_menu,popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
public boolean onMenuItemClick(MenuItem selection){
ImageView thisThing = (ImageView) findViewById(pictureId);
Drawable icon = selection.getIcon();
thisThing.setImageDrawable(icon);
return true;
}
});
popup.show();
}
});
}
}
I can't get my clear button to work in my program. My circle button works which displays random circles but my clear button does nothing. I'm lost. I know i'm supposed to use drawColor.Color.TRANSPARENT or the mode.clear but nothing is working.
package com.example.randomcircles;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.*;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import android.content.*;
public class DisplayRandomCircles extends Activity
{
FrameLayout f1, f2;
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.activity_display_random_circles);
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
f1 = (FrameLayout) findViewById(R.id.frame);
}
#SuppressLint("WrongCall")
public void doit(View v)
{
int rand = (int) (Math.random() * 60);
DrawCircle c = new DrawCircle(getApplicationContext());
Canvas d = new Canvas();
Paint p = new Paint();
switch (v.getId())
{
case (R.id.btn1):
f1.addView(c);
break;
case (R.id.btn2):
d.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
break;
}
}
}
package com.example.randomcircles;
import java.util.Random;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.*;
import android.view.*;
public class DrawCircle extends View
{
Random random = new Random();
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
int randX = random.nextInt(700);
int randY = random.nextInt(1000);
int randR = random.nextInt(200);
int color = Color.rgb(red, green, blue);
public DrawCircle(Context con)
{
super(con);
}
#SuppressLint("DrawAllocation")
#Override
public void onDraw(Canvas c)
{
super.onDraw(c);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setAntiAlias(true);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(100);
p.setColor(color);
p.setStyle(Paint.Style.FILL);
c.drawCircle(randX, randY, randR, p);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight=".75"
android:orientation="vertical" >
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:gravity="bottom|center"
android:orientation="horizontal" >
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|bottom"
android:layout_weight=".50"
android:onClick="doit"
android:text="#string/Circle" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".50"
android:layout_gravity="end|bottom"
android:onClick="doit"
android:text="#string/Clear" />
</LinearLayout>
</LinearLayout>
You are creating a new instance of DrawCircle every time doIt is called.
The old instance is still there. So you need to either remove the old view from f1, or get the exact same instance of DrawCircle you created before, set the new color, and then call invalidate() on the DrawCircle to force the redraw.
I am trying to create an app that displays a circle everytime I click a button. I have the layout looking great but when i click the button(circle) to display a circle on the screen nothing happens. I'm not confident that my draw circle class is being called correctly in my main activity. Here is my code below.
package com.example.randomcircles;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
public class DisplayRandomCircles extends Activity
{
DrawCircle c;
Canvas d;
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.activity_display_random_circles);
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
c = new DrawCircle(getApplicationContext());
d = new Canvas();
FrameLayout f1 = (FrameLayout) findViewById(R.id.frame);
}
#SuppressLint("WrongCall")
public void doit(View v)
{
switch (v.getId())
{
case (R.id.btn1):
c.onDraw(d);
break;
case (R.id.btn2):
break;
}
}
}
Here is my DrawCircle class
package com.example.randomcircles;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawCircle extends View
{
public DrawCircle(Context con)
{
super(con);
}
#Override
protected void onDraw(Canvas c)
{
super.onDraw(c);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setAntiAlias(true);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(100);
p.setColor(Color.RED);
p.setStyle(Paint.Style.FILL);
c.drawCircle(75, 75, 100, p);
}
}
And my layout xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight=".75"
android:orientation="vertical" >
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:gravity="bottom|center"
android:orientation="horizontal" >
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|bottom"
android:layout_weight=".50"
android:onClick="doit"
android:text="#string/Circle" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".50"
android:layout_gravity="end|bottom"
android:onClick="doit"
android:text="#string/Clear" />
</LinearLayout>
</LinearLayout>
Ok, here are some changes I'd make for this. I'm not exactly sure what you're trying to do, but this should make things easier.
First, change your class "DrawCircle" like this:
public class DrawCircle extends View
{
final Paint circlePaint;
{
circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
circlePaint.setAntiAlias(true);
circlePaint.setStyle(Paint.Style.STROKE);
circlePaint.setStrokeWidth(100);
circlePaint.setColor(Color.RED);
circlePaint.setStyle(Paint.Style.FILL);
}
public DrawCircle(Context con)
{
super(con);
}
public DrawCircle(Context con, AttributeSet set)
{
super(con, set);
}
public DrawCircle(Context con, AttributeSet set, int style)
{
super(con, set, style);
}
#Override
protected void onDraw(Canvas c)
{
super.onDraw(c);
c.drawCircle(75, 75, 100, circlePaint);
}
}
This will allow you to reuse the same Paint object with each draw because the onDraw() method can be called hundreds of times and there's no need to slow down your program for this.
Second, adding the other constructors allows you to add the View to your FrameLayouts by xml.
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.randomCircles.DrawCircle
android:id="#+id/circleFrame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Next, to fill your screen, you need to loop in your onDraw method. Think about drawing on the canvas as a stamp. Every time you draw, you stamp your image at the location you specify on top of the previous draw.
So
protected void onDraw(Canvas c)
{
super.onDraw(c);
for(int i = 0; i < 10; i++)
{
c.drawCircle(i*100, 75, 100, circlePaint);
}
}
This should draw 10 circles of radius 100 pixels across the top of your screen.
I have been looking around and searching for an answer and really trying to dive into android programming before asking any questions. I know that this site is here to help, but also not an outlet to be redundant and lazy. Though I am a begginer with android and am in need of some assistance if some of you have the time. I looked at a question that I really thought would help (URL: Button animations in android) But it just ended up making my program crash. I also checked out this one http://mobile.tutsplus.com/tutorials/android/android-sdk-creating-a-simple-property-animation/ , which also didn't really get me to the correct answer I was looking for. Now I have no code unfortunately but have tried to replicate the code from both of these example sites I have provided. They both crash when I get to the declaration of animation objects in the actual java code
i.e.
ImageView confettiStart = (ImageView) findViewById(R.id.confetti);
AnimatorSet confettiSet =(AnimatorSet)AnimatorInflater.loadAnimator(this,R.animator.startconfettianimations);
My goal is to basically just have a confetti animation come from the top of my screen and roll down to the bottom of my screen. I have created about 8 different images in order to create an "animation" but I really do not know how to implement this in Android itself. If someone could help or point me in the right direction I would greatly appreciate it. Thank you so much.
Use objectAnimator for that view and in that keep x parameter same while Change y parameter to 0 to 600 or something same . Hope it works. or translator animator will do the trick try it keep x1=0 x2=0 and y1=0 y2=600.
package com.shubh;
import android.os.Build;
import android.os.Bundle;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
public void startAnimation(View view) {
float dest = 0;
ImageView aniView = (ImageView) findViewById(R.id.imageView1);
switch (view.getId()) {
case R.id.Button01:
dest = 360;
if (aniView.getRotation() == 360) {
System.out.println(aniView.getAlpha());
dest = 0;
}
ObjectAnimator animation1 = ObjectAnimator.ofFloat(aniView,
"rotation", dest);
animation1.setDuration(2000);
animation1.start();
// Show how to load an animation from XML
// Animation animation1 = AnimationUtils.loadAnimation(this,
// R.anim.myanimation);
// animation1.setAnimationListener(this);
// animatedView1.startAnimation(animation1);
break;
case R.id.Button02:
// Shows how to define a animation via code
// Also use an Interpolator (BounceInterpolator)
Paint paint = new Paint();
TextView aniTextView = (TextView) findViewById(R.id.textView1);
float measureTextCenter = paint.measureText(aniTextView.getText()
.toString());
dest = 0 - measureTextCenter;
if (aniTextView.getX() < 0) {
dest = 0;
}
ObjectAnimator animation2 = ObjectAnimator.ofFloat(aniTextView,
"x", dest);
animation2.setDuration(2000);
animation2.start();
break;
case R.id.Button03:
// Demonstrate fading and adding an AnimationListener
RelativeLayout mainContainer = (RelativeLayout) findViewById(R.id.layout);
LayoutAnimationController controller = AnimationUtils.loadLayoutAnimation(this, R.anim.main_layout_animation);
mainContainer.setLayoutAnimation(controller);
dest = 1;
Button button3=(Button)findViewById(R.id.Button03);
button3.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.hyperspace_jump));
if (aniView.getAlpha() > 0) {
dest = 0;
}
ObjectAnimator animation3 = ObjectAnimator.ofFloat(aniView,
"alpha", dest);
animation3.setDuration(2000);
animation3.start();
break;
case R.id.Button04:
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(aniView, "alpha",
0f);
fadeOut.setDuration(2000);
ObjectAnimator mover = ObjectAnimator.ofFloat(aniView,
"translationX", -500f, 0f);
mover.setDuration(2000);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(aniView, "alpha",
0f, 1f);
fadeIn.setDuration(2000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(mover).with(fadeIn).after(fadeOut);
animatorSet.start();
break;
default:
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(this, HitActivity.class);
startActivity(intent);
return true;
}
}
and the xml is
<?xml version="1.0" encoding="utf-8" ?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
- <LinearLayout android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAnimation"
android:text="Rotate" />
<Button android:id="#+id/Button04"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAnimation"
android:text="Group" />
<Button android:id="#+id/Button03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAnimation"
android:text="Fade" />
<Button android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAnimation"
android:text="Animate" />
</LinearLayout>
<ImageView android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/img" />
<TextView android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageView1"
android:layout_alignRight="#+id/imageView1"
android:layout_marginBottom="30dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Try this
public class HitActivity extends Activity {
private ObjectAnimator animation1;
private ObjectAnimator animation2;
private Button button;
private Random randon;
private int width;
private int height;
private AnimatorSet set;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doctor_chemist_list);
width = getWindowManager().getDefaultDisplay().getWidth();
height = getWindowManager().getDefaultDisplay().getHeight();
randon = new Random();
set = createAnimation();
set.start();
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
int nextX = randon.nextInt(width);
int nextY = randon.nextInt(height);
animation1 = ObjectAnimator.ofFloat(button, "x", button.getX(),
nextX);
animation1.setDuration(1400);
animation2 = ObjectAnimator.ofFloat(button, "y", button.getY(),
nextY);
animation2.setDuration(1400);
set.playTogether(animation1, animation2);
set.start();
}
});
}
public void onClick(View view) {
String string = button.getText().toString();
int hitTarget = Integer.valueOf(string) + 1;
button.setText(String.valueOf(hitTarget));
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
private AnimatorSet createAnimation() {
int nextX = randon.nextInt(width);
int nextY = randon.nextInt(height);
button = (Button) findViewById(R.id.Button01);
animation1 = ObjectAnimator.ofFloat(button, "x", nextX);
animation1.setDuration(1400);
animation2 = ObjectAnimator.ofFloat(button, "y", nextY);
animation2.setDuration(1400);
AnimatorSet set = new AnimatorSet();
set.playTogether(animation1, animation2);
return set;
}
}
I would like to use viewSwitcher to switch between two layouts. It works with a button, but I would like to switch with touching the screen. I've found an onTouchListener example and i tried to implemet some kind of similar, but I did not manage to.
In my main.xml i got one Linear Layout which contains a ViewSwitcher and two other LinearLayout. These are the layouts i want to switch.
here it is:
<ViewSwitcher
android:id="#+id/viewSwitcher"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inAnimation="#android:anim/slide_in_left"
android:outAnimation="#android:anim/slide_out_right" >
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/firstlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg"
android:orientation="vertical" >
<ImageView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/titlebar" />
<Button
android:id="#+id/somebut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30px"
android:background="#drawable/but" />
</LinearLayout>
<LinearLayout
android:id="#+id/secondlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second layout" >
</TextView>
</LinearLayout>
</ViewSwitcher>
and my code:
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.ViewSwitcher;
public class SwitcherActivity extends Activity {
private float downXValue;
private View firstView;
private View SecondView;
private ViewSwitcher vs;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vs = (ViewSwitcher)findViewById(R.id.viewSwitcher);
firstView= findViewById(R.id.firstlayout);
secondView = findViewById(R.id.secondlayout);
LinearLayout first = (LinearLayout) findViewById(R.id.firstlayout);
first.setOnTouchListener((OnTouchListener) this);
}
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()){
case MotionEvent.ACTION_DOWN:{
// store the X value when the user's finger was pressed down
downXValue = arg1.getX();
break;
}
case MotionEvent.ACTION_UP:{
// Get the X value when the user released his/her finger
float currentX = arg1.getX();
// going backwards: pushing stuff to the right
if (downXValue < currentX)
{
if (vs.getCurrentView() != myFirstView)vs.showPrevious();
}
// going forwards: pushing stuff to the left
if (downXValue > currentX)
{
if (vs.getCurrentView() != mySecondView)
vs.showNext();
}
break;
}
}
return true;
}
}
My problem is, that i got ClassCastException in the line which contains the following:
first.setOnTouchListener((OnTouchListener) this);
Your activity has to implement OnTouchListener so that "this" can be used as the listener. Right now it's trying to cast an Activity to an OnTouchListener which is what's throwing the ClassCastException.
You also need to override the OnTouchListener methods to customize the way the touches are handled.