AndroidManifest.xml:
MainActivity.java:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.blogspot.codingatharva.manualprograms"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
MainActivity.java:
package com.blogspot.codingatharva.manualprograms; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.ToggleButton; public class MainActivity extends AppCompatActivity { private ToggleButton tb1; private ImageButton img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tb1 = findViewById(R.id.tb1); img = findViewById(R.id.img); tb1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(tb1.isChecked()) { img.setVisibility(View.VISIBLE); } else { img.setVisibility(View.INVISIBLE); } } }); } }
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" android:padding="10dp" tools:context=".MainActivity"> <ImageButton android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/logo" /> <ToggleButton android:id="@+id/tb1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:checked="true" android:text="On" /> </LinearLayout>
Output: