1.首先我们需要在res目录下的values目录下创建attrs.xml资源文件文件并在里面配置我们需要添加的新功能
代码如下:
<resources>
<declare-styleable name="tvAttrs">
<attr name="leftText" format="string"/>
<attr name="rightText" format="string"/>
</declare-styleable>
</resources>
2.之后就使我们的自定义控件了代码如下
public class MyTextView extends android.support.v7.widget.AppCompatTextView {
String titles="";
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta=context.obtainStyledAttributes(attrs,R.styleable.tvAttrs);
String leftText=ta.getString(R.styleable.tvAttrs_leftText);
String rightText=ta.getString(R.styleable.tvAttrs_rightText);
ta.recycle();
titles=leftText+rightText;
setText(titles);
}
}
3.最后在xml中调用并且设置相关属性
代码如下
<com.example.kangjiahang.testpicasso.MyTextView
android:id="@+id/tv_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:leftText="adc"
app:rightText=" dde"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />