思路:通过点击根据按钮的选择状态与false状态设置图片的路径
1.布局文件:
<LinearLayout 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" 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" > <!-- textOn为true状态,textOff为false状态 --> <ToggleButton android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ToggleButton" android:textOff="关" android:textOn="开" /> <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/img1" /> </LinearLayout>
2.MainActivity.java
package com.example.mooc; import android.app.Activity; import android.os.Bundle; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.MultiAutoCompleteTextView; import android.widget.ToggleButton; public class MainActivity extends Activity implements OnCheckedChangeListener { private Button login_button; private ToggleButton toggleButton; private ImageView imgView; private ImageButton img_button; private AutoCompleteTextView autoCompleteTextView1; private MultiAutoCompleteTextView mutiple; private String res[] = { "beijing1", "beijing2", "beijing3" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 将布局文件引入到Activity setContentView(R.layout.toggle_button); toggleButton = (ToggleButton) findViewById(R.id.toggleButton1); imgView = (ImageView) findViewById(R.id.imageView1); toggleButton.setOnCheckedChangeListener(this); } /** * arg0:代表组件本身 * arg1代表选中状态 */ @Override public void onCheckedChanged(CompoundButton arg0, boolean arg1) { // 按钮被点击的时候此函数执行 imgView.setBackgroundResource(arg1?R.drawable.ic_launcher:R.drawable.img1); } }
3.效果:(false的时候显示收纳袋,true的时候显示安卓图标)
点击后
时间: 2024-10-09 17:07:44