Android: Adding Background on a Custom TextView class

淺唱寂寞╮ 提交于 2019-11-28 05:40:17

问题


I want to have a background of my TextView class, but I don't know how. I try to use the onDraw method on the class but it is not working.

Here is my code for my custom TextView class.

public class Balls extends TextView{

public Balls(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
    this.setText("ball");
}

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    Paint paint = new Paint();
    paint.setColor(Color.RED);
    canvas.drawCircle(50, 50,30, paint);
}}

Any idea how can I fix this code? Thanks.


回答1:


You can set Background in following way,

public class Balls extends TextView{

    public Balls(Context context) {
        super(context);
        this.setText("ball");
        this.setBackgroundColor(R.drawable.imageName);
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        canvas.drawCircle(50, 50,30, paint);
    }
}

I used

 this.setBackgroundColor(R.drawable.imageName);

in constructor to set Background Image.Also you can set background color in same way.




回答2:


Try setBackground or setBackgroundResource




回答3:


See Scale Drawable and Shape Drawable



来源:https://stackoverflow.com/questions/12851608/android-adding-background-on-a-custom-textview-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!