<ToggleButton android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ToggleButton" />
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="30dp" android:text="Check Your Status ?" /> <ToggleButton android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="90dp" android:text="ToggleButton" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/toggleButton1" android:layout_below="@+id/textView1" android:layout_marginTop="32dp" android:text="TextView" /> </RelativeLayout>
package com.myapp; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.TextView; import android.app.AlertDialog; import android.widget.ToggleButton; import android.graphics.*; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final AlertDialog.Builder adb = new AlertDialog.Builder(this); // textView2 final TextView textView2 = (TextView)findViewById(R.id.textView2); textView2.setText("Current Status is Off"); textView2.setTextColor(Color.RED); final ToggleButton toggleBtn = (ToggleButton)findViewById(R.id.toggleButton1); toggleBtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click AlertDialog ad = adb.create(); if(toggleBtn.isChecked() == true) { textView2.setText("Current Status is On"); textView2.setTextColor(Color.GREEN); ad.setMessage("Current Status is On"); ad.show(); } else { textView2.setText("Current Status is Off"); textView2.setTextColor(Color.RED); ad.setMessage("Current Status is Off"); ad.show(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท