2014年12月2日 星期二

Android Switch

java

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class MainActivity extends Activity {

private Switch mSwitch;
private TextView mViewShow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewShow = (TextView)findViewById(R.id.tv_show);
mSwitch = (Switch)findViewById(R.id.switch_def);
mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener(){
       
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Log.d("dddddd", "hi");
if (isChecked) {
mViewShow.setText(getString(R.string.text_on));
} else {
mViewShow.setText(getString(R.string.text_off));
}
}
});
}

}





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:orientation="vertical"
>
    <TextView 
        android:id="@+id/tv_show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        
/>

    <Switch
        android:id="@+id/switch_def"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/tv_show"
        android:layout_marginTop="22dp"
        android:textOff="@string/text_off"
        android:textOn="@string/text_on" />
    
</RelativeLayout>





string.xml



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

    <string name="app_name">SwitchTest</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="text_on">On</string>
    <string name="text_off">Off</string>

</resources>




沒有留言:

張貼留言