简体   繁体   中英

Android: how to encapsulate layout.xml in Object

I have layout file which I'm inflating dynamically on the screen. Then in my activity I have to init some UI logic (listeners, etc...).

But now this logic needs to be moved to some class. And I can't decide what way is the best to create view based object that has its layout in xml.

public MyView extends View {
    MyView(Context context) {
        super(context);
        //inflation here...        
    }

OR

MyViewFactory {
    View get(Inflater inflater) {

    }

OR something else?

May be someone can also recommend source code where to look for.

You probably don't want to do this with a simple view like ImageView. you want it to be a more complex layout like (linear layout containing buttons etc)?

In case you need the first you are best off with a simple view instance like ImageView img = new ImageView(context); or a factory if you have more parameters involved if you think its simpler setting them in xml.

As far as more complex layouts go i prefer using a custom class extending some of the viewGroups( Like: MyView extends LinearLayout )

create a function called init();

call the function from each constructor

implement inside it something like:

LayoutInflater.from(context).inflate(R.layout.my_layout,this,true);

this + true would mean that the layout will be attached to the root, in this case linearLayout and you can use findViewById directly on the viewgroup)

ImageView img = findViewById(R.id.myView);

i find it really important to create custom views since they always include logic that is specific to them and can be reused and also expose some public methods to invoke from the activities that include the custom view.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM