您的位置:首页 > 其它

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

2017-02-26 22:15 288 查看
1.首先我们需要在res目录下的values目录下创建attrs.xml资源文件文件并在里面配置我们需要添加的新功能

代码如下:

<re
4000
sources>
<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" />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐