java - 可重复使用的按钮

标签 java android android-layout

我试图通过扩展 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/

相关文章:

java - Spring:对我的 ThreadFactory 使用 "Lookup method injection"看起来不可扩展

java - JPA/Hibernate 只写字段,不读取

java - 如何检查图像大小小于 100kb android

android - 添加可绘制资源

Android onCreate 或 onStartCommand 用于启动服务

Android 用 xml 中的另一个线性布局替换线性布局

android - 以编程方式将边距设置为 CardView

java - 面积图更改默认颜色

java - 在android中对 map 进行排序

android - 将 ViewPager 作为一行放置在 ListView 中