source code:
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MyView extends LinearLayout {
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.MyViewText);
TextView textView=new TextView(context);
int count=typedArray.getIndexCount();
for (int i = 0; i < count; i++) {
int attr=typedArray.getIndex(i);
switch (attr) {
case R.styleable.MyViewText_Text:
int resource=typedArray.getResourceId(R.styleable.MyViewText_Text, 0);
System.out.println(resource);
if(resource>0){//通过引用设值方式
textView.setText(typedArray.getResources().getText(resource));
}else{//通过直接设值方式
textView.setText(typedArray.getString(R.styleable.MyViewText_Text));
}
break;
default:
break;
}
}
addView(textView);
System.out.println("getChildCount:"+getChildCount());
System.out.println(getChildAt(0));
setBackgroundColor(0xaa00aa);
typedArray.recycle();
}
}
layout code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res/com.zhonghong.tsp.share"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<view class="com.demo.view.MyView" android:layout_width="wrap_content" android:layout_height="wrap_content" app:Text="@string/app_name">
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"/>
</view>
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"/>
</RelativeLayout>
attrs.xml code
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyViewText">
<!--同时兼容两种设值方式-->
<attr name="Text" format="reference|string"></attr>
</declare-styleable>
</resources>