Toggle Button Example in android
Strings.xml
<?xml version="1.0"encoding="utf-8"?>
<resources>
<string name="app_name">Toggle Button1</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>
Activity_main.xml
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />
</RelativeLayout>
MainActivity.java
importandroid.app.Activity;
import android.os.Bundle;
import android.view.Menu;
importandroid.widget.CompoundButton;
importandroid.widget.CompoundButton.OnCheckedChangeListener;
importandroid.widget.Toast;
importandroid.widget.ToggleButton;
public class MainActivity extends Activity implementsOnCheckedChangeListener{
ToggleButton toggleButton1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton1=(ToggleButton)findViewById(R.id.toggleButton1);
toggleButton1.setOnCheckedChangeListener(this);
}
@Override
public booleanonCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public voidonCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked)
Toast.makeText(getApplicationContext(), "Button is on",Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Button is off",Toast.LENGTH_LONG).show();
}
}
Komentar
Posting Komentar