安卓基本控件之Switch

来源:互联网 发布:postman ubuntu 编辑:程序博客网 时间:2024/06/05 03:22

布局文件

<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;
    }
    
}


0 0
原创粉丝点击