Animation on Android - java

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;
}
}

Related

Android: How to cycle through different images with button click?

In my android program I am wanting to cycle through different images of traffic lights on the click of a button. Whenever the app loads it starts off with an image of a red light, and when I click it I want it to change the green light, and the another click to a yellow light. This is what I have in my Java file
package com.example.trafficsimulator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void stopButton(View view){
final Button button = findViewById(R.id.button);
ImageView image = findViewById(R.id.redLightImage);
button.setBackgroundColor(getResources().getColor(R.color.yellowlight));
button.setText("Go");
image.setImageResource(R.drawable.yellowlight);
}
and XML file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/redLightImage"
android:layout_width="217dp"
android:layout_height="372dp"
android:layout_marginStart="97dp"
android:layout_marginTop="61dp"
android:layout_marginEnd="97dp"
android:layout_marginBottom="298dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/redlight" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="156dp"
android:layout_marginTop="76dp"
android:layout_marginEnd="167dp"
android:layout_marginBottom="173dp"
android:background="#BA1C1C"
android:onClick="stopButton"
android:text="#string/stop"
android:textColor="#android:color/white"
android:textColorHint="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/redLightImage"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
You can achieve your goal like this
Main Activity
Button buttonChangeLight;
ImageView imageLight;
int counter = 0;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChangeLight = findViewById(R.id.button);
imageLight = findViewById(R.id.redLightImage);
//to change lights
changeLight();
}
//change you light
public void changeLight(){
buttonChangeLight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(counter == 2){
counter = 0;
image.setImageResource(R.drawable.redLight);
}else if(counter == 1){
counter++;
image.setImageResource(R.drawable.yellowLight);
}else if(counter == 2){
counter++;
image.setImageResource(R.drawable.greenLight);
}
}
});
}
Hello (I was unable understand your problem but I uploaded the solution if this doesnt work let me know I'll try give better answer) You can do one thing here,
Initially add all the images(red,yellow,green) into the applications xml file all of them at the same place and then set the alpha of two of the images and as '0' from the attributes except the red image section then on every click of the button you set the alpha of the current image as zero and alpha of the second image as zero... so on and so forth
so the code will be something like this
boolean isred =true; //for red image
boolean isyellow = false; //for yellow image
boolean isgreen = false; // for green image
//button onclick listener
public void ChangeImage(View view){
if(isred == true){
RedImageView.animate().alpha(0).setduration(500); //500 milli-seconds it will
//give an animation effect
YellowImageView.animate().alpha(1).setduration(500);
isyellow = true;
isred = false;
}
if(isyellow == true){
YellowImageView.animate().alpha(0).setduration(500);
GreenImageView.animate().alpha(1).setduration(500);
isyellow = false;
isgreen = true;
}
if(isgreen == true){
GreenImageView.animate().alpha(0).setduration(500);
isgreen = false;
// now if you want to continue the same thing then you must add the below code
RedImageView.animate().alpha(1).setduration(500);
isred = true;
}
}

Create a clear button to clear canvas android

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.

Drawing Circles using Canvas and Framelayout android

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.

Update or change images in View during runtime

I have a little problem updating UI in OnClick Event.
When I do this:
case R.id.radStripMiningCoal :
{
LinearLayout testLayout = (LinearLayout)findViewById(R.id.layouttest);
LinearLayout layout3 = (LinearLayout)findViewById(R.id.layout2);
LinearLayout layout4 = (LinearLayout)findViewById(R.id.layout3);
LinearLayout layout = (LinearLayout)findViewById(R.id.recomended);
LinearLayout layout2 = (LinearLayout)findViewById(R.id.basic);
int origWidth = getWindowManager().getDefaultDisplay().getWidth();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(origWidth,LayoutParams.WRAP_CONTENT);
layout2.setLayoutParams(params);
layout.setLayoutParams(params);
testLayout.setLayoutParams(params);
layout3.setLayoutParams(params);
layout4.setLayoutParams(params);
stripminingcoal.setVisibility(View.VISIBLE);
VSLists.setVisibility(View.GONE);
Next.setVisibility(View.GONE);
AnimationDrawable animation = new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.multispd1), 5000);
animation.addFrame(getResources().getDrawable(R.drawable.img1), 5000);
animation.addFrame(getResources().getDrawable(R.drawable.shocktubecluster1), 5000);
animation.setOneShot(false);
ImageView imageAnim = (ImageView) findViewById(R.id.imgBasicIS);
imageAnim.setBackgroundDrawable(animation);
animation.start();
AnimationDrawable animation2 = new AnimationDrawable();
animation2.addFrame(getResources().getDrawable(R.drawable.unidelaysp), 5000);
animation2.addFrame(getResources().getDrawable(R.drawable.trunkline), 5000);
animation2.setOneShot(false);
ImageView imageAnim2 = (ImageView) findViewById(R.id.imgRecomendedIS);
imageAnim2.setBackgroundDrawable(animation2);
animation2.start();
AnimationDrawable animation3 = new AnimationDrawable();
animation3.addFrame(getResources().getDrawable(R.drawable.leadin2), 5000);
animation3.addFrame(getResources().getDrawable(R.drawable.tubestarter),5000);
animation3.setOneShot(false);
ImageView imageAnim3 = (ImageView) findViewById(R.id.imgRecomendedBSS);
imageAnim3.setBackgroundDrawable(animation3);
animation3.start();
txtBasicIS.setText("Shock Tube Multi SPD / Detonating Cord / Cluster");
txtRecomendedIS.setText("Shock Tube Uni-Delay SP / Trunkline");
txtRecomendedBSS.setText("Lead-In Line / Electric Shock Tube Starter");
Everything updates and displays fine.
But s soon as I do the same code in a different on "case" it does not update the images to the new images:
case R.id.radNarrowReefGold:
{
LinearLayout testLayout = (LinearLayout)findViewById(R.id.layouttest);
LinearLayout layout3 = (LinearLayout)findViewById(R.id.layout2);
LinearLayout layout4 = (LinearLayout)findViewById(R.id.layout3);
LinearLayout layout = (LinearLayout)findViewById(R.id.recomended);
LinearLayout layout2 = (LinearLayout)findViewById(R.id.basic);
int origWidth = getWindowManager().getDefaultDisplay().getWidth();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(origWidth,LayoutParams.WRAP_CONTENT);
layout2.setLayoutParams(params);
layout.setLayoutParams(params);
testLayout.setLayoutParams(params);
layout3.setLayoutParams(params);
layout4.setLayoutParams(params);
stripminingcoal.setVisibility(View.VISIBLE);
VSLists.setVisibility(View.GONE);
Next.setVisibility(View.GONE);
AnimationDrawable animation = new AnimationDrawable();
animation.addFrame(getResources().getDrawable(R.drawable.udlp3), 5000);
animation.addFrame(getResources().getDrawable(R.drawable.udlp6), 5000);
animation.addFrame(getResources().getDrawable(R.drawable.trunkline), 5000);
animation.setOneShot(false);
ImageView imageAnim = (ImageView) findViewById(R.id.imgBasicIS);
imageAnim.setBackgroundDrawable(animation);
animation.start();
AnimationDrawable animation2 = new AnimationDrawable();
animation2.addFrame(getResources().getDrawable(R.drawable.udlp3vivid), 5000);
animation2.addFrame(getResources().getDrawable(R.drawable.udlp6vivid), 5000);
animation2.addFrame(getResources().getDrawable(R.drawable.trunkline), 5000);
animation2.setOneShot(false);
ImageView imageAnim2 = (ImageView) findViewById(R.id.imgRecomendedIS);
imageAnim2.setBackgroundDrawable(animation2);
animation2.start();
AnimationDrawable animation3 = new AnimationDrawable();
animation3.addFrame(getResources().getDrawable(R.drawable.leadin2), 5000);
animation3.addFrame(getResources().getDrawable(R.drawable.tubestarter),5000);
animation3.setOneShot(false);
ImageView imageAnim3 = (ImageView) findViewById(R.id.imgRecomendedBSS);
imageAnim3.setBackgroundDrawable(animation3);
animation3.start();
txtBasicIS.setText("Uni-Delay LP (3) / Uni-Delay LP (6) / Trunkline");
txtRecomendedIS.setText("Shock Tube Uni-Delay SP / Trunkline");
txtRecomendedBSS.setText("Lead-In Line / Electric Shock Tube Starter");
}
What am I missing or doing wrong?
The textViews does not change either.
Thanks in advance.
Patrick
It is due to the missing "break;" statement in your switch case structure.
You can test this using the following small snippets i wrote on the fly. If you remove the break; statement, you could not swicth the text to MESSI, it shows only RONALDO. In other words, the logic is broken.
If the "break;" is there, you can switch between MESSI and RONALDO.
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
TextView myText;
private Button b1;
private Button b2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myText = (TextView)this.findViewById(R.id.textView1);
b1 = (Button)this.findViewById(R.id.buttonMessi);
b1.setOnClickListener(this);
b2 = (Button)this.findViewById(R.id.buttonRonaldo);
b2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.buttonMessi:
myText.setText("MESSI");
break;
case R.id.buttonRonaldo:
myText.setText("RONALDO");
break;
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="horizontal">
<Button
android:id="#+id/buttonMessi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignRight="#+id/textView1"
android:layout_marginBottom="40dp"
android:text="Messi" />
<Button
android:id="#+id/buttonRonaldo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignRight="#+id/textView1"
android:layout_marginBottom="40dp"
android:text="Ronaldo" />
</LinearLayout>
</RelativeLayout>
Try to add img.SetImageResource(0); before the previous line.
It worked kudos to you

NullPointerException with view.getLocationOnScreen

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.

Categories

Resources