为什么在OnCreate应在活动开始调用一次?应在、OnCreate

2023-09-12 05:00:27 作者:不期而遇

我想知道,为什么的OnCreate()在活动开始只调用一次?

I would like to know, why OnCreate() is called only once at the start of an activity?

我们可以称之为的OnCreate()不止一次在同一个活动呢?

Can we call OnCreate() more than once in the same activity?

如果是的,比我们怎样才能把它?谁能举个例子?

If yes, than how can we call it? can anyone give an example?

非常感谢!

推荐答案

为什么要再次叫的吗?除非活性被重建,这就是所谓的由系统。你不能打电话的OnCreate手动,这是一样的道理,为什么你会不会叫的setContentView()的两倍。作为文档:

Why would you want to called it again? unless the activity is reconstructed, which is called by system. You cannot call OnCreate manually , it is the same reason why you won't call setContentView() twice. as docs:

的onCreate(包)是你初始化你的活动。最   重要的是,在这里你会通常所说的setContentView(INT)与   布局资源定义你的用户界面,并使用findViewById(int)以   检索您需要与互动在UI中的小部件   编程。   一旦你完成初始化小部件,为什么你会吗?

onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically. Once you finish init your widgets Why would you?

更新 我需要一些背单词,你可以手动做到这一点,但我还是不明白为什么会这样叫。您是否尝试过片段? 样品code:

UPDATE I take some words back, you CAN do this manually but I still don't understand why would this be called. Have you tried Fragments ? Samplecode:

public class MainActivity extends Activity implements OnClickListener {
        private Button btPost;
        private Bundle state;
        private int counter = 0;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            state = savedInstanceState;
            btPost = (Button) findViewById(R.id.btPost);
            btPost.setOnClickListener(this);
            Toast.makeText(getBaseContext(), " " + counter, Toast.LENGTH_LONG)
                    .show();
        }

        @Override
        public void onClick(View v) {
            counter++;
            this.onCreate(state);
        }
    }
 
精彩推荐
图片推荐