代码如下,无法运行。没有报错
这是MainActivity.xml的
package com.example.test4; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.ToggleButton; public class MainActivity extends Activity implements OnCheckedChangeListener{ private ToggleButton tb; private ImageView img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //初始化控件 tb = (ToggleButton) findViewById(R.id.toggleButton1); img = (ImageView) findViewById(R.id.imageView1); // 给当前的tb设置监听器 tb.setOnCheckedChangeListener(this); } public void onCreateOptionsMenu(CompoundButton buttonView,boolean isCheckde) { // 当tb被点击的时候 当前的方法会执行 // buttonView 代表被点击的控件的本身 // ischeckde 代表被点击的控件的状态 // 当点击这个tb的时候 更换img 的背景 // img.setBackgroundResource(isCheckde?R.drawable.on:R.drawable.off); img.setBackgroundResource(isCheckde?R.drawable.on:R.drawable.off); // Inflate the menu; this adds items to the action bar if it is present. } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } } @Override public void onCheckedChanged(CompoundButton arg0, boolean arg1) { // TODO Auto-generated method stub } } 这是activity-main.xml的 <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" > <ToggleButton android:id="@+id/toggleButton1" android:checked="false" android:textOn="开" android:textOff="关" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/off" /> </LinearLayout>