I'm creating an Android application. I need to override the draw
method on a number of UI classes to create a custom appearance. These classes all subclass View
. I'm wondering what the best way to do this is. I'd like to be able to reuse code as much as possible, so I'm looking for help in organizing things. As I see it right now, I have 2 options:
Option 1 - Subclass Everything
If I want to use LinearLayout
, I create CustomLinearLayout
. If I want to use ImageView
, I create CustomImageView
. On each of these custom classes, I override draw
exactly the same way. This doesn't seem efficient because I'm repeating code and extending a number of classes which do almost nothing.
Option 2 - Subclass a Super Class
My original thought was to extend View
and create CustomView
, because it's already a superclass of all the classes I want to use. This, however, doesn't work because all the existing subclasses I want to use are still extending View
, not CustomView
.
Is there a better way to do this? Am I missing something?
One possible solution would be to extract your draw logic into a separate class DrawingCode
. This could contain a static method or you could even use instances of DrawingCode
to customize your drawing code with other parameters. Of course you'll still have to overwrite the draw()
method, but only write one line of code to call DrawingCode.draw(param1, param2)
. This way you get to store your drawing code in one central place and don't repeat yourself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.