How to start new activity on button click

后端 未结 24 1655
傲寒
傲寒 2020-11-21 05:54

In an Android application, how do you start a new activity (GUI) when a button in another activity is clicked, and how do you pass data between these two activities?

24条回答
  •  醉酒成梦
    2020-11-21 06:33

    An old question but if the goal is to switch displayed pages, I just have one activity and call setContentView() when I want to switch pages (usually in response to user clicking on a button). This allows me to simply call from one page's contents to another. No Intent insanity of extras parcels bundles and whatever trying to pass data back and forth.

    I make a bunch of pages in res/layout as usual but don't make an activity for each. Just use setContentView() to switch them as needed.

    So my one-and-only onCreate() has:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        LayoutInflater layoutInflater = getLayoutInflater();
    
        final View mainPage = layoutInflater.inflate(R.layout.activity_main, null);
        setContentView (mainPage);
        Button openMenuButton = findViewById(R.id.openMenuButton);
    
        final View menuPage = layoutInflatter.inflate(R.layout.menu_page, null);
        Button someMenuButton = menuPage.findViewById(R.id.someMenuButton);
    
        openMenuButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setContentView(menuPage);
            }
        });
    
        someMenuButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                do-something-interesting;
                setContentView(mainPage);
            }
        }
    }
    

    If you want the Back button to go back through your internal pages before exiting the app, just wrap setContentView() to save pages in a little Stack of pages, and pop those pages in onBackPressed() handler.

提交回复
热议问题