Domanda

final View view1 = getLayoutInflater().inflate( R.layout.activity, homescreen, false);

We are using getLayoutInflater() to inflate custom views in an activity. So flow is when user clicks on one button we remove one view and inflate another view in same activity. Now problem with this approach is if use click on back key of phone, application comes out of activity. What we really want is to get to previous layout.

  1. Is there method provided by android that we should implement?
  2. Handle back keys on SetOnKeyListner of each view
  3. Handle onBackPressed() of activity to see which view is currently on and manually inflate another view
  4. Use fragment transaction?
  5. Any other approach?
È stato utile?

Soluzione 2

1.Is there method provided by android that we should implement?

No. Although it is acceptable to replace views within an Activity, there is no convenient way of keeping a View collection and navigating between them.

2.Handle back keys on SetOnKeyListner of each view

Definitely not.

3.Handle onBackPressed() of activity to see which view is currently on and manually inflate another view

Handling BACK press is something which should only be done when absolutely necessary. What you have to remember is users of Android devices will expect a regular use and feel - deviating too far from expected behaviour may make your app less appealing. In saying that, depending on what your app does, handling BACK at the Activity level might be acceptable BUT you still have no easy way of managing a stack of Views.

4.Use fragment transaction?

Yes. Definitely the preferred approach. Fragments combine sub-Activity functionality as well as a View in a modular form. The OS will also handle the back stack for you making your life much easier when it comes to coding the app.

Altri suggerimenti

i would recomment you to use Fragments

you can add fragments to the backstack so you can manage your backnavigation in the app.

Best one will be implementing your logic using ViewFlipper or Pager, there you can navigate between views and control them via buttons. Considering your scenario, you can change view or page through on touch of buttons, both the widget have very good support for that.

During back press, you can easily navigate back to previous page until it reaches first, and after that you can simply finish your activity.

Hope it help.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top