Cara menampilkan tombol switch di android studio

Tutorial Android

Cara menampilkan tombol switch di android studio

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent" android:layout_height="match_parent">

<Switch

android:id="@+id/switch1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:switchMinWidth="56dp"

android:layout_marginLeft="100dp"

android:layout_marginTop="120dp"

android:text="Switch1:"

android:checked="true"

android:textOff="OFF"

android:textOn="ON"/>

<Button

android:id="@+id/getBtn"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="150dp"

android:layout_marginTop="100dp"

android:text="Get" />

</RelativeLayout>

 

MainActivity.java

package com.example.switchexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.Switch;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private Switch sw1;

private Button btnGet;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

sw1 = (Switch)findViewById(R.id.switch1);

btnGet = (Button)findViewById(R.id.getBtn);

btnGet.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String str1, str2;

if (sw1.isChecked()) {

str1 = sw1.getTextOn().toString();

}

else {

str1 = sw1.getTextOff().toString();

}

Toast.makeText(getApplicationContext(), "Switch1 - " + str1 + " \n" ,Toast.LENGTH_SHORT).show();

}

});

}

}

 

 

Tinggalkan Balasan

Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai *