Fragment is not starting from menu item when pressed - android

I'm trying to start a fragment from the toolbar (the toolbar is in a fragment too) but it's not starting, that was not the case when it was in the main activity it was working fine.
If You Want More Reference of any file or want to see other files
please tell me I will upload it
Java Files
Home_Fragment.java
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
MaterialToolbar materialToolbar = view.findViewById(R.id.tool_bar);
materialToolbar.setOnMenuItemClickListener(toolbarItemClickListener);
return view;
}
private final MaterialToolbar.OnMenuItemClickListener toolbarItemClickListener =
(MenuItem item) -> {
Fragment selectedFragment = null;
if (item.getItemId() == R.id.search_button) {
selectedFragment = new Search_Fragment();
}
return true;
};
XML Files
tool_bar.xml(menu XML)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/search_button"
android:icon="#drawable/ic_baseline_search_24"
android:title=""
app:showAsAction="always"
android:iconTint="#color/white"/>
</menu>
tool_bar.xml
<com.google.android.material.appbar.MaterialToolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#color/black"
app:itemIconSize="29dp"
app:layout_scrollFlags="scroll|enterAlways"
app:menu="#menu/tool_bar">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/app"
android:textColor="#color/white"
android:textSize="23sp"
android:textStyle="bold" />
</com.google.android.material.appbar.MaterialToolbar>

You've just created a new instance of your Fragment, but didn't add it to the FragmentManager, so it didn't start. You have to make a FragmentTransaction to start the fragment.
Fragment selectedFragment = null;
if (item.getItemId() == R.id.search_button) {
selectedFragment = new Search_Fragment();
getParentFragmentManager.beginTransaction()
.replace(R.id.fragment_container, Search_Fragment.class, null) // fragment_container is the ID of the fragment holder
.setReorderingAllowed(true)
.commit();
}

Related

Android Studio Bottom Bar Nav: How do I add to each fragment?

I followed a tutorial online to create a Bottom Bar Navigation, but the guy didn't explain clearly how to add stuff to each fragment and swap between the fragments. I want to add an EditText to the home page as an example on how to add items to the fragments. Here's my code:
Main Activity -
public class MainActivity extends AppCompatActivity {
private static final String TAG_FRAGMENT_CATA = "tag_frag_cata";
private static final String TAG_FRAGMENT_HOME = "tag_frag_home";
private static final String TAG_FRAGMENT_SETTINGS = "tag_frag_settings";
private BottomNavigationView bottomNavigationView;
private List<BottomBarFragment> fragments = new ArrayList<>(3);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_nav);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.bottombaritem_cata:
switchFragment(0, TAG_FRAGMENT_CATA);
return true;
case R.id.bottombaritem_home:
switchFragment(1, TAG_FRAGMENT_HOME);
return true;
case R.id.bottombaritem_settings:
switchFragment(2, TAG_FRAGMENT_SETTINGS);
return true;
}
return false;
}
});
buildFragmentsList();
switchFragment(1, TAG_FRAGMENT_HOME);
}
private void buildFragmentsList() {
BottomBarFragment cataFragment = buildFragment("Categories");
BottomBarFragment homeFragment = buildFragment("Home");
BottomBarFragment settingsFragment = buildFragment("Settings");
fragments.add(cataFragment);
fragments.add(homeFragment);
fragments.add(settingsFragment);
}
private BottomBarFragment buildFragment(String title) {
BottomBarFragment fragment = new BottomBarFragment();
Bundle bundle = new Bundle();
bundle.putString(BottomBarFragment.ARG_TITLE, title);
fragment.setArguments(bundle);
return fragment;
}
private void switchFragment(int pos, String tag) {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_fragmentholder, fragments.get(pos), tag).commit();
}
}
Bottom Bar Activity -
public class BottomBarFragment extends Fragment {
public static final String ARG_TITLE = "arg_title";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.bottom_bar_fragment, container, false);
return rootView;
}
}
XML for the Main Activity
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:itemBackground="#android:color/white"
app:itemIconTint="#android:color/black"
app:itemTextColor="#android:color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottombar_menu" />
<FrameLayout
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="#+id/bottom_nav"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<FrameLayout
android:id="#+id/frame_fragmentholder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</android.support.constraint.ConstraintLayout>
XML Layout file -
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BottomBarFragment">
</android.support.constraint.ConstraintLayout>
If someone could explain how to use this code, I would really appreciate it!
You have three fragements in your bottomNavigationBar. I guess these would be cata, home and settings. For each one you need to create new class.
E.g. for cata:
public class CataFragment extends Fragment {
public CataFragment() {
// Required constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//here you would do the fragment specific coding
return inflater.inflate(R.layout.fragment_cata, container, false);
}
}
As you can already see, they are in touch with a layout file, here the fragment_cata file for what you have to create an xml layout file with its name. The layout file can be an autocreated blank fragment layout that you can find in the list when you create new files. That would look like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChatFragment">
<!-- TODO: Update blank fragment layout -->
</RelativeLayout>
This layout file you can handle like any other layout file

Uneven Bottom Navigation Bar

I'm trying to create a bottom navigation bar with 5 items regularly spaced and without labels underneath the icons. I found lots of guidance and followed it but unlike the examples I followed, my navigation bar display is very uneven. How can I make it evenly distributed?
This is what it looks like now:
My xml view (within Relative Layout):
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemBackground="#color/colorPrimary"
app:itemIconTint="#android:color/white"
app:itemTextColor="#android:color/white"
app:menu="#menu/navigation" />
Navigation xml file:
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/navigation_home"
android:enabled="true"
android:icon="#drawable/ic_home_black_24dp"
android:title="Home"
app:showAsAction="always" />
<item
android:id="#+id/navigation_look"
android:icon="#drawable/ic_find_in_page_black_24dp"
android:title="Search"
android:enabled="true"
app:showAsAction="always"/>
<item
android:id="#+id/navigation_basket"
android:enabled="true"
android:icon="#drawable/ic_shopping_basket_black_24dp"
android:title="Basket"
app:showAsAction="always"/>
<item
android:id="#+id/navigation_favourite"
android:icon="#drawable/ic_favorite_black_24dp"
android:title="Favourite"
android:enabled="true"
app:showAsAction="always"/>
<item
android:id="#+id/navigation_account"
android:enabled="true"
android:icon="#drawable/ic_person_black_24dp"
android:title="Account"
app:showAsAction="always"/>
</menu>
And this is what is in my CategoryActivity.java within onCreate:
BottomNavigationView navigationSearch = (BottomNavigationView)
findViewById(R.id.navigation_search);
navigationSearch.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
Intent main = new Intent(CategoryActivity.this, MainActivity.class);
startActivity(main);
break;
case R.id.navigation_look:
Intent search = new Intent(CategoryActivity.this, SearchActivity.class);
startActivity(search);
break;
case R.id.navigation_basket:
Intent basket = new Intent(CategoryActivity.this, BasketActivity.class);
startActivity(basket);
break;
case R.id.navigation_favourite:
Intent favourite = new Intent(CategoryActivity.this, FavouritesActivity.class);
startActivity(favourite);
break;
case R.id.navigation_account:
Intent account = new Intent(CategoryActivity.this, AccountActivity.class);
startActivity(account);
break;
}
return false;
}
});
i had the same problem but with 4 items, there is a sort of trick, you should use this method on your BottomNavigationView after the findViewById.
#SuppressLint("RestrictedApi")
public static void disableShiftMode(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
//noinspection RestrictedApi
item.setShiftingMode(false);
// set once again checked value, so view will be updated
//noinspection RestrictedApi
item.setChecked(item.getItemData().isChecked());
}
} catch (NoSuchFieldException e) {
Log.e("BNVHelper", "Unable to get shift mode field", e);
} catch (IllegalAccessException e) {
Log.e("BNVHelper", "Unable to change value of shift mode", e);
}
}
Sorry, i can't really explain the solution more in-depth since it was an issue i solved a long time ago following some advice on StackOverflow and i don't remember the theory/reasons there was a need for this, but this works fine for me on Android Oreo so you could do some experiments and find a better way.
I recommend you to use the fragments
navigationSearch.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId())
{
case R.id.navigation_home:
selectedFragment = HomeFragment.newInstance();
break;
case R.id.navigation_look:
selectedFragment = LookFragment.newInstance();
break;
case R.id.navigation_basket:
selectedFragment = BasketFragment.newInstance();
break;
case R.id.navigation_favourite:
selectedFragment = FavouriteFragment.newInstance();
break;
case R.id.navigation_account:
selectedFragment = AccountFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout,selectedFragment);
transaction.commit();
return true;
}
});
setDefaulFragment();
private void setDefaulFragment() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout,HomeFragment.newInstance());
transaction.commit();
}
activity_category.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient"
tools:context=".CategoryActivity">
<FrameLayout
android:id="#+id/frame_layout"
android:animateLayoutChanges="true"
android:layout_above="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimaryDark"
app:itemIconTint="#drawable/nav_item_color_state"
app:itemTextColor="#drawable/nav_item_color_state"
app:menu="#menu/bottom_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
Example fragment:
HomeFragment.java:
public class HomeFragment extends Fragment {
View mFragment;
public static HomeFragment newInstance(){
HomeFragment homeFragment = new HomeFragment();
return homeFragment ;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mFragment = inflater.inflate(R.layout.fragment_home,container,false);
return mFragment;
}
}
Example fragment :
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeFragment">
<TextView
android:text="Home Fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
What you can do is give the Title attribute as android:title="" in Navigation.xml and then to disable the shift mode use BottomNavigationViewHelper.disableShiftMode(your BottomNavigationView)
Use a linear layout with horizontal orientation.
You can give layout_weight for each item about 20. WeightSum of 100 for the Linear layout.
Load the data using fragments.

FragmentManager replace not working?

I am having a hard time figuring out why my FragmentManager isn't working.
I'm using an Android studio template for nav drawer activity. The most confusing thing is, I have the exact same code in another app and it works just fine.
Here is the code:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
switch (id) {
case R.id.nav_camera:
fragment = new MyFragment();
Log.i("ID", String.valueOf(id));
break;
case R.id.nav_gallery:
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_main, fragment)
.commit();
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Now, when I click on the nav_camera it logs the click just fine, but nothing else happens, the fragment doesn't get replaced. No errors, no exceptions, just the same screen over and over.
Fragment code, nothing here just testing:
public class MyFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
Fragment layout, just a blank:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
The rest of the code is auto generated by andorid studio.
Here is content_main, which I am trying to replace with fm:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content_main"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.goran.mymoviedb.movies.MainActivity"
tools:showIn="#layout/app_bar_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
It should replace the layout with a blank one whan nav_camera is clicked but nothing happens, even though correct click is registered.
Actually your code is working but the issue is that you have blank layout and because background of fragment layout is by default transparent you can not see the change. Put background color on your root layout of fragment (LinearLayout) for example: android:background="#android:color/white"
and you will see fragement replacement.

android - How to set menu items in the middle in a Bottom Navigation View?

I have a Bottom Navigation View with 4 items.
I wish to set the items in the middle of each bottom navigation view button and I have found a method but it works only when the application starts.
After I select another item, every icon moves up and I don't know why they are not keeping their position.
public class MainActivity extends AppCompatActivity{
private Toolbar mToolbar;
private BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.customToolbar);
setSupportActionBar(mToolbar);
setTitle("");
mToolbar.setNavigationIcon(R.mipmap.back_icon);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
BottomNavigationViewShiftDisable.disableShiftMode(bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.profile:
fragment = new FirstFragment();
break;
case R.id.friends:
fragment = new SecondFragment();
break;
case R.id.circle:
fragment = new ThirdFragment();
break;
case R.id.settings:
fragment = new ForthFragment();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, fragment);
transaction.commit();
setMenuIconsInMiddle(bottomNavigationView);
return true;
}
});
bottomNavigationView.setSelectedItemId(R.id.profile);
}
/**
* This method is used to set margins for all the icons in the menu that is used in the
* bottom navigation view.
* #param navigationView an instance of the Bottom navigation view that holds the menu with
* the icons.
*/
public void setMenuIconsInMiddle(BottomNavigationView navigationView){
BottomNavigationMenuView menuView = (BottomNavigationMenuView)navigationView.getChildAt(0);
for(int index = 0; index <menuView.getChildCount(); index++){
final View iconView = menuView.getChildAt(index).findViewById(android.support.design.R.id.icon);
final ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams)iconView.getLayoutParams();
layoutParams.setMargins(0,50,0,0);
navigationView.requestLayout();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hermes.profilescreen.MainActivity">
<include layout="#layout/custom_toolbar"/>
<include layout="#layout/bottom_navigation"/>
</RelativeLayout>
bottom_nav_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item
android:id="#+id/profile"
android:enabled="true"
android:icon="#drawable/ic_people_outline_black_24dp"
app:showAsAction="ifRoom"
android:title=""
/>
<item
android:id="#+id/friends"
android:enabled="true"
android:icon="#drawable/ic_person_black_24dp"
app:showAsAction="ifRoom"
android:title=""
/>
<item
android:id="#+id/circle"
android:enabled="true"
android:icon="#drawable/ic_panorama_fish_eye_black_24dp"
app:showAsAction="ifRoom"
android:title=""
/>
<item
android:id="#+id/settings"
android:enabled="true"
android:icon="#drawable/setting_white"
app:showAsAction="ifRoom"
android:title=""
/>
</menu>
bottom_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frame_layout"
android:layout_above="#+id/bottom_navigation"
>
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/light_black"
app:itemBackground="#drawable/set_backgorund"
app:itemIconTint="#color/item_state"
app:menu="#menu/bottom_nav_main"
/>
</RelativeLayout>
call setMenuIconsInMiddle on a thread. try this:-
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
//your code here
...
...
...
//Looper.getMainLooper() runs on main thread
new Handler(Looper.getMainLooper()).post(new Runnable(){
#Override
public void run() {
setMenuIconsInMiddle(bottomNavigationView);
}
});
return true;
}
});
this is working for me...

Fragments inside a fragment Android application

I'm trying to put 2 fragments inside a fragment. I found some code on internet but, as far as I could go, I don't succeed to put 2 fragments in 1 fragment.
I have seen tips dealing with FragmentManager and especially the method getChildFragmentManager() but I don't know how it works with 2 fragments.
For the story, I'm using an activity with ActionBar which creates 3 fragments. In one of them, I need to handle a graph and a kind of menu to change the graph scale. In this way, I need 2 fragments in one fragment.
Here is the code :
The fragment which handles the others:
public class GraphDisplayFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.graph_fragment, container, false);
return myFragmentView;
}
}
The code to draw the graph:
public class GraphFragment extends Fragment {
private static final int SERIES_NR = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
GraphicalView myFragmentView = ChartFactory.getTimeChartView(this.getActivity(), getDateDemoDataset(), getDemoRenderer(),null);
return myFragmentView;
}
//some functions to set graph propreties
}
The XML files :
graph_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/graph_fragment"
android:name="com.test.GraphFragment"
android:layout_width="match_parent"
android:layout_height="259dp" >
</fragment>
<fragment
android:name="com.test.GraphDetailFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/graph_detail_fragment">
</fragment>
</LinearLayout>
graph_detail.xml with a test implementation
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="211dp"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
The weird thing is, it works at the begining when I switch between fragments in the ActionBar but after 3-4 moves, I get this error :
android.view.InflateException: Binary XML file line #7: Error inflating class fragment
If anyone has the solution, it would be awesome!
So first off change your xml for graph_fragment.xml to this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/graph_fragment_holder"
android:layout_width="match_parent"
android:layout_height="259dp" >
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/graph_detail_fragment_holder">
</FrameLayout>
</LinearLayout>
Then in code to inflate them from the fragment use something like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.graph_fragment,
container, false);
FirstChildFragment frag1 = (FirstChildFragment) getChildFragmentManager()
.findFragmentById(R.id.first_frag_layout);
SecondChildFragment frag1 = (SecondChildFragment) getChildFragmentManager()
.findFragmentById(R.id.second_frag_layout);
if (null == frag1) {
FirstChildFragment = new frag1();
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.add(R.id.graph_fragment_holder, frag1)
.addToBackStack(null).commit();
}
if (null == frag2) {
SecondChildFragment = new frag2();
FragmentTransaction transaction = getChildFragmentManager()
.beginTransaction();
transaction.add(R.id.graph_detail_fragment_holder, frag2)
.addToBackStack(null).commit();
}
return rootView;
}
MyFragment myFragment = (MyFragment)getChildFragmentManager().findFragmentById(R.id.my_fragment);
You can try to use the method *findFragmentById(fragment_id)* from SupportFragmentManager to get the instance of fragment from your .xml file and insert your fragment there.
Something like:
Fragment myFragment = getSupportFragmentManager().findFragmentById(R.id.myFragmentId);
I hope to help you.
Best regards.
Adriano

Categories

Resources