首页 > 学院 > 开发设计 > 正文

自定义view-使用xml控制界面的呈现

2019-11-07 22:53:51
字体:
来源:转载
供稿:网友

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" />
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表