我试图通过扩展 Button 类来创建一个可重用的按钮。我只是尝试一些基本的设置背景颜色和按钮文本的方法。我对在哪里/如何调用扩展 Button 的类中的 init 方法有点困惑。我知道我可以用样式设置这些字段,但我希望有一种方法可以在类里面做到这一点。我希望在类中设置 if 条件来确定按钮是否会改变透明、颜色、形状和其他属性。
这是类(class),
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,
<?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>
最佳答案
我想这就是你想要的。
换句话说,您只在类中创建了一个 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");
}
}
关于java - 可重复使用的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41248373/