我试图通过扩展button类来创建一个可重用的按钮。我只是尝试一些基本的设置背景颜色和文本的按钮。对于如何在扩展Button的类中调用init方法,我有点困惑。我知道我可以用一种样式来设置这些字段,但是我希望有一种方法可以在这个类中实现。我希望在类中设置if条件,以确定按钮是否会从透明、颜色、形状和其他属性中更改。
这是课程,
public class SVButton extends Button {
public SVButton(Context context) {
super(context);
}
public SVButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SVButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private void init(Context context) {
Button SVColorButton = new Button(getContext());
SVColorButton.setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary));
SVColorButton.setText("Push Me");
}
}
以下是我所称的customWidget按钮,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.agar098.atomicdesigndemos.MainActivity">
<com.example.agar098.atomicdesigndemos.CustomWidgets.SVButton
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
发布于 2016-12-20 09:56:48
我想这就是你想要的。
换句话说,您只在类中创建了一个new Button();
,实际上没有扩展任何内容。
public class SVButton extends Button {
private Context mContext;
public SVButton(Context context) {
super(context);
this.mContext = context;
init();
}
public SVButton(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
init();
}
public SVButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
init();
}
private void init() {
this.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorPrimary));
this.setText("Push Me");
}
}
发布于 2016-12-20 10:08:33
1.当您没有在xml中定义并直接使用下面的.按钮时
final SVButton svButton = new SVButton(this);
构造函数下面的将调用
public SVButton(Context context) {
super(context);
init();
}
2.在xml中定义按钮时,如下面所示
<com.example.agar098.atomicdesigndemos.CustomWidgets.SVButton
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
在构造函数下面的将调用
public SVButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
https://stackoverflow.com/questions/41248373
复制相似问题