FrameLayout.LayoutParams doesn't work - android

I am trying to avoid the following situation in the activity( screen shot of the activity). When I add the margins using setMargins it does not work. I have tried adding margins via xml code and the end result is achieved but it very time consuming and it can't be guaranteed that it will work for all devices. How can i do it in code?
Here is the code.
package com.example.android.tourguide;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.FrameLayout;
public class TouristAttractions extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private NavigationView mNavigationView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_item);
/*
Finding the Toolbar that is defined in activity_main.xml via the id toolbar.
Note:The following three lines should be repeated for all the activities that are opened from the MainActivity. Also the toolbar should have an orientation
which is not zero.
*/
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_for_menu_items);
/*
Setting the action bar as the toolbar defined in the above code line
*/
setSupportActionBar(toolbar);
/*
Setting the title text color of the app bar.
*/
toolbar.setTitleTextColor(ContextCompat.getColor(this, R.color.color_of_text_of_app_bar));
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
/*
Finding the drawerLayout so that when the user clicks on the menu item of the navigation drawer it should close as we invoke the method closeDrawers()
*/
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
if (menuItem.getItemId() == R.id.home_menu) {
/*
Opening the home class that is the MainActivity when the Tourist Home menu button is clicked.
*/
Intent intentToOpenHomeClass = new Intent(TouristAttractions.this, MainActivity.class);
startActivity(intentToOpenHomeClass);
} else if (menuItem.getItemId() == R.id.entertainment_menu) {
Intent intentToOpenEntertainmentClass = new Intent(TouristAttractions.this, Entertainment.class);
startActivity(intentToOpenEntertainmentClass);
} else if (menuItem.getItemId() == R.id.gardens_menu) {
Intent intentToOpenGardenClass = new Intent(TouristAttractions.this, Garden.class);
startActivity(intentToOpenGardenClass);
} else {
mDrawerLayout.closeDrawers();
}
return true;
}
});
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout_for_menu_items);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager_for_menu_items);
AdapterForFragmentOfTouristAttraction adapterForFragmentOfTouristAttraction = new AdapterForFragmentOfTouristAttraction(this, getSupportFragmentManager());
viewPager.setAdapter(adapterForFragmentOfTouristAttraction);
tabLayout.setupWithViewPager(viewPager);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) toolbar.getLayoutParams();
params.setMargins(0, toolbar.getHeight(), 0, 0);
ActionBar actionbar = getSupportActionBar();
/*
actionBar.setDisplayHomeAsUpEnabled(true) will make the icon clickable and add the < at the left of the icon.
*/
actionbar.setDisplayHomeAsUpEnabled(true);
/*
Enabling the menu icon of the navigation.However note we are simply adding the menu icon however clicking on the icon does absolutely nothing.
*/
actionbar.setHomeAsUpIndicator(R.drawable.baseline_menu_white_24);
}
}

First of all, it might be a better idea to use a LinearLayout with a vertical orientation, a RelativeLayout, or a ConstraintLayout to position views below one another. In more exotic use cases even a CoordinatorLayout might be better suited.
FrameLayouts are mostly used to simply overlay views on one another, without depdendencies between them.
This said, the issue you are facing occurs because you use toolbar.getHeight() right after adding the view, which will always be 0. Try attaching a debugger and see for yourself!
The reason is that Android needs a bit of time to measure -> layout -> draw its views, and if you call getHeight right after adding the layout it will not have done either of those steps, leaving the values uninitialized, at 0.
There are ways around that, but again, you would be better off using a different layout alltogether. If you insist on using a FrameLayout the cleanest approach would be to extend it and create your own, where you can measure and layout the view yourself. The hacky, hard to maintain, and confusing approach would be to use ViewTreeObserver to listen for the changes and react to them. This is bad because you have to wait for a full layout pass before you trigger yet another one.
Don't use a FrameLayout here.

You havn't Done
yourView.setLayoutParams(params);

Related

Android - ActionBarToggle method not resolved by Android Studio

I'm trying to implement Material Navigation Bar. I followed someone's tutorial for it. But I'm facing a little problem. Android Studio resolves everything except for drawer_open and drawer_close parameters for the constructor of ActionBarDrawerToggle e.g.
mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,R.string.drawer_open,R.string.drawer_close)
Here it fails to resolve drawer_open and drawer_close. Google's Navigation Drawer sample works perfectly fine. I have imported all necessary packages. I can't figure out what's going wrong since I've just started learning android.
Full code of MainActivitiy is:
package com.startup.demo;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends ActionBarActivity {
//First We Declare Titles And Icons For Our Navigation Drawer List View
//This Icons And Titles Are holded in an Array as you can see
String TITLES[] = {"Home","Events","Mail","Shop","Travel"};
//int ICONS[] = {R.drawable.ic_home,R.drawable.ic_events,R.drawable.ic_mail,R.drawable.ic_shop,R.drawable.ic_travel};
//Similarly we Create a String Resource for the name and email in the header view
//And we also create a int resource for profile picture in the header view
String NAME = "Akash Bangad";
String EMAIL = "akash.bangad#android4devs.com";
//int PROFILE = R.drawable.aka;
private Toolbar toolbar; // Declaring the Toolbar Object
RecyclerView mRecyclerView; // Declaring RecyclerView
RecyclerView.Adapter mAdapter; // Declaring Adapter For Recycler View
RecyclerView.LayoutManager mLayoutManager; // Declaring Layout Manager as a linear layout manager
DrawerLayout Drawer; // Declaring DrawerLayout
ActionBarDrawerToggle mDrawerToggle; // Declaring Action Bar Drawer Toggle
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Assinging the toolbar object ot the view
and setting the the Action bar to our toolbar
*/
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are of fixed size
mAdapter = new MyAdapter(TITLES,NAME,EMAIL); // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
// And passing the titles,icons,header view name, header view email,
// and header view profile picture
mRecyclerView.setAdapter(mAdapter); // Setting the adapter to RecyclerView
mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager
Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout); // Drawer object Assigned to the view
mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
// open I am not going to put anything here)
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Code here will execute once drawer is closed
}
}; // Drawer Toggle Object Made
Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
mDrawerToggle.syncState(); // Finally we set the drawer toggle sync State
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Place the following string in strings.xml
drawer_open = "xxx"
drawer_close = "xxx"

How do I make a slide left/right menu in Android?

I'm trying to create a small game on Android and have some questions on a specific section of my game. I'm fairly new to android so please excuse if I don't have a full understanding of certain things.
When clicking "play" I'd like to view slide-able menu that makes it able for the user to swipe left and right to choose a level. Overtime I will be adding few more levels but have 2-3 of them now.
What would be the best way to do this? Is it best to implement a fragment for each "level page" or create entirely new activities?
My project is compatible for Android ver. 2.3.3 and above, so it's automatically included the "appcompat_v7" project. (I don't know if that makes a difference).
I've pasted my code below if needed:
package com.example.snake;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class SnakeLevelSelectActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snake_level_select);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.snake_level_select, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_snake_level_select, container, false);
return rootView;
}
}
}
What I intended to do was create several fragment classes and animate between the fragments when the user swipes. I also have issues understanding on how to use several fragments with the "PlaceHolderFragment" class, since the solutions I've found on SO have been different. This is an entirely question, but would be appreciated if it was answered as well.
What would be the best way to do this? Is it best to implement a fragment for each "level page" or create entirely new activities?
This is exactly what a Fragment is for. What you are looking for is already there and named ViewPager. Using ADT and Eclipse you can even create an Activity with this already implemented. Use the "Navigation type" combobox for that purpose:
You can also choose "Action Bar Tabs (with ViewPager)", which will enable Tabs in the ActionBar and make sure that you can switch to different Fragments using both the swipe gesture as well as the tabs.
Android now has this built-in in the SDK.
They call it the Navigation Drawer.
Look up the documentation it contains sample project, it is very easy to implement.

Get rid of fragments

I decided to not use fragments for now, although Android wants developers to now use it.
But I don't find it useful at the beginning. Unfortunately my IDE prepares everything to use fragments, so my question basically is, how to I get rid of everything, thats necessary for fragments? Is there a way to create a project without fragments? Thats what I did:
package com.pthuermer.juraquiz;
import java.io.IOException;
// import com.pthuermer.juraquiz.QuizActivity.PlaceholderFragment; // only necessary for Fragments
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build;
public class AppLaunch extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_launch);
/* FRAGMENTS
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
END FRAGMENTS */
// code goes here...
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.app_launch, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
* Useredit: not going to use fragments for now.
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_app_launch,
container, false);
return rootView;
}
}
*/
}
I think many people in the Android community will agree that fragments are not easy to handle and even draw new problems, some of them without even a decent proper solution.
Nevertheless, trying to remove all fragments from an app is not an easy task and might require good Android programming skills. You will have to convert your fragments either to views or activities, and that is not so easy to do, especially for activities containing multiple fragments.
The best option so far is to use mortar from Square, but this alternative is not totally ready and mature yet and using it requires, TMHO, advanced Android skills.
So, if I were a relatively new programmer in the Android world, I would keep fragments, get used to them, understand how they can be used to create reusable components and make apps that work on both phones and tablets.
After a while, when you will master them, you will find their drawbacks, and be able to look for alternatives.
I tried to study mortar from Square three times and still I haven't the slightest idea how to use it. So I went ahead and used Kotlin+Anko, switched all Fragments to Views and I'm more than happy - the code base is three times smaller, no dirty Fragment hacks, no NPEs that view has not been created for unknown reason, etc. Just implement views as follows:
class QuestionnaireView(ctx: Context, questions: List<Question>): _LinearLayout {
init {
orientation = LinearLayout.VERTICAL
for (question in questions) {
verticalLayout {
textView {
text = question.title
}.lparams(matchParent, wrapContent)
... etc - generate answer fields as necessary
}.lparams(matchParent, wrapContent)
}
}
}
Advantages:
Pass parameters using constructors like a human being, not via retarded arguments Bundle
No longer worry about the Fragment lifecycle and whether onCreateView() has yet been called or not.
Gets rid of exceptions thrown in Android's moveToState() mammoth method
Get rid of thousands layout.xml files stored in a single directory
Get rid of that styles.xml horrible mess
No need to define multiple layouts just to show a list+details on 720dp devices: just add if(screenWidthDp>=720) { detailView {} } to your init block.
Disadvantages:
No layout previews
Android Studio will become so slow it's almost useless.
You'll need to generate IDs for those views, otherwise their state will be lost on rotate

Slider Menu both side(right & left) in single Activity

I want slide Menu in both side(right & left) on single Activity
on Button click like below
i have tried this two library
https://github.com/jfeinstein10/SlidingMenu/
and
https://github.com/SimonVT/android-menudrawer
but both are give slide Menu only right or left side.
Yep Analizer has it right with setmode. Here's an example from jfeinstein10 library. Controlling the left menu with setMenu.. and the right with setSecondary...
https://github.com/jfeinstein10/SlidingMenu/blob/master/example/src/com/slidingmenu/example/LeftAndRightActivity.java
package com.slidingmenu.example;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import com.slidingmenu.example.fragments.ColorFragment;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.slidingmenu.lib.SlidingMenu.OnOpenedListener;
public class LeftAndRightActivity extends BaseActivity {
public LeftAndRightActivity() {
super(R.string.left_and_right);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSlidingMenu().setMode(SlidingMenu.LEFT_RIGHT);
getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
setContentView(R.layout.content_frame);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new SampleListFragment())
.commit();
getSlidingMenu().setSecondaryMenu(R.layout.menu_frame_two);
getSlidingMenu().setSecondaryShadowDrawable(R.drawable.shadowright);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.menu_frame_two, new SampleListFragment())
.commit();
}
}
Make sure to get a clean and updated copy of the library as well. Just in case.
I'm using the one at https://github.com/jfeinstein10/SlidingMenu/ and it works fine on both sides. Don't forget to set this to make it working:
getSlidingMenu().setMode(SlidingMenu.LEFT_RIGHT);
Using SimonVT's MenuDrawer you can achieve sliding menu on both sides using two menuDrawer instances as follows
leftmenu = MenuDrawer.attach(this, MenuDrawer.MENU_DRAG_WINDOW);
rightmenu = MenuDrawer.attach(this, MenuDrawer.MENU_DRAG_WINDOW,Position.RIGHT);
for button click please refer the examples in the library.
I think you can use https://github.com/jfeinstein10/SlidingMenu/ to achieve it.You should watch the demo.There is a left and right demo in it.Good luck!
Just adding to sooraj.e's answer, since it didn't worked for me at Simon VT's MenuDrawer last release.
This is working fine on it's last version (unfortunately deprecated)
mDrawerLeft = MenuDrawer.attach(MainActivity.this,
MenuDrawer.Type.BEHIND, Position.LEFT, MenuDrawer.MENU_DRAG_WINDOW);
mDrawerLeft.setDropShadowEnabled(false);
mDrawerLeft.setContentView(R.layout.activity1);
mDrawerLeft.setMenuView(R.layout.menu1);
mDrawerRight = MenuDrawer.attach(MainActivity.this,
MenuDrawer.Type.BEHIND, Position.RIGHT, MenuDrawer.MENU_DRAG_WINDOW);
mDrawerRight.setDropShadowEnabled(false);
mDrawerRight.setContentView(R.layout.activity1);
mDrawerRight.setMenuView(R.layout.menu2);
Library link: https://github.com/SimonVT/android-menudrawer/

Fragments: Remove all fragments in a view

The scenario I am faced with, is in my application I have a single pane and dual pane style layout. Rather than individually handle every single navigation operation possible between the screens, for every different style of layout, I am using a function which sets up the layout correctly when given the desired screen.
It is basically a switch statement for each screen in the app, with a nested switch statement in each screen to handle each layout style. This is what I'm talking about in code:
protected void setupScreen() {
switch(currentScreen) {
case SCREEN_ONE:
switch(currentLayout) {
case SINGLE_PANE:
// Perform actions to setup the screen
break;
case DUAL_PANE:
// Perform actions to setup the screen
break;
}
break;
case SCREEN_TWO:
switch(currentLayout) {
case SINGLE_PANE:
// Perform actions to setup the screen
break;
case DUAL_PANE:
// Perform actions to setup the screen
break;
}
break
// ... etc ....
}
}
In the section where I want to perform the actions to setup the screen, this consists of the following basic three operations:
// Create the fragments if necessary
if (screenFragment == null) {
screenFragment = new myFragment();
}
// Remove the existing fragments from the layout views
// HOW???
// Add the fragments for this screen to the view
getSupportFragmentManager().beginTransaction().add(pane1.getId(), myFragment, "myFragment").commit();
As you can see, what I am struggling with is how to do the second step. How do you remove all Fragments from a given View without knowing exactly which ones you are wanting to remove? The closest I have found is FragmentTransaction.replace() which does successfully do this for every case but when it turns out you are replacing a Fragment with the same fragment. In this case, it does not remove all, then add (like the documentation suggests), it just seems to remove. Is this an issue with using the compatibility libraries or is it not the way FragmentTransaction.replace() should be used?
In any case, how should I go about doing this? Do I have to code a removeAllFragments() function to go through every fragment and detach it or is there a way to do the first half of what the 'two in one' FragmentTransaction.replace() function claims to do?
None of the other answers were really working for me. Here's what I did:
List<Fragment> al = getSupportFragmentManager().getFragments();
if (al == null) {
// code that handles no existing fragments
return;
}
for (Fragment frag : al)
{
// To save any of the fragments, add this check.
// A tag can be added as a third parameter to the fragment when you commit it
if (frag == null || frag.getTag().equals("<tag-name>")) {
continue;
}
getSupportFragmentManager().beginTransaction().remove(frag).commit();
}
or, if you're forced to use it (but not recommended):
.commitAllowingStateLoss();
Also, if you're removing all fragments from the view multiple times, you might consider checking if the current frag is null or isDetached() or isRemoving() or you might get NullPointerExceptions.
Update: The documentation for getSupportFragmentManger().getFragments() is apparently hidden now, but still works just fine in my code. Here's the screenshot of the documentation:
Having said that, since it is hidden, they no longer want this method used, so see my update below.
Update 8-4-15: If you're not using the support library for fragments, there is unfortunately no getFragments() available, but there are still a couple, more inconvenient, options.
Give each fragment a tag or id upon creation, and iterate through them to process each fragment as desired.
Create a listener using onAttachListener so each time a new fragment is attached to the activity, you can store that fragment, and then iterate through that data structure to process each fragment as desired.
When not using the getSupportFragmentManager(), to process a transaction you will need to use getFragmentManager() instead.
The typical mechanism is to use FragmentManager.findFragmentByTag() . You use this and add tags to your fragments (or the alternative for id's). This way you can determine what fragments are currently being managed. Then, once you have a handle to a present fragment (findFragmentByTag returns non-null), you can use FragmentManager.beginTransaction() to start a FragmentTransaction and remove / add the necessary fragments. Working in this way will allow you to avoid the 're-adding' process for the fragment you want to keep.
What I'd probably do is have code like so: (warning psuedo code)
Fragment pane1 = FragmentManager.findFragmentByTag("myFragmentPane1");
Fragment pane2 = FragmentManager.findFragmentByTag("myFragmentPane2");
setupScreen(pane1, pane2);
You should also consider sub-classes of your class instead of having 'everything in one class'. You have a fairly obvious case of Martin Fowler's Replace Conditional with Subclass. Otherwise, I fear this is going to be incredibly hard to manager when you add another screen.
If you use android.support.v4.app.Fragment you can do this:
List<Fragment> fragments = getSupportFragmentManager().getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
}
}
Turns out FragmentTransaction.replace() is the correct operation and should work correctly. It only does not work when using ActionBarSherlock and SherlockFragmentActivity so I can only assume it is a bug in this compatibility library.
I have confirmed this through using the code below to implement the desired behaviour through Android on API11+, the android compatibility library, and ActionBarSherlock. It only breaks in the last instance.
package com.test.test;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.os.Bundle;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends SherlockFragmentActivity {
// Consistent fragment instance
myFragment myFrag = null;
// Views
FrameLayout fl = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
Button b = new Button(this);
b.setText("Repeat");
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Reattach the same fragment
getSupportFragmentManager().beginTransaction().replace(fl.getId(), myFrag).commit();
}
});
fl = new FrameLayout(this);
fl.setId(200);
fl.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
myFrag = new myFragment();
getSupportFragmentManager().beginTransaction().add(fl.getId(), myFrag).commit();
ll.addView(b);
ll.addView(fl);
setContentView(ll);
}
public static class myFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView tv = new TextView(getActivity());
tv.setText("My fragment");
tv.setGravity(Gravity.CENTER);
tv.setBackgroundColor(Color.RED);
return tv;
}
}
}
This is more or less how I have handled this. Have all your fragments implement an interface something like:
public interface NamedFragment{
public FragmentName getFragmentName();
}
Make an enum corresponding to your fragments:
public enum FragmentName{
SOME_FRAGMENT,
SOME_OTHER_FRAGMENT;
}
Then in your fragment switching activity:
// Get the manager and transaction separately so you can use both:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
// Get a reference to the fragment(s) currently in the container(s)
Fragment currentFragment = fragmentManager.findFragmentById(position);
FragmentName cFragmentName =
((NamedFragment) currentFragment).getFragmentName();
Fragment nextFragment =
Fragment.instantiate(this, some_new_fragment_string);
FragmentName nFragmentName =
((NamedFragment) nextFragment).getFragmentName();
// Compare the "names"
if(cFragmentName != nFragmentName){
ft.replace(position, nextFragment);
}
You'll have to change things around a little to fit your particulars.

Categories

Resources