If SetContentView (new HellwView (this) is used all the time, it seems that there is always something missing, and the accessibility of defining components using XML in Android is lost, this is quite unpleasant. In this section, we will see a solution to the custom View error. Let's look at the definition of the View in XML.
1. A small error defining View in XML
We try to write the incorrect example directly.
Take out the View example in the previous lecture and modify the main layout:
<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
>
<TextView
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "@ string/hello"
/>
<Com. fxhy. stady. HelloView
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
/>
</LinearLayout>
Modify MainActivity
Super. OnCreate (savedInstanceState );
SetContentView (R. layout.Main); // Use a custom View
Run:
We found that an error was reported. We can view it in LogCat:
11-24 10:58:38. 993: ERROR/AndroidRuntime (323): Caused by: java. lang. NoSuchMethodException: HelloView (Context, AttributeSet)
There is no constructor HelloView (Context, AttributeSet), and the ending method is coming.
Ii. Solution
You only need to add the following methods in HelloView to solve the problem:
/**
* This is what we need to initialize in XML
**/
PublicHelloView (Context context, AttributeSet attrs ){
Super(Context, attrs );
}
Run:
There is a similar online problem about this solution: Why do we have to add this method? In fact, this method is used as a callback method when the system parses the attributes defined in XML. If you want to have a better understanding of View and the principles of the solution just now, you can follow my blog. I will explain it in the future "in-depth analysis of View principles, sometimes there may be a sense of openness.
3. View layout in XML
You can also add a View in XML using the following method:
<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
>
<TextView
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "@ string/hello"
/>
<View class = "com. fxhy. stady. HelloView"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
/>
</LinearLayout>
The running result is the same as above.