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

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

Related

How to add values by holding button in countdowntimer

I am making boxing countdown timer and to set how long round supposed to last I am using two button first "+" and second "-" my time add every 5 seconds ex "5,10,15,20,25..." but I always I have to click to add 5 second. I would like to hold button and my value will add automatically what should I do?
I hope I add every important information in my question
my code from buttons and display
public void dodawanie1(View view) {
iloscrund=iloscrund+1;
display(iloscrund);
public void odejmowanie1(View view) {
if(iloscrund>1){
iloscrund=iloscrund-1;
display(iloscrund);
}
}
private void display(int numer) {
TextView displayInteger=(TextView) findViewById(R.id.textView16);
displayInteger.setText("" + numer);
}
odejmowanie means decrease value
dodawanie means increase value
If you mean to determine between click and hold, use onTouchListener to determine hold button event.
onTouchListener
I think you should use Runnable and Handler class for do it.
this link should be useful.
Android: Implement a 1 second interval timer before calling a function
activity_auto_inc.xml
<?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=".AutoIncActivity">
<TextView
android:id="#+id/num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:gravity="center"
android:text="1"
android:textSize="26sp"
android:textColor="#color/black"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/add"
android:text="add"
android:textColor="#color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/num" />
</androidx.constraintlayout.widget.ConstraintLayout>
AutoIncActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AutoIncActivity extends AppCompatActivity implements
View.OnLongClickListener, View.OnTouchListener {
Button add;
TextView txt;
boolean isAddPressed = false;
Handler handler;
final int TIME_INTERVAL = 100;
final int STEP = 1;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_inc);
handler = new Handler();
add = findViewById(R.id.add);
txt = findViewById(R.id.num);
add.setOnLongClickListener(this);
add.setOnTouchListener(this);
}
#Override
public boolean onLongClick(View view) {
if (view.getId() == R.id.add) {
isAddPressed = true;
handler.postDelayed(new AutoInc(), TIME_INTERVAL);
}
return false;
}
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_UP ||
motionEvent.getAction() == MotionEvent.ACTION_CANCEL) {
isAddPressed = false;
}
return false;
}
private class AutoInc implements Runnable {
#Override
public void run() {
if (isAddPressed) {
txt.setText(String.valueOf(Integer.parseInt(txt.getText().toString()) +
STEP));
handler.postDelayed(this, TIME_INTERVAL);
}
}
}
}

How to hide next button and show when radio group button is selected

How to I hide the next button and will only show when the user choose a radio group button
I have this XML code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="#+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/assembly"
android:checked="false"
/>
<RadioButton
android:id="#+id/csharp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="false"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/java"
android:checked="false" />
<Button
android:id="#+id/btnDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NEXT"
android:onClick="OnClick"
/>
</RadioGroup>
</LinearLayout>
and this class code
package com.example.quiz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
/**
* Created by leste on 3/5/2016.
*/
public class CS_Category extends Activity {
private RadioGroup radioSexGroup;
private RadioButton radioSexButton;
private Button btnDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cs_category);
addListenerOnButton();
}
public void addListenerOnButton() {
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioSexGroup.getCheckedRadioButtonId();
radioSexButton = (RadioButton) findViewById(selectedId);
if (radioSexButton.getId() == R.id.assembly) {
Intent i = new Intent(CS_Category.this, CS_Assembly.class);
startActivity(i);
} else {
if (radioSexButton.getId() == R.id.csharp) {
Intent i = new Intent(CS_Category.this, CS_Csharp.class);
startActivity(i);
} else {
if (radioSexButton.getId() == R.id.java) {
Intent i = new Intent(CS_Category.this, CS_Java.class);
startActivity(i);
}
}
Toast.makeText(CS_Category.this,
radioSexButton.getText(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
What should I do to hide the next button and show only if there is a selected radio button
In your button xml you should use:
android:visibility="gone"
In java you should use:
btnDisplay.setVisibility(View.VISIBLE);
First of all I would take the button out of the radio group and just have it be below it. Then in my java code I would have this function:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.assembly:
if (checked)
make_button_visible();
break;
case R.id.csharp:
if (checked)
make_button_visible();
break;
}
}
Make sure that each radio button has onClick="onRadioButtonClicked" set.
Then have a function called make_button_visible() that has these lines:
Button mButton=(Button)findViewById(R.id.btnDisplay);
mButton.setVisibility(View.VISIBLE);//This will make it visible
add below code in your onCreate method
addListenerOnButton();
btnDisplay.setVisibility(View.INVISIBLE);
radioSexGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if (btnDisplay.getVisibility() == View.INVISIBLE)
btnDisplay.setVisibility(View.VISIBLE);
}
});

Animation on Android

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

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.

Changing the position of the thumb of the SeekBar using a different Button

I'm trying to move the position of the seekbar using a button. Basically I have a seekbar from 0 to 100. and I have button presents set up at arbitrary values (40,50,60 etc). When I try to set the progress on the seekbar via button, I get a fault.. I've already initialized the seekBar in the onCreate() method.
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar1);
currentProgress = 40;
seekBar.setMax(100);
seekBar.setProgress(currentProgress);
button40.setOnClickListener(button40Listener);
But when use the below, it crashes.
private OnClickListener button40Listener = new OnClickListener() {
public void onClick(View v) {
currentProgress = 40;
seekBar.setProgress(currentProgress);
}
}
This seems straight-forward. Any ideas?
You shouldn't need to put up another Seekbar. The initial one should be fine. Without the exception message and stack trace I'm not sure what is causing the crash. However, I just coded an example and works as you would expect. Perhaps by looking at my example you can identify your issue.
SeekbarTest.java:
package com.example.seekbartest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
public class SeekbarTest extends Activity {
/** Called when the activity is first created. */
private SeekBar seekBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
seekBar = (SeekBar)findViewById(R.id.seekBar1);
Button fortyPctButton = (Button)findViewById(R.id.buttonFortyPct);
fortyPctButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
seekBar.setProgress(40);
}
});
Button sixtyPctButton = (Button)findViewById(R.id.buttonSixtyPct);
sixtyPctButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
seekBar.setProgress(60);
}
});
Button eightyPctButton = (Button)findViewById(R.id.buttonEightyPct);
eightyPctButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
seekBar.setProgress(80);
}
});
}
}
And here is the main.xml it is referencing for the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:text="#string/hello"
android:id="#+id/textView1"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/seekBar1"
android:layout_below="#+id/textView1"
android:layout_alignLeft="#+id/textView1"
android:layout_alignRight="#+id/textView1"/>
<Button
android:layout_width="wrap_content"
android:text="40%"
android:id="#+id/buttonFortyPct"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBar1"
android:layout_alignLeft="#+id/seekBar1"/>
<Button
android:layout_width="wrap_content"
android:text="60%"
android:id="#+id/buttonSixtyPct"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/buttonFortyPct"
android:layout_alignTop="#+id/buttonFortyPct"
android:layout_alignBottom="#+id/buttonFortyPct"/>
<Button
android:layout_width="wrap_content"
android:text="80%"
android:id="#+id/buttonEightyPct"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/buttonSixtyPct"
android:layout_alignTop="#+id/buttonSixtyPct"
android:layout_alignBottom="#+id/buttonSixtyPct"/>
</RelativeLayout>
Just create a new android app and replace the generated code + layout with the example above. It should work for you.
Good luck,
Craig

Categories

Resources