Android中自定义veiw使用Java中的回调方法
//------------------MainActivity----中----------------------------------
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
private MyButton myButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到控件
myButton = (MyButton) findViewById(R.id.bt_mybutton);
myButton.setonButtonClickListener(new OnButtonClickListener() {
@Override
public void OnButtonClick() {
Toast.makeText(MainActivity.this, "在Activity中点击了Button", 0).show();
}
});
}
//---------------------布局文件中-----自定义button--------------
<com.bw.huidiao.MyButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bt_mybutton"
android:text="点击回调"/>
//------------------自定义button - 创建一个类继承button实现3个又参构造方法----------------------------------------
package com.bw.huidiao;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
public class MyButton extends Button implements OnClickListener{
private Context context;
public MyButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public MyButton(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
this.context=context;
setOnClickListener(this);
}
@Override
public void onClick(View v) {
//Toast.makeText(context, "在MyButton中点击了Button", 0).show();
listener.OnButtonClick();
}
private OnButtonClickListener listener;
//接口回调
//定义接口
public interface OnButtonClickListener{
public void OnButtonClick();
}
//暴露给外界一个方法,方便调用
public void setonButtonClickListener(OnButtonClickListener listener){
this.listener=listener;
}
}