공부/안드로이드(Android)

이벤트 - 토글 버튼(Toggle Button)

도도-도윤 2017. 11. 7. 21:52

이벤트 - 토글 버튼(Toggle Button)


토글 버튼을 활용한 이벤트 처리를 소개합니다.

조금 컴퓨터 사양이 좋으면 되겠습니다. 가상 버벅 거림이 있습니다.

i5 3세대에 SSD 컴퓨터를 사용하는 데, 버벅 거리는 현상이 있습니다.



1. 소개




  171107_ToggleBtn.zip




2. 코드



<?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"
tools:context="com.example.lab.program.MainActivity">

<ToggleButton
android:id="@+id/toggleBtn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Toggle on"
android:textOff="Toggle Off"
/>
</LinearLayout>

 main.xml

 

package com.example.lab.program;

import android.app.Application;
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 {

private View.OnClickListener toggleListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
ToggleButton toggleBtn = (ToggleButton)view;

if ( toggleBtn.isChecked() )
{
Toast.makeText(getApplicationContext(), "Checked", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Unchecked", Toast.LENGTH_SHORT).show();
}

}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final ToggleButton toggleBtn = (ToggleButton)findViewById(R.id.toggleBtn1);
toggleBtn.setOnClickListener(toggleListener);

}

}

 main.java



171107_ToggleBtn.zip
7.91MB