Android установить пользовательское значение для пользовательского просмотра текста программно - PullRequest
0 голосов
/ 19 ноября 2018

У меня есть пользовательский класс TextView. Я реализовал градиентный атрибут как цвет textview. Но мне удалось реализовать это только в xml. Я новичок в пользовательских представлений. Я не знаю, как я могу добавить setStartColor, setEndColor в свой пользовательский класс TextView.

Значения / атр

<declare-styleable name="GradientTextView">
    <attr name="startColor" format="color" />
    <attr name="endColor" format="color" />
</declare-styleable>

GradientTextView

public class GradientTextView extends AppCompatTextView {
    public GradientTextView(Context context) {
        super(context);

    }
    public GradientTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.GradientTextView);
        int startColor = a.getColor(R.styleable.GradientTextView_startColor, Color.WHITE);
        int endColor = a.getColor(R.styleable.GradientTextView_endColor, Color.WHITE);
        Shader myShader = new LinearGradient(0, 0, 0, 100,startColor, endColor, Shader.TileMode.CLAMP);
        this.getPaint().setShader(myShader);
        a.recycle();
    }  
}

XML

<mehran.design.GradientTextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:startColor="@color/yellow"
    app:endColor="@color/blue"/>

Ответы [ 2 ]

0 голосов
/ 19 ноября 2018

Как это:

public class GradientTextView extends AppCompatTextView {
        public GradientTextView(Context context) {
            super(context);

        }
        public GradientTextView(Context context, AttributeSet attrs) {
            super(context, attrs);
            TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.GradientTextView);
            int startColor = a.getColor(R.styleable.GradientTextView_startColor, Color.WHITE);
            int endColor = a.getColor(R.styleable.GradientTextView_endColor, Color.WHITE);
            Shader myShader = new LinearGradient(0, 0, 0, 100,startColor, endColor, Shader.TileMode.CLAMP);
            this.getPaint().setShader(myShader);
            a.recycle();
        }  

        public void setCustomColor(int startColor,int endColor){
            Shader myShader = new LinearGradient(0, 0, 0, 100,startColor, endColor, Shader.TileMode.CLAMP);
            this.getPaint().setShader(myShader);
            invalidate();
        }
    }
0 голосов
/ 19 ноября 2018

определить переменную startColor и endColor а также сеттеры для него

как

public void setStartColor(int color) {
    this.startColor= color;
    --- do your logic----
    invalidate();
}

Ссылка Ссылка

...