Atma
Atma

Reputation: 29805

Conditionally switch between layouts in Android

How do you switch between layouts in an activity and populate fields based on layout currently used?

For example if there is a logic in a view to load a view:

  if(category == 1){ 
      setContentView(R.layout.layout1);
  }else{
      setContentView(R.layout.layout2);
    TextView title = (TextView) findViewById(R.id.titleTV);
      title.setText("myTitle");

  }

If the else code is called the view never sets the title TextView to the String.

How do I accomplish conditionally going between the two views?

Upvotes: 2

Views: 1707

Answers (3)

Dimitris Makris
Dimitris Makris

Reputation: 5183

In case you want to flip across difference Views you can examine various possibilities, such as:

  • ViewPager via the compatibility library (http://android-developers.blogspot.com/2011/08/horizontal-view-swiping-with-viewpager.html)
  • ViewFlipper or ViewSwitcher (http://developer.android.com/reference/android/widget/ViewFlipper.html, http://developer.android.com/reference/android/widget/ViewSwitcher.html)
  • Or even a simple FrameLayout (http://developer.android.com/reference/android/widget/FrameLayout.html)

Hope this helps for now! In case you need anything specific please shoot it!

Upvotes: 1

aromero
aromero

Reputation: 25761

Another alternative would be to use Fragment. The advantage over the choices dimitris mentioned is that each fragment has it's own lifecycle, so you can delegate all code related to each view to its fragment, and keep your main activity clean.

To do this, simply use a FrameLayout in the Activity as a placeholder for the fragments. Fragments can communicate with the activity by using the listener pattern.

Upvotes: 2

havexz
havexz

Reputation: 9590

BTW have you considered Fragments. They are meant to deal with conditional layouts. Their basic motivation is screen sizes etc. But they can also fit your problem.

Refer to:

Upvotes: 0

Related Questions