xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
This is to declare the namespace. If you want the attributes of your own life to be meaningful in the View, you need to add a namespace prefix to the attribute, such as "android" or "app".
We can define our own namespace to use custom attributes
Steps :
1 Declare the namespace:
xmlns:zsg="http://schemas.android.com/apk/res-auto"
Note here:
If you want to use your custom attributes in eclipse, you cannot use res-auto,
you must replace it with the package to which your custom view belongs (xmlns:myxmlns=""http://schemas.android.com/ apk/res/<package name of your application>"), if the custom attribute you just used is made into lib, you can only use res-auto, and in android-studio, whether you are You can only use res-auto if you write your own custom view or the custom view in the referenced lib. The previous way of writing the package name was abandoned in android-studio.
2 Custom attributes are
in attrs. xml file to define custom attributes
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="TestView"> <!--Attribute name attribute type --> <attr name="text" format="string" /> <attr name="textColor" format="color" /> </declare-styleable> </resources>
3 Use custom attributes in the layout file
where MyView is a custom view
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:zsg="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <com.zsg.mytextview.MyView android:layout_width="match_parent" android:layout_height="30dp" zsg:text="This is a custom attribute" zsg:textColor="#ff0000"/> </RelativeLayout>
4 Get the value in the custom attribute in MyView
public class MyView extends View { public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); //get TypedArray TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TestView); String text = (String)a.getText(R.styleable.TestView_text); int textColor = a.getColor(R.styleable.TestView_textColor, 0xff000000); Log.d("test", "text:" + text); Log.d("test", "textColor:" + textColor); a.recycle(); } }
Output:
For the usage of TypeArray and AttributeSet, please refer to
http://blog.csdn.net/lmj623565791/article/details/45022631