本文介绍了Android按钮onclick覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个具有预定义onClick
的CustomButton
.实际上,我的对象将完成与
I would like to create a CustomButton
which has a predefined onClick
.In fact, my object would do the same job than
CustomButton mButton = getViewById(..);
mButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
show_something()
}
是否可以将Listener
嵌入到从Button继承的CustomButton对象中?我想要的是在布局XML文件中创建一个CustomButton
,而不必在我的活动中提及此按钮,这样可以:
Is there a way to embed the Listener
into the CustomButton object that inherits from Button ?What I would like is to create a CustomButton
in my layout XML file, and not having to mention this button in my activity, which would give:
main.xml:
<LinearLayout xmlns:"...">
<com.mypackage.view.CustomButton
(attributes)/>
</LinearLayout>
CustomButton.java:
CustomButton.java:
class CustomButton extends Button implements... {
@Override
OnClick (or something like that, that's the core of my question, what to put here)
}
myActivity.java
myActivity.java
public class myActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
非常感谢.
推荐答案
您真的很亲密:
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class CustomButton extends Button implements OnClickListener{
public CustomButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public CustomButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomButton(Context context) {
super(context);
init();
}
private void init(){
setOnClickListener(this);
}
@Override
public void onClick(View v) {
// Do something
}
}
这篇关于Android按钮onclick覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!