Android增加监听的三种实现方式


在Android中,为一个按钮增加监听的方式有三种

匿名内部类

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //加载布局文件
    setContentView(R.layout.activity_main);
    //获得布局中的按钮
    btn = (Button) findViewById(R.id.btn);
    //为按钮增加匿名内部类监听
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            //打印提示信息
            Toast.makeText(MainActivity.this, "匿名内部类实现监听", Toast.LENGTH_SHORT).show();
        }
    });
}

内部类

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //加载布局文件
    setContentView(R.layout.activity_main);
    //获得布局中的按钮
    btn = (Button) findViewById(R.id.btn);
    //内部类实现点击监听
    btn.setOnClickListener(new MyClickListener());
}
//定义一个内部类
class  MyClickListener implements OnClickListener{

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        Toast.makeText(MainActivity.this, "内部类实现监听", Toast.LENGTH_SHORT).show();
    }

}

实现接口

定义的Activity实现OnClickListener接口,并重新onClick()方法

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //加载布局文件
    setContentView(R.layout.activity_main);
    //获得布局中的按钮
    btn = (Button) findViewById(R.id.btn);
    //增加监听,传递this对象,this代表的是被点击的控件
    btn.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    // TODO Auto-generated method stub
    switch (view.getId()) {
    case R.id.btn:
        Toast.makeText(MainActivity.this, "实现接口实现监听", Toast.LENGTH_SHORT).show();
        break;
    }
}

注意点

如果在 Fragment 内部监听 Activity 控件事件时,使用内部匿名类必须将变量设为静态变量

/**
 * 
 * 程序主界面
 * 
 * @author Changweihua
 *
 */
public class MainActivity extends Activity {

    public static final int FILE_RESULT_CODE = 1;  
    //获得当前外部储存设备的目录
    static String SDCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
    static String DCIM = Environment.DIRECTORY_DCIM + File.separator;

    static MainActivity mainActivity;

    static RecursiveFileObserver listener = null;   

    static String listenFolder = null;

    static EditText etIP;
    static EditText etPort;
    static EditText folder;//选中文件夹
    static Button startButton;
    static Button stopButton;
    static Button selectButton;
    static ToggleButton toggleStatusButton;

    static String host;
    static String port;

    final PopupWindow popupWindow = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }

        mainActivity = this;

    }

    private static Handler mHandler = new Handler() {  

        @Override
        public void handleMessage (Message msg) {//此方法在ui线程运行  
            //new AlertDialog.Builder(null).setMessage(Environment.DIRECTORY_DCIM).show();
             super.handleMessage(msg);
             //if(msg.what == 1){
                 folder.setText(listenFolder);
            // }
        }  
    };  

    static Thread thread = new Thread(new Runnable(){

        @Override
        public void run() {
             Message message = new Message();
             message.what = 1;
             mHandler.sendMessage(message);
        }

    });

    public void SelectFolder() {

    }

    public void StopButton(View v) {
        System.out.println("直接绑定事件");
    }

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


    /**
     * 右键菜单处理
     */
    @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_rights) {
            new AlertDialog.Builder(this)    
                .setTitle("权限说明")  
                .setMessage("本程序会监听本机网络状态并进行提示,后台进行文件传输")  
                .setPositiveButton("好的", null)  
                .show();
            return true;
        }
//      }else if (id == R.id.action_about){
//          
//          popupWindow = new PopupWindow(, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, true);
//           
//            popupWindow.showAtLocation(findViewById(R.id.parent), Gravity.CENTER 
//                            | Gravity.CENTER, 0, 0);
//             popupWindow.setAnimationStyle(R.style.PopupAnimation);
//             // 加上下面两行可以用back键关闭popupwindow,否则必须调用dismiss();
//             ColorDrawable dw = new ColorDrawable(-00000);
//             popupWindow.setBackgroundDrawable(dw);
//             popupWindow.update();
//      }
        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);

            selectButton = (Button)rootView.findViewById(R.id.btnSelectFolder);
            startButton = (Button)rootView.findViewById(R.id.btnStart);
            stopButton = (Button)rootView.findViewById(R.id.btnStop);
            folder = (EditText)rootView.findViewById(R.id.etSelectedFolder);
            etIP = (EditText)rootView.findViewById(R.id.etIP);
            etPort = (EditText)rootView.findViewById(R.id.etPort);
            toggleStatusButton = (ToggleButton)rootView.findViewById(R.id.tbToggleStatus);

            final RadioButton rbUDP = (RadioButton)rootView.findViewById(R.id.radioUDP);
            final RadioButton rbWS = (RadioButton)rootView.findViewById(R.id.radioWS);

            RadioGroup group = (RadioGroup)rootView.findViewById(R.id.radioGroup);

            //绑定一个匿名监听器
            group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    // TODO Auto-generated method stub
                    ConstVars.tt = ConstVars.TransType.HTTP;
                    if(checkedId == rbUDP.getId()){
                        ConstVars.tt = ConstVars.TransType.UDP; 
                    }
                    if(checkedId == rbWS.getId()){
                        ConstVars.tt = ConstVars.TransType.WS; 
                    }

                }


            });

            if(folder != null){
                folder.addTextChangedListener(new TextWatcher() {

                    @Override
                    public void beforeTextChanged(CharSequence s, int start,
                            int count, int after) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start,
                            int before, int count) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        // TODO Auto-generated method stub
                        if(s.length() > 0){
                            toggleStatusButton.setEnabled(true);
                        }else {
                            toggleStatusButton.setEnabled(false);
                        }
                    }

                });
            }

            if(selectButton != null){
                selectButton.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                    // TODO Auto-generated method stub
                        //Intent intent = new Intent(MainActivity.this, MyFileManager.class);  
                        //startActivityForResult(intent, FILE_RESULT_CODE); 

                        //mHandler.obtainMessage(1).sendToTarget();;
                        listenFolder = SDCardRoot + DCIM + "Camera/";
                        thread.start();
                    }
                });
            }

            if(startButton != null){
                startButton.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        if(listener == null){
                            listener = new RecursiveFileObserver(listenFolder);
                        }
                        listener.startWatching(); 
                    }
                });
            }

            if(stopButton != null){
                stopButton.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        if(listener != null){
                            listener.stopWatching(); 
                        }
                    }
                });
            }

            if(toggleStatusButton != null){
                toggleStatusButton.setOnCheckedChangeListener(new OnCheckedChangeListener()  
                {  
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)   
                    {  

                        //NetworkHelper.HttpTest(mainActivity);

//                      if(!NetworkHelper.isNetworkAvailable(mainActivity)){
//                          new AlertDialog.Builder(mainActivity)    
//                              .setTitle("信息提示")  
//                              .setMessage("请检查手机是否已经连接到 WIFI")  
//                              .setPositiveButton("好的", null)  
//                              .show();
//                          return ;
//                      }

                        toggleStatusButton.setChecked(isChecked);  
                        MyLog.e("ToggleButton 按钮事件", isChecked ? "开启" : "关闭");
                        ConstVars.host = etIP.getText().toString();
                        ConstVars.port = Integer.parseInt(etPort.getText().toString());

                        ConstVars.upHost = "http://" + ConstVars.host;

                        if(isChecked){
                            //SyncHandler.folder = new File((Environment.DIRECTORY_DCIM)).getAbsolutePath() + File.separator + "Camera";
                            //SyncHandler.start();
                            if(listener == null){
                                MyLog.e("SDCardListener Status:", "Started");
                                listener = new RecursiveFileObserver(listenFolder);
                            }
                            listener.startWatching(); 
                        }else {
                            //SyncHandler.stop();
                            if(listener != null){
                                MyLog.e("SDCardListener Status:", "Stopped");
                                listener.stopWatching(); 
                            }
                        }

                    }  

                });
            }

            return rootView;
        }
    }

    /**
     * 
     * 匿名内部类作为事件监听器类
     * 
     * @author Changweihua
     * 
     */
    class UploadButton implements OnClickListener{
        @Override
        public void onClick(View v){
            System.out.println("内部类作为事件监听器");

            if(listener == null)
            {

            }

        }

    }

} 

知识共享许可协议
《Android增加监听的三种实现方式》 常伟华 创作。
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议 | 3.0 中国大陆许可协议进行许可。

站内公告