09 January 2017

Android: ButtonToggle - Công tắc ON OFF (Android Studio)

activity_main.xml
Java Android 2017
<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ToggleButton
        android:id="@+id/btn_toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        />
</RelativeLayout>
MainActivity.java
Java Android 2017
package com.example.lonely.buttontoggle;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ToggleButton btnToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnToggle = (ToggleButton) findViewById(R.id.btn_toggle);
        btnToggle.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (btnToggle.isChecked()) {
            Toast.makeText(this, "Toggle ON", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Toggle OFF", Toast.LENGTH_SHORT).show();
        }
    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang