AndroMinor AndroMinor - 2 months ago 9
Java Question

hide and show button for an image is not working randomely in android

I am making a simple app for showing an image with a button and hiding that with another button. Button function is running nice when i click once on show and hide but after one click each, both stop responding. Please help and here is the code:-

package com.androminor.funcolor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class FunActivity extends AppCompatActivity {
Button button;
Button buttonHide;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fun);
buttonListener();
}
public void buttonListener() {

image = (ImageView)findViewById(R.id.imageView);
button = (Button)findViewById(R.id.buttonChange);
buttonHide = (Button)findViewById(R.id.buttonHide);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
image.setImageResource(R.drawable.golushapng);
}
});
buttonHide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
image.setVisibility(View.INVISIBLE);
}
});
}
}


--

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/relativelayout"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.androminor.funcolor.FunActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonChange"
android:text="@string/Golusha"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="108dp" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hide"
android:id="@+id/buttonHide"
android:layout_alignTop="@+id/buttonChange"
android:layout_alignParentEnd="true" />
</RelativeLayout>

Answer

That's because you've set the image's visibility to invisible when you click the hideButton. You need to make the image visible again.

In your first button's onClick listener, add the following line:

image.setVisibility(View.VISIBLE);
Comments