Safe to pass instance of an Activity to another object?

后端 未结 1 1304
春和景丽
春和景丽 2021-02-10 08:42

What I\'m basically trying to do is pass an instance of my Activity to another object which will build the dynamic UI.

The main reason I\'m doing this is to keep the Act

1条回答
  •  再見小時候
    2021-02-10 09:22

    In my opinion it is not a good idea to pass the ACTIVITY somewhere - actually I'm not sure whether this will do anything at all.

    What you can do is:

    1 - You can create your own class, extending View class, build your UI there. What you have to pass to that class is your activity context!

    for example:

    class Custom_UI_Builder extends View {
        public  Custom_UI_Builder(Context cxt) {
            super(cxt);
            // more stuff - your UI components...
        }
    }   
    

    in the Activity that uses you 'UI class'

    public myActivity extends Activity{
        @Override
    public void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
    
        myView = new Custom_UI_Builder(this);
    
                //what every else you need...
    
            mainLayout = new LinearLayout(this.getApplicationContext());
        mainLParam = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        mainLayout.setLayoutParams(mainLParam);
        mainLayout.setOrientation(LinearLayout.VERTICAL);
                mainLayout.addView(myView, LayoutParams.MATCH_PARENT, 390);
        setContentView(mainLayout);
    
    }}
    

    2 - Then you can create an instance of your custom_UI_builder class in your Activity.

    I'm not sure if this will have any unwanted effects on memory load.

    Hope it will work!

    0 讨论(0)
提交回复
热议问题