【发布时间】:2017-04-09 20:58:53
【问题描述】:
我有一个非常简单的“CustomButton”类,它扩展了默认的“Button”类。我的 CustomButton 使用 onTouchEvent 并且我想将一个函数从我的 Activity 传递给 CustomButton 并让它在触地时执行。
CustomButton 类工作正常,但我似乎不知道如何将函数传递给它。
活动:
public class mainActivity extends Activity
{
@Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
Context context = getApplicationContext();
setContentView( R.layout.main );
LinearLayout root = (LinearLayout) findViewById( R.id.myLayout );
View child1 = getLayoutInflater().inflate( R.layout.child, null );
// Define the button
final CustomButtom myCustomButton = (CustomButtom)child1.findViewById( R.id.button_id );
myCustomButtom.setCallback( test ); // <-- I want to pass my 'test' function to CustomButton class,
// so it can get executed by the onTouchEvent
root.addView( myCustomButton );
super.onCreate( savedInstanceState );
}
private int test()
{
Log.d( "test", "Callback executed!" );
}
}
这是我的 CustomButton 类:
public class CustomButtom extends Button
{
private Function callback;
public CustomButtom(Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnTouchListener
(
new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
executeCallback(); // <-- My callback would get executed from here
}
return true;
}
}
);
}
public void setCallback(Function function)
{
callbackFunction = function; // Save the callback in a local variable
}
private boolean executeCallback()
{
return callbackFunction.execute(); // execute the callback
}
}
是否有我可以用于此目的的“数据类型”,例如“功能”,或者有不同的方法来实现这一点?谢谢!
【问题讨论】: