Is it better to create new Activities or just create a different Layout and replace the existing layout?

前端 未结 3 473
野的像风
野的像风 2021-01-06 17:19

Since I am new to Android, I am now thinking on what is the correct way of doing things.

As it stands, the application I\'m writing has 4 different screens:

3条回答
  •  梦毁少年i
    2021-01-06 18:04

    You should probably use a separate Activity for each screen; otherwise you need to end up keeping track of which individual View is currently being displayed, plus the state of all those not currently being displayed when the user switches to another window, or a call comes in etc.

    It's easier to keep track of this state if you just use a separate Activity for each piece of functionality.

    If you do decide to keep everything in a single Activity however, you could look at the TabActivity class. However, there are also caveats there that prevent you from having an Activity as the tab content.

    • Android: Why shouldn't I use activities inside tabs?

    Regarding your follow-up, you unfortunately cannot attach an Intent directly to a Button like you can with a MenuItem via the XML, however you could just extend Activity to make your own common base class with some code that hooks up the listeners.

    Something like:

    public class BaseActivity extends Activity {
        protected View.OnClickListener mButtonListener;
    
        protected void setupHeaderButtons() {
            findViewById(R.id.header_btn_1).setOnClickListener(mButtonListener);
            // ...
            findViewById(R.id.header_btn_n).setOnClickListener(mButtonListener);
        }
    }
    
    public class FirstActivity extends BaseActivity {
        @Override
        public void onCreate(Bundle b) {
            super.onCreate(b);
            setContentView(R.layout.first_activity);
    
            // This needs to be done *after* the View has been inflated
            setupHeaderButtons();
        }
    }
    

提交回复
热议问题