I want to auto scroll a list item to top (firstVisible item) in my recycler view and get the view at that position, so I can highlight it, from my fragment.
So, this is the gist of my fragment code :
private void activateNewListItem(int position) {
mLayoutManager().scrollToPositionWithOffset(position, 0);
RecyclerView.ViewHolder viewHolder = mRecyclerView.findViewHolderForLayoutPosition(position);
View view = viewHolder.getItemView();
view.setBackgroundColor(getResources().getColor(R.color.esr_light_grey));
}
If position is 1,2,3,4 etc, mRecyclerView.findViewHolderForPosition(position) returns a valid ViewHolder,
because I guess RecyclerView has drawn ViewHolders for those indexes in dataSet.
However, if I pass in position as say, 25, mRecyclerView.findViewHolderForPosition(position) returns null, because I assume, it hasn't been drawn yet, even thoughI called mLayoutManager.scrollToPositionWithOffset(position, 0) above it.
What can I do to achieve these two things?
Scroll the list item of dataSet index position to firstVisibleItem.
Get the View or ViewHolder object of that listItem, so I can change the background or whatever.
Instead of accessing ViewHolder somewhere else, go for a custom selector background in your adapters item layout xml file instead, track the position in your adapter as selected position and call notifydatasetchanged()/notifyItemRangeChanged() to highlight it once the scroll is complete. You already have the scrollToPosition() method, have a scroll listener to track the scroll state.
Example for selector background : item_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android=
"http://schemas.android.com/apk/res/android">
<item android:state_activated="true"
android:drawable="#color/primary_dark" />
<item android:drawable="#android:color/transparent" />
</selector>
Set it as background to your item xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container_list_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/item_selector">
<--- Your layout items here --->
</RelativeLayout>
Your adapter code :
public class SampleAdapter extends RecyclerView.Adapter<SampleAdapter.ViewHolder> {
private final String[] list;
private int lastCheckedPosition = -1;
public SampleAdapter(String[] list) {
this.list = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(parent.getContext(), R.layout.sample_layout, null);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.choiceName.setText(list[position]);
holder.containerView.setSelected(position == lastCheckedPosition);
}
#Override
public int getItemCount() {
return list.length;
}
public class ViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.choice_name)
TextView choiceName;
#Bind(R.id. container_list_item)
View containerView;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lastCheckedPosition = getAdapterPosition();
notifyItemRangeChanged(0, list.length);
}
});
}
}
}
To scroll to any position :
recyclerview.scrollToPosition(position)
Let me know if this helps.
It takes some seconds to update the ViewHolder Information. Just scroll and delay the mRecyclerView.findViewHolderForLayoutPosition call for some milliseconds (100ms sounds reasonable)
Put this code in your fragment where you are going to scroll to the first RecyclerView item:
RecyclerView.ViewHolder holder = mRecyclerView
.findViewHolderForAdapterPosition(0);
while (holder == null) {
int firstVisiblePosition = mLayoutManager()
.findFirstCompletelyVisibleItemPosition();
RecyclerView.ViewHolder firstVisibleHolder = mRecyclerView
.findViewHolderForAdapterPosition(firstVisiblePosition);
View v = firstVisibleHolder.getItemView();
if (v != null) mRecyclerView.scrollBy(0, (int) v.getY());
else break;
holder = mRecyclerView.findViewHolderForAdapterPosition(0);
}
View view = null;
if (holder != null) view = holder.getItemView();
if (view != null) mRecyclerView.scrollBy(0, (int) view.getY());
Related
so I have an application that is as follows:
login page where the user enters his credentials and can access the main app if his credentials are correct. and if he checks the remember me checkbox, his username and password will be saved in shared preferences so that he can directly go to the main app in the second time.
the main app has a tabbed layout with a viewpager. in one of the tabs, which is a fragment, I use a recyclerview to display data, that I get from a database, in rows.
now in each row there is a reply button that will show details corresponding to each row when clicked. the details will be shown in a new fragment.
so the point is that I managed to replace the tab's fragment with the new fragment using this code in the recyclerview's adapter:
public class recyclerviewAdapter : RecyclerView.Adapter
{
// Event handler for item clicks:
public event EventHandler<int> ItemClick;
List <summary_request> summary_Requests=new List<summary_request>();
//Context context;
public readonly stores_fragment context;
public recyclerviewAdapter(stores_fragment context, List<summary_request> sum_req)
{
this.context = context;
summary_Requests = sum_req;
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.recycler_view_data, parent, false);
recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
return vh;
}
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
recyclerview_viewholder vh = holder as recyclerview_viewholder;
vh.by_user.Text = summary_Requests[position].By;
vh.warehousename.Text = summary_Requests[position].warehousename;
vh.project.Text = summary_Requests[position].project;
vh.operations_note.Text = summary_Requests[position].destination_Note;
vh.source_Note.Text = summary_Requests[position].source_Note;
vh.stockType.Text = summary_Requests[position].stockType;
vh.requestStatus.Text = summary_Requests[position].requestStatus;
vh.reply.Click += delegate
{
summary_detail_req fragment = new summary_detail_req();
var fm = context.FragmentManager.BeginTransaction();
fm.Replace(Resource.Id.frameLayout1, fragment);
fm.AddToBackStack(null);
fm.Commit();
int nb = context.FragmentManager.BackStackEntryCount;
Toast.MakeText(context.Context, nb.ToString(), ToastLength.Long).Show();
};
}
private void Reply_Click(object sender, EventArgs e)
{
Toast.MakeText(context.Context, "reply" , ToastLength.Long).Show();
}
public override int ItemCount
{
get { return summary_Requests.Count; }
}
// Raise an event when the item-click takes place:
void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
}
}
but my context.FragmentManager.BackStackEntryCount remain zero! I don't get it. in my main activity, I am using this code for the backpress function:
stores_fragment.recyclerviewAdapter adapter;
public override void OnBackPressed()
{
string userName = pref.GetString("Username", String.Empty);
string password = pref.GetString("Password", String.Empty);
if (userName != String.Empty || password != String.Empty && adapter.context.FragmentManager.BackStackEntryCount == 0)
{
this.FinishAffinity();
}
else
base.OnBackPressed();
}
but i'm not getting what i want. this function is getting me out of the whole app.the first part of the if statement is because without it, when the I press the back button from the main activity it takes me back to the login page and I don't want that.
my question is what should I do to manage my fragments and the backpress function?
thanks in advance.
so the point is that I managed to replace the tab's fragment with the new fragment using this code in the recyclerview's adapter
According to your description, you want to open another fragment from recyclerview Button.click, if yes, please take a look the following code:
on OnBindViewHolder
int selectedindex;
// Fill in the contents of the photo card (invoked by the layout manager):
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
selectedindex =position;
PhotoViewHolder vh = holder as PhotoViewHolder;
// Set the ImageView and TextView in this ViewHolder's CardView
// from this position in the photo album:
vh.Image.SetImageResource(mPhotoAlbum[position].PhotoID);
vh.Caption.Text = mPhotoAlbum[position].Caption;
vh.btnreply.Click += Btnreply_Click;
}
To show detailed activity. MainActivity is the current activity for recyclerview.
private void Btnreply_Click(object sender, EventArgs e)
{
Showdetailed(selectedindex);
}
private void Showdetailed(int position)
{
var intent = new Intent();
intent.SetClass(MainActivity.mac, typeof(DetailsActivity));
intent.PutExtra("selectedid", position);
MainActivity.mac.StartActivity(intent);
}
The detailedactivity.cs:
public class DetailsActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
var index = Intent.Extras.GetInt("selectedid", 0);
var details = DetailsFragment.NewInstance(index); // Details
var fragmentTransaction = FragmentManager.BeginTransaction();
fragmentTransaction.Add(Android.Resource.Id.Content, details);
fragmentTransaction.Commit();
}
}
The DetailsFragment.cs:
public class DetailsFragment : Fragment
{
public int ShownPlayId => Arguments.GetInt("selectedid", 0);
public static DetailsFragment NewInstance(int index)
{
var detailsFrag = new DetailsFragment { Arguments = new Bundle() };
detailsFrag.Arguments.PutInt("selectedid", index);
return detailsFrag;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
// return inflater.Inflate(Resource.Layout.YourFragment, container, false);
if (container == null)
{
// Currently in a layout without a container, so no reason to create our view.
return null;
}
var scroller = new ScrollView(Activity);
var text = new TextView(Activity);
var padding = Convert.ToInt32(TypedValue.ApplyDimension(ComplexUnitType.Dip, 4, Activity.Resources.DisplayMetrics));
text.SetPadding(padding, padding, padding, padding);
text.TextSize = 24;
Photo photo =PhotoAlbum.mBuiltInPhotos[ShownPlayId];
text.Text = photo.Caption;
scroller.AddView(text);
return scroller;
}
}
About implementing fragment, you can take a look:
https://learn.microsoft.com/en-us/samples/xamarin/monodroid-samples/fragmentswalkthrough/
I'm using viewpager to display pictures. I just need three fragments basically: previous image to preview, current display image and next image to preview. I would like to just display a preview of previous and next image, it will change to full image when user actually swipe to it. So I'm thinking of just using 3 fragment to achieve this. Code is below:
private class ImagePagerAdapter extends FragmentStatePagerAdapter implements ViewPager.OnPageChangeListener {
private ImageFragment mImageFragment;
private ImagePreviewFragment mPreviousPreviewFragment;
private ImagePreviewFragment mNextPreviewFragment;
public ImagePagerAdapter(FragmentManager fm, ImageFragment image, ImagePreviewFragment previous, ImagePreviewFragment next) {
super(fm);
mImageFragment = image;
mPreviousPreviewFragment = previous;
mNextPreviewFragment = next;
}
#Override
public Fragment getItem(int position) {
if (position == mPager.getCurrentItem()) {
mImageFragment.display(position);
return mImageFragment;
}
if (position < mPager.getCurrentItem()) {
mPreviousPreviewFragment.display(position - 1);
return mPreviousPreviewFragment;
}
mNextPreviewFragment.display(position + 1);
return mNextPreviewFragment;
}
#Override
public int getCount() {
return 100;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Log.d(TAG, "onPageScrolled");
}
#Override
public void onPageSelected(final int position) {
Log.d(TAG, "onPageSelected " + position);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
notifyDataSetChanged();
}
}, 500);
}
#Override
public void onPageScrollStateChanged(int state) {
Log.d(TAG, "onPageScrollStateChanged " + state);
}
#Override
public int getItemPosition(Object item) {
return POSITION_NONE;
//return POSITION_UNCHANGED;
}
}
So basically, I pre-created three fragments to display previous/next preview and current image and return them for getItem(). I also notifydatasetchange() in onpageselected() to make all three position to update the fragment when user swipe to new page.
But the problem is that it will throw out
Fragment already added IllegalStateException
when the fragments are added a second time. I think it's because it's been added before. I can create a new fragment every time but I think that's wasteful. So how can I reuse the already created fragment and just update them?
Thanks,
Simon
FragmentStatePagerAdapter design suggests creating a new Fragment for every page (see Google's example). And unfortunately you cannot readd a Fragment once it was added to a FragmentManager (what implicitly happens inside adapter), hence the exception you got. So the official Google-way is to create new fragments and let them be destroyed and recreated by the adapter.
But if you want to reuse pages and utilize an analogue of ViewHolder pattern, you should stick to views instead of fragments. Views could be removed from their parent and reused, unlike fragments. Extend PagerAdapter and implement instantiateItem() like this:
#Override
public Object instantiateItem(ViewGroup container, final int position) {
//determine the view type by position
View view = viewPager.findViewWithTag("your_view_type");
if (view == null) {
Context context = container.getContext();
view = LayoutInflater.from(context).inflate(R.layout.page, null);
view.setTag("your_view_type");
} else {
ViewGroup parent = (ViewGroup) item.getParent();
if (parent != null) {
parent.removeView(item);
}
}
processYourView(position, view);
container.addView(view, MATCH);
return view;
}
You should add some extra logic to determine the view type by position (since you have 3 types of views), I think you can figure that out.
I have 3 ListFragments being handled by a viewPager (managed by a FragmentAdapter) - they work perfectly. Now when the user clicks an item in ListFragment #1, a new Fragment should open with the details. It's behaving strangely in the following manner:
Only clicking a list item twice opens the DetailFragment, yet debugging shows the first click indeed goes into the DetailFragment, but doesn't show the view (the view still shows the current ListFragment).
After clicking the 2nd time, the DetailFragment does show it's layout, but not the elements within it (like TextView, etc).
If the user 'accidently' swipes the screen when DetailFragment is showing, the viewPager sets it in place of the 2nd ListFragment! Only when pressing back on the DetailFragment view will 'reset' the viewPager to it's correct ListFragment. Of course if the user swipes when in a DetailFragment, the next ListFragment of the viewPager should appear, and the DetailFragment should be removed.
Thanks for any tips muddling through Android's odd world of fragments and views :)
public class PlanetFragment extends ListFragment{
LayoutInflater inflater;
ListView list;
ArrayList<HashMap<String, String>> planetListArray;
HashMap<String, String> planetMap;
Activity activity;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.planets_tab_layout, container, false);
inflater=(LayoutInflater)getLayoutInflater(savedInstanceState);
activity = getActivity();
context = PlanetFragment.this.getActivity();
String dbTableName = "Table_Planets";
SQLiteHelper info = new SQLiteHelper(getActivity().getBaseContext());
info.open();
ArrayList<HashMap<String, String>> datafromSQL = info.getData(dbTableName);
if(!datafromSQL.isEmpty()){
planetListArray = new ArrayList<HashMap<String, String>>();
for (int i = 0; i<datafromSQL.size(); i++){
planetMap = new HashMap<String, String>();
planetMap.put(PLANET_ID, datafromSQL.get(i).get(KEY_PLANET_ID));
planetMap.put(ZODIAC_ID, datafromSQL.get(i).get(KEY_ZODIAC_ID));
planetMap.put(DEGREES, datafromSQL.get(i).get(KEY_DEGREES));
planetMap.put(CONTENT, datafromSQL.get(i).get(KEY_CONTENT));
planetListArray.add(planetMap);
}
info.close();
}
list = (ListView) v.findViewById(android.R.id.list);
PlanetAdapter adapter=new PlanetAdapter(getActivity(), R.layout.planets_row, planetListArray);
list.setAdapter(adapter);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//the dividers
getListView().setDivider(getResources().getDrawable(R.drawable.purplebartop));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
HashMap<String, String> item = planetListArray.get(position);
Bundle bundle = new Bundle();
bundle.putSerializable("itemMap", item);
bundle.putInt("position", position);
Fragment frag = DetailFragment.newInstance();
frag.setArguments(bundle);
if (frag != null) {
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.pager, frag, "frag")
.addToBackStack("frag")
.commit();
}
}
}
public class DetailFragment extends Fragment{
Context context;
Activity activity;
TextView planetName;
public static android.support.v4.app.Fragment newInstance() {
DetailFragment f = new DetailFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
inflater=(LayoutInflater)getLayoutInflater(savedInstanceState);
View v = inflater.inflate(R.layout.dialog_details, container, false);
activity = getActivity();
context = DetailFragment.this.getActivity();
planetName = (TextView)v.findViewById(R.id.planetNameExpanded);
planetName.setText("planetX");
return v;
}
}
EDIT:
Instead of getActivity().getSupportFragmentManager() I have also tried getChildFragmentManager() but it always gives the error: The method getChildFragmentManager() is undefined for the type PlanetFragment.
When you click on a list item, you are indeed constructing a new details fragment and telling the fragment manager to replace the tag "frag" with that fragment. However, you are not telling the view pager to switch over to that fragment.
Since you already have a back-pointer to your activity, you could use findViewById to find your view pager, and then call viewPager.setCurrentItem.
I think you might be asking for trouble by constructing a new details fragment inside of the list fragment. When you use a FragmentPagerAdapter, the adapter usually constructs the fragments. I would have implemented this by letting the adapter make the fragments, and then in your onListItemClick find the existing details fragment and call a method on it to configure it with the new data. But maybe just the setCurrentItem will fix your problem.
EDIT
First, I would write your FragmentPagerAdapter so you can use getItem to fetch the existing fragment, without creating a new one each time.
public class PlanetFragmentAdapter extends FragmentPagerAdapter {
private Fragment [] fragments = new Fragments[3];
public PlanetFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments[position];
if (fragment == null) {
switch (position) {
case 0:
fragment = new PlanetFragment();
break;
case 1:
fragment = new DetailFragment();
break;
case 2:
fragment = new MysteryFragment();
break;
}
fragments[position] = fragment;
}
return fragment;
}
}
Also add functions in your activity to work with your fragments:
public void setPage(int position) {
viewPager.setCurrentItem(position);
}
public DetailFragment getDetailFragment() {
return (DetailFragment) viewPager.getItem(1); // now it doesn't create a new instance
// you could also use getSupportFragmentManager().findFragmentById() here
}
Now when you click on an item in your list fragment, you can get the existing detail fragment, configure it, and set the ViewPager to show the detail fragment.
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
HashMap<String, String> item = planetListArray.get(position);
Bundle bundle = new Bundle();
bundle.putSerializable("itemMap", item);
bundle.putInt("position", position);
PlanetActivity pa = (PlanetActivity) activity;
DetailFragment frag = pa.getDetailFragment();
frag.setArguments(bundle);
pa.setCurrentItem(1);
}
I have the same problem as Navigating back to FragmentPagerAdapter -> fragments are empty but would like some clarification on the solution of using getChildFragmentManager().
This solution uses getChildFragmentManager(), the manager for fragments inside this Fragment(OuterFragment, which has the viewpager). InnerFragment is a page inside OuterFragment. When someone clicks the listview in InnerFragment, I want InnerFragment2 to replace InnerFragment. What do the xml and fragment managers look like?
fragment_outer.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/vpPager"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<android.support.v4.view.PagerTabStrip
android:id="#+id/pager_header"
android:layout_gravity="top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:paddingBottom="4dp"
android:paddingTop="4dp" />
<FrameLayout
android:id="#+id/inner_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.view.ViewPager>
OuterFragment.java:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_outer, container, false);
vpPager = (ViewPager) v.findViewById(R.id.vpPager);
FragmentManager cfManager = getChildFragmentManager();
adapterViewPager = new MyPagerAdapter(cfManager);
vpPager.setAdapter(adapterViewPager);
return v;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return 2;
}
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return InnerFragment.newInstance(false);
case 1:
return InnerFragment.newInstance(true);
default:
return null;
}
}
InnerFragment shows up as a fragment inside OuterFragment, which has the viewpager. InnerFragment has a listview that when clicked, should replace InnerFragment with InnerFragment2.
InnerFragment.java:
FragmentManager fm = getChildFragmentManager();
fm = fm.beginTransaction();
ft.addToBackStack(null);
ft = ft.replace(R.id.inner_content,
InnerFragment2.newInstance(someArg));
ft.commit();
This throws an error saying InnerFragment2 does not recognize view R.id.inner_content.
Not only should InnerFragment2 replace InnerFragment, but when InnerFragment2 is shown and it's button is clicked, I want InnerFragment2 replaced with InnerFragment3. I basically want to use inner_content as an inner container and keep adding fragments to a backstack for appropriate back behavior.
Do I getChildFragmentManager() or getFragmentManager() each time I add to my fragment backstack, what does the xml pattern look like, because having one framelayout in my outerfragment isn't doing it.
public void setupViewPager(ViewPager viewPager) {
FragmentManager cfManager=getChildFragmentManager();
viewPagerAdapter = new ViewPagerAdapter(cfManager);
// viewPagerAdapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
viewPagerAdapter.addFragment(new EntertainmentWallpaperFragment(), getString(R.string.title_entertainment_wallpapers));
viewPagerAdapter.addFragment(new EntertainmentMusicFragment(), getString(R.string.title_entertainment_music));
viewPagerAdapter.addFragment(new EntertainmentGamesFragment(), getString(R.string.title_entertainment_games));
viewPagerAdapter.addFragment(new EntertainmentEBooksFragment(), getString(R.string.title_entertainment_ebooks));
viewPagerAdapter.addFragment(new EntertainmentAppsFragment(), getString(R.string.title_entertainment_apps));
viewPager.setAdapter(viewPagerAdapter);
}
I hope this helps. I had the same problem where the fragments apear but once you go back they dissapear and find an empty fragent. Commnented the line that I had first implemented which after updating the fragment manager I was able to enjoy free smooth scroll.
I'm currently trying to program an Android Launcher with Fragments but I have problems with the Views on the Fragments.
I have a Dock-Fragment with a Dock-Controller which allow the user to change fragments, such as apps menu, settings fragment etc. The Dock is displayed on the buttom of the display, the Fragments(apps menu, settings fragment) should be displayed above the Dock.
The problem is, that the apps menu is not shown in its associated Fragment but rather in the Dock Fragment behind the dock icons,... So I guess, the app menu fragment gets the wrong view in its onCreateView()-Method, but I don't get why.
This is the code of the MainActivity that extends from FragmentActivity. I add the fragments to the manager.
private void addDockToManager() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(dbConnection.getLayout(DOCK_TAG), dockController.getFragment(), DOCK_TAG);
ft.commit();
}
private void addPluginsToManager() {
FragmentManager fm = null;
FragmentTransaction ft = null;
for(String key : controllerMap.keySet()) {
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
FrameController controller = null;
if ((controller = controllerMap.get(key)) != null) {
ft.add(dbConnection.getLayout(key), controller.getFragment(), key);
if (key.equals(standardFrame))
ft.addToBackStack(key);
}
ft.commit();
fm.executePendingTransactions();
}
fm = getSupportFragmentManager();
ft = fm.beginTransaction();
for(String key : controllerMap.keySet()) {
if (controllerMap.get(key) != null && !key.equals(standardFrame)) {
ft.hide(fm.findFragmentByTag(key));
}
}
ft.commit();
}
The layouts are hardcoded at the moment in dbConnection:
public int getLayout(String name) {
int layout = -1;
switch(name) {
case "app_menu" : layout = R.id.fl_app_menu;
case "settings" : layout = R.id.fl_settings;
case "dock" : layout = R.id.fl_dock;
}
return layout;
}
The MainActivity's xml looks like that:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.activity.MainActivity"
tools:ignore="MergeRootFrame" >
<FrameLayout
android:id="#+id/fl_settings"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_above="#+id/fl_dock"
android:background="#00ffffff" >
</FrameLayout>
<FrameLayout
android:id="#+id/fl_app_menu"
android:layout_width="match_parent"
android:layout_height="400dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_above="#+id/fl_dock"
android:background="#00ffffff" >
</FrameLayout>
<FrameLayout
android:id="#+id/fl_dock"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" >
</FrameLayout>
</RelativeLayout>
The xml of the apps menu is a gridview and looks like that:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gv_apps"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="6"
android:gravity="center"
android:columnWidth="50dp"
android:stretchMode="columnWidth" >
</GridView>
The App Fragment looks like that:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.external_apps, group, false);
layout = (GridView) view.findViewById(R.id.gv_apps);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
GridViewAdapter gridViewAdapter = new GridViewAdapter((AppMenuController) myController, apps);
((GridView) layout).setAdapter(gridViewAdapter);
}
And the getView Method of the GridViewAdapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(controller.getMainActivity().getApplicationContext());
imageView.setImageDrawable(buttons.get(position).getIcon());
imageView.setLayoutParams(new GridView.LayoutParams(65, 65));
return imageView;
}
I hope what I mentioned is enough to resolve the problem. I am searching the web for hours but I found no solution.
It's a much simpler problem than that I think.
public int getLayout(String name) {
int layout = -1;
switch(name) {
case "app_menu" : layout = R.id.fl_app_menu;
case "settings" : layout = R.id.fl_settings;
case "dock" : layout = R.id.fl_dock;
}
return layout;
}
Should be:
public int getLayout(String name) {
int layout = -1;
switch(name) {
case "app_menu" :
layout = R.id.fl_app_menu;
break;
case "settings" :
layout = R.id.fl_settings;
break;
case "dock" :
layout = R.id.fl_dock;
break;
}
return layout;
}
Because switch-case structure is still essentially just an organized goto, and not actually an if-else structure, aka if you don't break out, then all cases will run sequentially.
I found the problem. And it was in a part of the code I never expected it to be.
The Dummy-Switch-Case in dbConnection caused it. Seemingly Strings aren't compared by value but rather by reference in such a Switch-Case. So it always chose the dock container layout to be associated with the app menu in the fragment manager,...