简体   繁体   English

Android-减少使用的活动数量

[英]Android - Reducing the number of activities used

I'm trying a method to reduce the number of total activities used in an application by switching layouts using the same activity. 我正在尝试一种方法,通过使用同一活动切换布局来减少应用程序中使用的活动总数。 What I am doing is - 我正在做的是-

/* Class A is the actual activity */
public class A extends Activity{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button but=(Button)findViewById(R.id.button1);
        but.setOnClickListener(new View.OnClickListener(){

        /*When the button is pressed, create an object of class B to switch layout*/
        public void onClick(View arg0) {
            B b=new B(A.this);
        }
        });
    }
}


/*Classs B handles some operation*/
public class B{

    Activity a;

    /*Set the new layout inside the constructor or call some other function to do that*/
    B(Activity act){
        a=act;
        a.setContentView(R.layout.newlayout);
    }

So, the Class B would switch the layout, do some operation. 因此,B类将切换布局,进行一些操作。 I would like to know whether this method is good practice, and also if there are other methods to do the same. 我想知道这种方法是否是好的做法,以及是否还有其他方法可以做到这一点。 Thanks 谢谢

Honestly i don't think is a good practice because in this way to keep alive several classes in your stack because they are referenced by the main activiy class that is always running so it could be a waste of resources. 老实说,我不认为这是一个很好的做法,因为通过这种方式来永葆几类中的筹码,因为它们是由始终运行,所以它可能是一种资源的浪费主要activiy类引用。

Managing several activities that handle specific task is much better in my opinion for 2 reason: 我认为管理两个处理特定任务的活动要好得多,这有两个原因:

  1. It adheres to the object oriented principles 它遵循面向对象的原则
  2. You delegate to the OS the task to manage resources. 您将任务委派给操作系统来管理资源。 For this reason activity class has a lifecycle in order to optimise the resources. 因此,活动类具有生命周期,以优化资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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