Android 如何为TextView设置默认背景的形状?

Android 如何为TextView设置默认背景的形状?,android,android-studio,Android,Android Studio,我需要将我的形状设置为所有文本的默认背景,但我不知道怎么做,我想在我的项目中添加许多TextView,所以这对我来说非常重要,我已经尝试过搜索互联网,但没有成功:(试试这个代码 import android.content.Context; import android.graphics.Typeface; import android.util.AttributeSet; import android.widget.TextView; public class CustomTextView

我需要将我的形状设置为所有文本的默认背景,但我不知道怎么做,我想在我的项目中添加许多
TextView
,所以这对我来说非常重要,我已经尝试过搜索互联网,但没有成功:(

试试这个代码

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class CustomTextView extends TextView{
 public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomTextView(Context context) {
        super(context);
        init();
    }

    public void init() {
        if(!isInEditMode()){

            setBackgroundResource("Your shape file id ");// like r.drawable.shape_textview
        }

    }
}

创建自定义
TextView
将引导您,您可以在构造函数中设置默认背景:请详细解释,无法理解,是否要设置TextViewbackground@Amir Palang@AmirPalang还请确保阅读Stackoverflow文档页面以创建自定义视图:。请尝试这两种方法,并用您想要的内容编辑您的问题到目前为止还没有。很好,luckcan,你不可以在xml上这样做吗?检查一下,我不知道为什么这个答案被标记为已接受。这与将形状创建为可绘制的无关。只需在xml上设置
background
属性,而不是为此创建一个全新的类@AmirPalang@Sanoop你知道如何创造吗android中的形状文件?请向谷歌学习,然后创建一个简单的形状文件,并将形状文件放在像R.drawable.your_shape_文件名而不是“your shape file id”这样的位置.那么创建
CustomTextView
类的目的是什么,既然你已经在形状和背景方面有了经验,那么回答我,
android:background=“@drawable/white\u text\u view\u style”的目的是什么
如果您有一个可绘制的
白色编辑\文本\样式
在xml/android中的这一行,并且如果widget的更改已经可以通过提供的默认widget属性实现,则不建议为其创建一个类,我不是说您没有错,但该方法太长,这是对e问题。我想你完全误解了我的观点,我想说的是答案与形状无关或有助于创建形状,它只是在drawable文件夹中添加了对形状文件的引用,同样可以在
xml
本身上进行,并继续学习android中的形状文件。我也会做同样的Happie编码:)