自定义View的Listener

从写C#的年代开始,我经常在面试程序员的时候问这个一个简单得不能再简单的问题:Java(or C#)中,接口是干什么用的?

很可惜的是,非常多简历上写着“精通java开发”的童鞋们都答不上来。最近改一个Android程序,在Activity和View之间用全局Handler把消息传来传去,颇有古时候用go to语句搞noodle program的架势。

无奈重构,用Listener回调来传递消息,上代码,先定义Listener,然后在自定义View里插入回调,Activity里重写回调方法:

MyViewListener

package com.net.laonan.plum.views;

/**
 * Created by Alan on 15/12/16.
 */
public interface MyViewListener {
    void onLaonanShow(boolean naked);
}

MyView

package com.net.laonan.plum.views;

import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by Alan on 15/12/18.
 */
public class MyView  extends FrameLayout {

    private TextView tvPrompt;
    private EditText etMyInput;

    private MyViewListener _listener;

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.my_view, this);
        etUsername = (EditText) findViewById(R.id.et_username);
        etCombination.setOnKeyListener(new EditText.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
               String userName = etUsername.getText().toString();
               if(userName.equals("laonan.net") {
                     _listener.onLaonanShow(true);   
               }    
            }
        });
    }


    public void setListener(MyViewListener listener) {
        _listener = listener;
    }
}

MainActivity

package com.net.laonan.plum.views;
import android.util.Log;
import android.app.Activity;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyView myView = (MyView)findViewById(R.id.my_view1);
        myView.setListener(new LaonanListener());
    }

    private class LaonanListener implements MyViewListener {
        @Override
        public void onLaonanShow(boolean naked) {
            if(naked)
                Log.d("laonan.net", "Laonan is naked!");
            else
                Log.d("laonan.net","Laonan is not naked!");
        }
    }
}

xml布局文件极简单,不写了。

Android Listener Handler 接口
Views (3557) Comment (0) 2015-12-23
For example, "name@something.com". If someone replies to you it will be via email.
For example, "http://someaddress.com"