佈局文件
<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:checked="true" 默認選中狀態
Switch 4.0之後使用
-->
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="開"
android:textOff="關"
android:checked="true"
android:onClick="OnclickSwitch"
/>
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/bg1"
android:layout_centerInParent="true"
/>
</RelativeLayout>
Java代碼
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Switch;
public class MainActivity extends Activity {
//聲明控件
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//通過findViewById 找出相應的控件
iv = (ImageView) findViewById(R.id.iv);
}
//switch的點擊事件
public void OnclickSwitch(View v){
Switch switch1 = (Switch) v;
boolean isChecked = switch1.isChecked();
if(isChecked){
iv.setImageResource(R.drawable.bg1);
}else{
iv.setImageResource(R.drawable.bg);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}