How does the Android skin changing function dynamically obtain the resource ID of the background picture in the control?

This is a problem encountered when doing a skin change function.

For skin change, there are examples on the Internet. You can read the required resources from other skin installation packages, on the premise that you must first hold the reference name of this resource, such as r.drawable Background (hey, this is not nonsense). The principle of this skin changing scheme is that the resource name of its own application is r.drawable Background, which should also be the name in the skin package, and then obtain the specific ID of the resource in the skin package through this name. Code:

In this skin changing scheme, each activity needs to traverse the entire layout when switching skin to judge the control. If the ID contains the character "skin", it means that the control is a control that needs skin changing, and the ID of the control can be saved first.

Code to traverse the view

The problem is, in a local application, you hold a control, such as a button, whose ID can directly call button The getid () method gets the background image, but we can call button The getbackground () method gets its object, but there is no method to get the reference name of the resource image, so we can't get its specific ID. The solution that comes to mind later is that each time an activity initializes, we traverse the attribute set attributeset of each control in advance. If there is a control that needs to be skinned, save the value of its Android: background attribute. Therefore, we need to overload the oncreateview (string name, context, attributeset, attributes) method of the activity, My understanding of this method is that it will be called before the initialization of each control (including LinearLayout, textview, button, etc.) in the activity. I also logged and verified it. The attrs parameter is the property set of the control, which is what we need. Code:

With this backgroundid, you can get the reference name of the resource r.drawable Background, and then we can get the corresponding resource files from other packages by name, so that we can perform the skin changing operation. Moreover, through this method, you can obtain not only the ID of the image resource, but also the string, such as r.string Title, font color, such as r.color Red, font size such as r.dimensions text_ size_ Small and other attributes, so as to expand the scope of skin change.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>