You are on page 1of 2

MY TOGGLE BUTTON

LAYOUT

ATTRIBUTES

Component Attribute Value


LinearLayout orientation vertical
TextView id textView
layout_width 300dp
layout_heiight wrap_content
layout_marginTop 30dp
layout_marginLeft 30dp
text My Image
textSize 34sp
ImageView id imageView
layout_width 300dp
layout_height 200dp
layout_marginTop 30dp
layout_marginLeft 30dp
ToggleButton id toggleButtonShow
layout_width 300dp
layout_height wrap_content
layout_marginTop 30dp
layout_marginLeft 30dp
textOff Hide Image
textOn Show Image
CODE
MAINATIVITY.JAVA

package com.example.mytogglebutton;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

TextView textView;
ImageView imageView;
ToggleButton toggleButtonShow;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
imageView = findViewById(R.id.imageView);
toggleButtonShow = findViewById(R.id.toggleButtonShow);

toggleButtonShow.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
imageView.setVisibility(View.INVISIBLE);
textView.setText("My Image Hidden");
}
else{
imageView.setVisibility(View.VISIBLE);
textView.setText("My Image Shown");
}
}
});
}
}

You might also like