ToggleButton的使用有感
今天用到ToggleButton开关按钮,由于给他设置错了监听事件,效果不是所想 原来用的多的还是监听状态的改变。写一个例子,显示效果才明白。
package com.rotunda.test;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.CompoundButton;import android.widget.TextView;import android.widget.ToggleButton;public class ToggleButtonTest extends Activity { /** Called when the activity is first created. */private ToggleButton tg;private TextView tv,tvc;private static boolean ischecked=false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tg=(ToggleButton)findViewById(R.id.togglebutton_displaychart_showgrid); tv=(TextView)findViewById(R.id.textview_main_showtest); tvc=(TextView)findViewById(R.id.textview_main_showclick);// tg.setOnCheckedChangeListener(tgcheckedlistener); tg.setOnClickListener(tgclicklistener);// this.p } ToggleButton.OnClickListener tgclicklistener=new OnClickListener() {public void onClick(View v) {// TODO Auto-generated method stubif(ischecked){tvc.setText("click ischecked");}else{tvc.setText("click not checked");}} }; ToggleButton.OnCheckedChangeListener tgcheckedlistener=new ToggleButton.OnCheckedChangeListener() {public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {// TODO Auto-generated method stubif(isChecked){tv.setText("checked");ischecked=true;System.out.println("ischecked==="+ischecked);}else{tv.setText("not checked");ischecked=false;System.out.println("ischecked==="+ischecked);}} };}
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><TextView android:id="@+id/textview_main_showtest" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/textview_main_showclick" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <ToggleButton android:id="@+id/togglebutton_displaychart_showgrid" android:layout_width="70dip" android:layout_height="wrap_content" android:layout_marginLeft="10dip" android:textOff="网格" android:textOn="网格" /></LinearLayout>可以试着观察一下来了解