質問

I'm a beginner to Android development and I'm implementing an address book app. This app will need an 'add contact' screen and an 'edit contact' screen. These screens are going be pretty similar - 'add contact' is essentially going to be the 'edit contact' screen but for a new blank contact and with a different title in the action bar. Should I implement them as separate layouts and activities (they are going to be accessed using different buttons) or is there a way that I can avoid duplicate code (maybe using strategy objects or something?)

Thanks for any advice.

役に立ちましたか?

解決

Use same activity, layout and code. The only difference between edit and add is that in first case you have an Account object (a class of your own), while in the other you don't have.

So in onCreate after you've setup the views you can perform a check if in getIntent() (assuming that for edit the caller activity put the object in intent) you have that Account object and if so, retain it and fill the activity views with its properties. Also you can change here the header - edit or add.

When pressing on a save button/action menu, if you have the Account object already you'll perform an update, while for the other case (object retained is null) you'll perform an add.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top