How to check which image is linked to ImageView in android? - android

Well i have one button and one ImageView in my app.
What i am trying to do is when i pressing on the button then the image at the ImageView will change.
All i have are two pics file.
What i am trying to do is - if the first pic is linked to the ImageView than change it to pic2 by clicking on the button, and if pic2 is linked than a click on the button will change it back to the first pic file.
here's the onClick method i tried to use:
public void onClick(View v) {
ImageView ib1 = (ImageView)findViewById(R.id.imageView1)
View p1 = findViewById(R.drawable.pic1);
if(ib1.getResources()==R.drawable.pic1){
ib1.setImageResource(R.drawable.pic2);
}else{
ib1.setImageResource(R.drawable.pic1);
}
}
Thanks for any kind of help

Rather than checking the image, I would suggest set the information tag of the ImageView each time you change the image, like:
if(ib1.getTag() != null && ib1.getTag().toString().equals("pic1")){
ib1.setImageResource(R.drawable.pic2);
ib1.setTag("pic2");
} else {
ib1.setImageResource(R.drawable.pic1);
ib1.setTag("pic1");
}

private ImageView ib1;
private int currentImage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ib1 = (ImageView) findViewById(R.id.imageView1);
currentImage = R.drawable.pic1;
}
public void onClick(View view){
currentImage = (currentImage == R.drawable.pic1) ? R.drawable.pic2 : R.drawable.pic1;
ib1.setImageResource(currentImage);
}

You can also create a Boolean variable and assign it true and then if the boolean variable is true you change the picture of image button and set the boolean variable to false:- here my code example in java:-
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
android.view.View;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
ImageButton play_pause;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play_pause = findViewById(R.id.play_pause_button);
final boolean[] play_or_pause = new boolean[1];
play_pause.setImageResource(R.drawable.ic_baseline_play_arrow_24);
play_or_pause[0] = true;
play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (play_or_pause[0]) {
play_pause.setImageResource(R.drawable.ic_baseline_pause_24);
play_or_pause[0] = false;
}else {
play_pause.setImageResource(R.drawable.ic_baseline_play_arrow_24);
play_or_pause[0] = true;
}
}
});
}
}
and xml code:-
<?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"
android:background="#color/black"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView"
android:layout_width="252dp"
android:layout_height="48dp"
android:gravity="center"
android:text="TBT Music Player"
android:textColor="#color/white"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.087" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="247dp"
android:layout_height="263dp"
android:src="#drawable/ic_baseline_library_music_24"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.512"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.124" />
<SeekBar
android:id="#+id/seekBar"
android:layout_width="327dp"
android:layout_height="41dp"
android:thumbTint="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView2"
app:layout_constraintVertical_bias="0.163"
android:secondaryProgressTint="#color/white"/>
<ImageButton
android:id="#+id/play_pause_button"
android:layout_width="64dp"
android:layout_height="77dp"
android:backgroundTint="#color/black"
android:src="#drawable/ic_baseline_play_arrow_24"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/seekBar"
app:layout_constraintVertical_bias="0.213" />
</androidx.constraintlayout.widget.ConstraintLayout>

Related

What function should i use to open the activities of each button on android studio?

I'm having small problem on my project. I can't open the activities of each button after clicking it. I don't know if the codes I used are correct. please help me fix it. Thank you.
activity_main2.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=".MainActivity2"
android:background="#drawable/backgroundimg">
<Button
android:id="#+id/button"
android:layout_width="270dp"
android:layout_height="60dp"
android:backgroundTint="#android:color/holo_blue_dark"
android:text="Sleep"
android:textAllCaps="false"
android:textColor="#FFFFFF"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.299" />
<Button
android:id="#+id/button1"
android:layout_width="270dp"
android:layout_height="60dp"
android:backgroundTint="#android:color/holo_blue_dark"
android:text="Stress Reliever"
android:textAllCaps="false"
android:textColor="#FFFFFF"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.433" />
<Button
android:id="#+id/button2"
android:layout_width="270dp"
android:layout_height="60dp"
android:backgroundTint="#android:color/holo_blue_dark"
android:text="Calm"
android:textAllCaps="false"
android:textColor="#FFFFFF"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.57" />
<Button
android:id="#+id/button3"
android:layout_width="270dp"
android:layout_height="60dp"
android:backgroundTint="#android:color/holo_blue_dark"
android:text="Motivational Quotes"
android:textAllCaps="false"
android:textColor="#FFFFFF"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.701" />
<TextView
android:id="#+id/goodday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Good Day,"
android:textColor="#color/white"
android:textSize="20pt"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.078"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.04" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Melana!"
android:textColor="#color/white"
android:textSize="17pt"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.059"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.112" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity2.java
package com.example.serenityapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity2 extends AppCompatActivity {
Button butt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
butt1=(Button) findViewById(R.id.button);
butt1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
setContentView(R.layout.activity_stress);
}
});
}
}
This is what the app looks like and the four buttons should open their respective activities
This is just an example. As someone answered here, you could just search how to start a new activity.
butt1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent navigateToAnotherActivity = new Intent(this, SleepActivity.class);
startActivity(navigateToAnotherActivity);
}
});
to navigate from one activity to another intent is used
Intent intent = new Intent(this, TargetActivity.class)
startActivity(intent)
As I can see in the screenshot you provided. You have created 4 different activities. You just need to open them using the below code.
This code goes inside the onCreate() method of MainActivity2
public class MainActivity2 extends AppCompatActivity {
private Button bt_Sleep, bt_Stress_Reliever, bt_Calm, bt_Motivational_Quotes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
bt_Sleep = findViewById(R.id.button);
bt_Stress_Reliever = findViewById(R.id.button1);
bt_Calm = findViewById(R.id.button2);
bt_Motivational_Quotes = findViewById(R.id.button3);
bt_Sleep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent sleep = new Intent(MainActivity2.this, sleep.class);
startActivity(sleep);
}
});
bt_Stress_Reliever.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent stressReliever = new Intent(MainActivity2.this, stress.class);
startActivity(stressReliever);
}
});
bt_Calm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//calm change with your actual activity name
Intent calmIntent = new Intent(MainActivity2.this, calm.class);
startActivity(calmIntent);
}
});
bt_Motivational_Quotes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//motivational_quotes change with your actual activity name
Intent mq = new Intent(MainActivity2.this, motivational_quotes.class);
startActivity(mq);
}
});
}
}
This code should work.
Still facing problem comment here.

Toggle Button in Android

Can anyone help or share a link on how to implement this toggle button in android:
I've tried using this:
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Active"
android:textOff="Completed"/>
but it's not having the desired output.
It has only one button and it changes when i click on it. What i want is two buttons side by side as shown in the picture above.
With some research, i found a better way with the new Material Design. We need to use the MaterialButtonToggleGroup which is provided in the Android material library:
<com.google.android.material.button.MaterialButtonToggleGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:singleSelection="true"
app:checkedButton="#id/active">
<com.google.android.material.button.MaterialButton
android:id="#+id/active"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Active"
style="#style/Widget.MaterialComponents.Button.OutlinedButton"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/completed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Completed"
style="#style/Widget.MaterialComponents.Button.OutlinedButton"/>
</com.google.android.material.button.MaterialButtonToggleGroup>
Hope this helps other persons as well...
Custom Implementation ----
Colors
<color name = "background">#5cc0fa</color>
<color name = "white">#FFFFFF</color>
XML layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
>
<LinearLayout
android:id="#+id/linear_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/background"
android:orientation="horizontal"
tools:context=".MainActivity">
<Button
android:id="#+id/btn_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:textColor="#color/white"
android:background="#color/background"
android:text="All" />
<Button
android:id="#+id/btn_done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:textColor="#color/background"
android:background="#color/white"
android:text="Done" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
Inside Activity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
int var = 0;
Button btnAll;
Button btnDone;
LinearLayout linearLayout;
public void toggle() {
if(var == 0) {
var = 1;
btnAll.setBackgroundColor(getResources().getColor(R.color.white));
btnAll.setTextColor(getResources().getColor(R.color.background));
btnDone.setBackgroundColor(getResources().getColor(R.color.background));
btnDone.setTextColor(getResources().getColor(R.color.white));
} else {
var = 0;
btnAll.setBackgroundColor(getResources().getColor(R.color.background));
btnAll.setTextColor(getResources().getColor(R.color.white));
btnDone.setBackgroundColor(getResources().getColor(R.color.white));
btnDone.setTextColor(getResources().getColor(R.color.background));
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = findViewById(R.id.linear_layout);
btnAll = findViewById(R.id.btn_all);
btnDone = findViewById(R.id.btn_done);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toggle();
}
});
btnAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toggle();
}
});
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toggle();
}
});
}
}

onClick Method not working Android

I have a LandingPage with two Buttons, each pointing to a different activity.. None of the onClick Methods is functioning.. I know this is supposed to be really basic stuff but I cannot find the solution..
My code is the following:
public class LandingPage extends AppCompatActivity {
Button log_in, sign_up;
Typeface tfc_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing_page);
log_in = (Button) findViewById(R.id.LogIn_Button);
sign_up = (Button) findViewById(R.id.SignUp_Button);
setFontType();
addSoundtoButtons();
}
public void addSoundtoButtons(){
//Add Sound to the Buttons
final MediaPlayer mediaPlayer = MediaPlayer.create(this,R.raw.button_click_sound);
log_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaPlayer.start();
}
});
sign_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaPlayer.start();
}
});
}
public void setFontType(){
//Set Font Type for Buttons
tfc_button = Typeface.createFromAsset(getAssets(), "fonts/TEMPSITC.TTF");
log_in = (Button) findViewById(R.id.LogIn_Button);
sign_up = (Button) findViewById(R.id.SignUp_Button);
log_in.setTypeface(tfc_button);
sign_up.setTypeface(tfc_button);
}
public void OnClickButtonLogin(View view){
Intent intent = new Intent(this, SignInPage.class);
startActivity(intent);}
public void OnClickButtonSignUp(View view){
Intent intent = new Intent(this, SignUpPage.class);
startActivity(intent);
}
}
My Activity Layout is the Following:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
android:background="#drawable/landingpagenormal"
tools:context="com.example.gebruiker.prototype1oneplayerpurevisualisation.Activities.LandingPage">
<Button
android:id="#+id/LogIn_Button"
android:layout_width="171dp"
android:layout_height="57dp"
android:layout_marginBottom="17dp"
android:layout_marginStart="18dp"
android:background="#drawable/login_button"
android:onClick="OnClickButtonLogin"
android:text="Log In"
android:textColor="#FFEAEA"
android:textSize="35sp"
app:layout_constraintBottom_toTopOf="#+id/SignUp_Button"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/SignUp_Button"
android:layout_width="171dp"
android:layout_height="57dp"
android:onClick="OnClickButtonSignUp"
android:layout_marginBottom="38dp"
android:layout_marginStart="18dp"
android:background="#drawable/signup_button"
android:text="Sign Up"
android:textColor="#FFEAEA"
android:textSize="35sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
The Layout of the Landscape Mode of my Activity is the following:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
android:background="#drawable/landingpagelandscape"
tools:context="com.example.gebruiker.prototype1oneplayerpurevisualisation.Activities.LandingPage">
<Button
android:id="#+id/LogIn_Button"
android:layout_width="171dp"
android:layout_height="57dp"
android:layout_marginBottom="25dp"
android:layout_marginStart="100dp"
android:background="#drawable/login_button"
android:onClick="OnClickButtonLogin"
android:text="Log In"
android:textColor="#FFEAEA"
android:textSize="35sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/SignUp_Button"
android:layout_width="171dp"
android:layout_height="57dp"
android:layout_marginBottom="25dp"
android:onClick="OnClickButtonSignUp"
android:layout_marginEnd="100dp"
android:background="#drawable/signup_button"
android:text="Sign Up"
android:textColor="#FFEAEA"
android:textSize="35sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</android.support.constraint.ConstraintLayout>
Ok, so, you have two conflicting things. First, the onClick attribute in your layout:
android:onClick="OnClickButtonLogin"
Second, the setOnClickListener() in your Activity:
log_in.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaPlayer.start();
}
});
The second one will override the first. You should still see/hear the effects of mediaPlayer.start(), but you won't ever get a call to OnClickButtonLogin(). If you wanted to have both, you could remove the setOnClickListener() call and just add mediaPlayer.start() to the OnClickButtonLogin() method:
public void OnClickButtonLogin(View view) {
mediaPlayer.start();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}

ImageSwitcher now showing image

I am trying to run a simple app which displays an image with Animation on button click.All I see is a white screen.I am using exact code from the tutorial.Can any one tell me whats the problem?
This is the tutorial https://www.tutorialspoint.com/android/android_imageswitcher.htm
This is MainActivity.java
import...
public class MainActivity extends AppCompatActivity {
ImageSwitcher imageSwitcher;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageSwitcher=(ImageSwitcher)findViewById(R.id.img);
btn=(Button)findViewById(R.id.button);
imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
#Override
public View makeView() {
ImageView view = new ImageView(getApplicationContext());
view.setScaleType(ImageView.ScaleType.CENTER);
view.setLayoutParams(new
ImageSwitcher.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT));
return view;
}
});
Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
Animation out = AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right);
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "s", Toast.LENGTH_SHORT).show();
imageSwitcher.setImageResource(R.drawable.m1);
}
});
}
}
This is my xml file.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:custom="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="vaibhav.com.game.MainActivity">
<ImageSwitcher
android:id="#+id/img"
android:layout_width="324dp"
android:layout_height="419dp"
android:layout_margin="0dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="5dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.454"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
tools:layout_editor_absoluteX="57dp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp"
app:layout_constraintHorizontal_bias="0.439"
app:layout_constraintVertical_bias="0.946" />
</android.support.constraint.ConstraintLayout>

Android - In RelativeLayout, ImageView is not showing in the specific area

I'm new to android.
I'm trying to make a simple application.
There are two buttons(left and right) and an image.
Image moves left or right according to the clicked button.
The problem is like the following pictures :
LEFT button is clicked multiple times
RIGHT button is clicked several times
Moving left is OK, but when the image moves right, the image will disappear behind something. Please, let me know why the image disappears and how to fix this problem.
This is activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.alticast.avoidpoo.MainActivity">
<RelativeLayout
android:id="#+id/relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1">
<ImageView
android:id="#+id/img_android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/buttonLinearLayout"
android:layout_centerHorizontal="true"
android:visibility="visible"
app:srcCompat="#mipmap/ic_launcher" />
<LinearLayout
android:id="#+id/buttonLinearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<Button
android:id="#+id/btn_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/left"
android:visibility="visible" />
<Button
android:id="#+id/btn_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/right"
android:visibility="visible" />
</LinearLayout>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
This is MainActivity.class.
package com.alticast.avoidpoo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
int layout_width; // the width of relative layout
int layout_height; // the height of relative layout
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
public void init() {
Button btn_left = (Button) findViewById(R.id.btn_left);
Button btn_right = (Button) findViewById(R.id.btn_right);
btn_left.setOnClickListener(moveBtnClickListener);
btn_right.setOnClickListener(moveBtnClickListener);
final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relative_layout);
ViewTreeObserver vto = relativeLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
layout_height = relativeLayout.getMeasuredHeight();
layout_width = relativeLayout.getMeasuredWidth();
}
});
}
View.OnClickListener moveBtnClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ImageView img_android = (ImageView) findViewById(R.id.img_android);
int id = view.getId();
if (id == R.id.btn_left) {
int x = img_android.getLeft();
if (x-10 <= 0) return;
img_android.setLeft(x-10);
} else if (id == R.id.btn_right) {
int x = img_android.getLeft();
if (x+10 > layout_width-img_android.getWidth()) return;
img_android.setLeft(x+10);
}
}
};
}
==============================================================================
I solved this problem by using setLayoutParams() methods.
Guessing that calling setLeft () directly on the image view seems to be a bad idea. It seems to be the key to using LayoutParams.
The new MainActivity.class is the following. :
View.OnClickListener moveBtnClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ImageView img_android = (ImageView) findViewById(R.id.img_android);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)img_android.getLayoutParams();
int id = view.getId();
if (id == R.id.btn_left) {
if (params.leftMargin-10 < 0) return;
params.leftMargin = params.leftMargin - 10;
} else if (id == R.id.btn_right) {
if (params.leftMargin+10 > layout_width-img_android.getWidth()) return;
params.leftMargin = params.leftMargin + 10;
}
img_android.setLayoutParams(params);
}
};
In activity_main.xml, I just removed 'android:layout_centerHorizontal="true"' from the image view.
<ImageView
android:id="#+id/img_android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/buttonLinearLayout"
android:visibility="visible"
app:srcCompat="#mipmap/ic_launcher" />

Categories

Resources