How to run multiple activities and also close those activities - android

I have an activity in which the user enters the no of items to be created.
I have created an activity to enter the details of the item.
After pressing a button then the activity for entering details starts
For more than one item the activity should run one after the other and if the user presses back button a popup arises to confirm cancel the process.
I wrote in Kotlin language
I tried by using for loop but all the activities run in the background, I should press back button for all the activity

You can use a ViewPager in your activity and a adapt a list of fragments for each item using FragmentPagerAdapter.
The backstack will contain only the fragment holding the ViewPager so presing back will close the activity alltogheter.
Main Activity:
public class MyActivity extends AppCompatActivity {
private ViewPager myViewPager;
private MyFragmentAdapter adapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
adapter = new MyFragmentAdapter(getSupportFragmentManager());
adapter.setFragments("5");
myViewPager = findViewById(R.id.myViewPager);
myViewPager.setAdapter(adapter);
}
}
Fragment Adapter :
class MyFragmentAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments = new ArrayList<>();
public MyFragmentAdapter(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
public void setFragments(String noOfFragments){
int intFragments = Integer.parseInt(noOfFragments);
for (int i = 0; i < intFragments; i++){
this.fragments.add(new Fragment());
}
}
}
Activity layout:
<?xml version="1.0" encoding="utf-8"?>
<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"enter code here>
<ViewPager
android:id="#+id/myViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</ConstraintLayout>
I have removed the views qualifiers, you should fill in with either support library or androidx

Related

BottomNavigation initial setCurrentItem not showing fragment and relaunching fragment fails

I have a Main Activity which uses a TabSelectedListener to show fragments for the AHBottomNavigation menu. The fragment called "FirstFragment" contains a FragmentPagerAdapter which allows the user to swipe between two tabs, each of which have its own fragment, called FirstTabInFirstFragmentFragment and SecondTabInFirstFragmentFragment (renamed for simplicity).
My issue is that:
a). When the Main Activity is launched, the "First" Bottom Navigation menu item is selected, however the "FirstFragment" is not launched. So, it shows the proper item selected with a blank screen. It only launches the First Fragment if I tap on the menu item again.
b). Once the FirstFragment has been properly launched and is being shown on screen (by the temporary fix done in a), if I select a different menu item (i.e. to navigate to SecondFragment) and then select the FirstFragment's menu item again, the two tabs within it are blank. Also, the sliding between the fragments for the two tabs does not work and gets "stuck" so you have to pull it all the way to one side or all the way to the other.
Hopefully I have explained my problem clearly - if there is anything I'm missing, I can provide more details.
Note that I am using com.aurelhubert.ahbottomnavigation.AHBottomNavigation
Here are the relevant files:
MainActivity.java:
public class MainActivity extends AppCompatActivity{
private AHBottomNavigationAdapter navigationAdapter;
private AHBottomNavigationViewPager viewPager;
private AHBottomNavigation bottomNavigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Add menu items to bar
bottomNavigation = (AHBottomNavigation) findViewById(R.id.bottom_navigation);
this.createNavItems();
bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
#Override
public boolean onTabSelected(int position, boolean wasSelected) {
//show fragment
if (position==0)
{
FirstFragment firstFragment=new FirstFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content_id,firstFragment).commit();
}else if (position==1)
{
SecondFragment secondFragment=new SecondFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content_id, secondFragment).commit();
}else if (position==2)
{
ThirdFragment thirdFragment=new ThirdFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content_id,thirdFragment).commit();
}else{
FourthFragment fourthFragment=new FourthFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content_id,fourthFragment).commit();
}
return true;
}
});
}
private void createNavItems(){
navigationAdapter = new AHBottomNavigationAdapter(this, R.menu.navigation);
navigationAdapter.setupWithBottomNavigation(bottomNavigation);
// set current item
bottomNavigation.setCurrentItem(0);
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_id"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.aurelhubert.ahbottomnavigation.AHBottomNavigation
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
</android.support.design.widget.CoordinatorLayout>
FirstFragment.java:
public class FirstFragment extends Fragment {
private FragmentActivity mContext;
public FirstFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file
//setContentView(R.layout.activity_first);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) getView().findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
// using getFragmentManager() will work too
FirstFragmentPagerAdapter adapter = new FirstFragmentPagerAdapter(mContext.getSupportFragmentManager(), mContext);
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) getView().findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
}
/**
* Override to set context. This context is used for getSupportFragmentManager in onCreateView
* #param activity
*/
#Override
public void onAttach(Activity activity) {
mContext=(FragmentActivity) activity;
super.onAttach(activity);
}
}
fragment_first.xml:
<?xml version="1.0" encoding="utf-8"?>
<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"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabBackground="#color/firstTabBackground"
app:tabIndicatorColor="#color/firstTabIndicatorColor"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
FirstFragmentPagerAdapter.java:
public class FirstFragmentPagerAdapter extends FragmentPagerAdapter {
private Context context;
public FirstFragmentPagerAdapter(FragmentManager fm, Context mContext){
super(fm);
context = mContext;
}
/**
* The ViewPager asks the adapter for the fragment at a given position,
* i.e. for the 1st fragment, the ViewPager asks for the fragment at
* position 1.
* #param position
* #return
*/
#Override
public Fragment getItem(int position){
if (position == 0){
return new FirstTabInFirstFragmentFragment();
}
else{
return new SecondTabInFirstFragmentFragment();
}
}
/**
* On launch, the ViewPager asks the adapter how many pages there will be.
* Here, our adapter returns how many pages there will be.
* #return
*/
#Override
public int getCount() {return 2;}
#Override
public CharSequence getPageTitle(int position) {
switch(position){
case 0:
return context.getResources().getString(R.string.first_tab_in_first_fragment_page_title);
case 1:
return context.getResources().getString(R.string.second_tab_in_first_fragment_page_title);
default:
return null;
}
}
}
I was able to solve this in two steps. First, in my Main Activiy method createNavItems, in addition to doing a bottomNavigation.setCurrentItem(0);, I also had to manually update the CoordinatorLayout (which has ID content_id) with the default fragment:
getSupportFragmentManager().beginTransaction().replace(R.id.content_id, new FirstFragment()).commit();
Next, to solve the TabLayout issues I had to change this line:
FirstFragmentPagerAdapter adapter = new FirstFragmentPagerAdapter(mContext.getSupportFragmentManager(), mContext);
to
FirstFragmentPagerAdapter adapter = new FirstFragmentPagerAdapter(getChildFragmentManager(), mContext);
The reason for this is that when nesting Fragments inside of other Fragments with ViewPager, getFragmentManager() is for managing Fragments within a Fragment whereas mContext.getSupportFragmentManager() is used for Activities.
Firstly, Inorder to initially load the frstfragment on startup, u have to define the frstfragments view as default view to mainactivitys view.
Secondly, you need to have a framelayout to load the views for each fragment when selecting bottomnavigation menu.. here you are simply replacing the parent layout of mainactivity, which is a wrong concept, i believe.
So you need to create a child framelayout to load fragment views for each bottomnavigation menu items.
edits:
my layout which contains bottomnavigation,
<?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:id="#+id/content_home"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_home"
android:keepScreenOn="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/ll_toolbar_home_search">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="30dp"
android:background="#drawable/btn_style_white"
android:layout_marginRight="10dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_search"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Search 18000+ products"
android:id="#+id/tv_search_home"/>
</LinearLayout>
</android.support.v7.widget.Toolbar>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/ll_toolbar_home_search"
android:layout_above="#+id/navigation"
android:id="#+id/frame_layout_fragment"
android:background="#color/white">
</FrameLayout>
<com.aurelhubert.ahbottomnavigation.AHBottomNavigation
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
and java class for that activity( only method that contains bottomnavigation manipulations) is follows:
private void BottomView1() {
navigation = (AHBottomNavigation) findViewById(R.id.navigation);
AHBottomNavigationItem item1 = new AHBottomNavigationItem("Home", R.drawable.ic_home, R.color.ash);
AHBottomNavigationItem item2 = new AHBottomNavigationItem("Category", R.drawable.ic_category, R.color.ash);
AHBottomNavigationItem item3 = new AHBottomNavigationItem("Search", R.drawable.ic_search, R.color.ash);
AHBottomNavigationItem item4 = new AHBottomNavigationItem("Offers", R.drawable.ic_offers, R.color.ash);
AHBottomNavigationItem item5 = new AHBottomNavigationItem("Cart", R.drawable.ic_cart, R.color.ash);
navigation.addItem(item1);
navigation.addItem(item2);
navigation.addItem(item3);
navigation.addItem(item4);
navigation.addItem(item5);
navigation.setCurrentItem(getResources().getColor(R.color.colorPrimaryDark));
navigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW);
setCartNotification();
navigation.setAccentColor(getResources().getColor(R.color.colorPrimaryDark));
navigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
#Override
public boolean onTabSelected(int position, boolean wasSelected) {
Intent ii ;
Fragment selectedFragment = null;
if(position==0){
selectedFragment = HomeFragment.newInstance();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout_fragment, selectedFragment);
transaction.commit();
} else if(position==1){
ii = new Intent(HomeActivity.this, ShopByCategoryActivity.class);
startActivity(ii);
} else if(position==2){
ii = new Intent(HomeActivity.this, SearchActivity.class);
startActivity(ii);
} else if(position==3){
ii = new Intent(HomeActivity.this, OffersActivity.class);
startActivity(ii);
} else if(position==4){
ii = new Intent(HomeActivity.this, MyCartActivity.class);
startActivity(ii);
}
return true;
}
});
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout_fragment, HomeFragment.newInstance());
transaction.commit();
}

why fragment doesn`t show up with ViewPagerIndicator

I have a activity whose content view is a fragment, I added viewpager and viewpagerindicator to this activity. I created an FragmentPagerAdapter for the pager, the adapter constructs three fragments for displaying three tabs. But when I run the project, only see the pager title shows up. Why doesn`t the three fragments show up?
I created the pager and indicator on create of the Activity lifecycle.
public class BrowserActivity extends SherlockFragmentActivity
implements ReposFragment.OnFileSelectedListener, StarredFragment.OnStarredFileSelectedListener, OnBackStackChangedListener {
super.onCreate(savedInstanceState);
setContentView(R.layout.seadroid_main);
adapter = new SeafileTabsAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
indicator.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(final int position) {
currentPosition = position;
supportInvalidateOptionsMenu();
disableUpButton();
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
});
the adapter constructs three fragments for displaying three tabs view
class SeafileTabsAdapter extends FragmentPagerAdapter implements
IconPagerAdapter {
public SeafileTabsAdapter(FragmentManager fm) {
super(fm);
}
private ReposFragment reposFragment = null;
private ActivitiesFragment activitieFragment = null;
private StarredFragment starredFragment = null;
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
if (reposFragment == null) {
reposFragment = new ReposFragment();
}
return reposFragment;
case 1:
if (starredFragment == null) {
starredFragment = new StarredFragment();
}
return starredFragment;
case 2:
if (activitieFragment == null) {
activitieFragment = new ActivitiesFragment();
}
return activitieFragment;
default:
return new Fragment();
}
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.tabs_library).toUpperCase();
case 1:
return getString(R.string.tabs_starred).toUpperCase();
case 2:
return getString(R.string.tabs_activity).toUpperCase();
default:
return null;
}
}
#Override
public int getIconResId(int index) {
return ICONS[index];
}
#Override
public int getCount() {
return ICONS.length;
}
}
the layout file seadroid_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.viewpagerindicator.TabPageIndicator
android:id="#+id/indicator"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
UPDATE
I have found that ViewPager tutorials used LineaLayout as the root container. So is it necessary to change FragmentLayout to be LineaLayout here. When I changed to LineaLayout, the app crashed, and the log is
12-02 07:01:13.636: E/AndroidRuntime(3807): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.seafile.seadroid2/com.seafile.seadroid2.ui.activity.BrowserActivity}: android.view.InflateException: Binary XML file line #21: Error inflating class LineaLayout
12-02 07:01:13.636: E/AndroidRuntime(3807):at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
Try switching the root view in your XML to LinearLayout. Right now you are using FrameLayout, which has the effect of putting your ViewPager on top of your TabPageIndicator. Also, since the layout_height is 0, you're not going to see your fragments. I suspect this is your problem -- clearly you meant to use LinearLayout.
Also, be careful with your SeafileTabsAdapter class. Right now it is caching the fragments, which seemed logical to me when I started using FragmentPagerAdapter too. However, FragmentPagerAdapter caches the fragments too, so you have a danger of a memory leak with this approach. If you want to call getItem directly, without auto-creating a fragment each time, then you can first call findFragmentByTag to see if the fragment is there yet. The string Android uses for the tag can be found in the source, or in this SO question:
Replace Fragment inside a ViewPager
Hope this helps. I'm still a bit confused about your code, because in the description you say you have a ViewPager inside a fragment, but the posted code seems to show a ViewPager inside your activity.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.viewpagerindicator.TabPageIndicator
android:id="#+id/indicator"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>
I hope this answers your concern in your comment. If you instead mean that the sherlock code is expecting a FrameLayout as the root view (this would surprise me, although I haven't used it), then all you need to do is put the LinearLayout above as a child of the FrameLayout you had before. Does that make sense?

Android Activity Layout with Multiple Fragments

I'm new to Android, there's so much unknown that I don't even know which direction to look for solutions.. I hope experienced developers can enlighten me on this..
I have a UI design that is quite different from common Android app layout, most of which I've seen so far use Tabs or the upper-left corner control button..
My Main Activity is 1) full-screen without ActionBar 2) has a fixed "control panel" layer occupying the bottom half of the screen 3) a full-screen ViewPager (contains three pages, can swipe left and right) below the "control panel" layer.
I'm able to achieve either 1&2 or 1&3 but not all together. I think the main problem is to add the control panel on top of the ViewPager within the same screen.
I tried to put ViewPager and "control panel" as two fragments inside the MainActivity layout.. it didn't work... below is the layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.MainActivity">
<fragment
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:layout="#layout/fragment_pager"/>
<fragment android:name="com.example.MainFragment"
android:layout_width="fill_parent"
android:layout_height="200dip"
android:layout_gravity="bottom"
tools:layout="#layout/fragment_main"/>
</LinearLayout>
In case you need more info, attach my MainActivity as well
public class MainActivity extends FragmentActivity {
static final int NUM_ITEMS = 3;
private FragmentPagerAdapter mAdapter;
private ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.hide();
setContentView(R.layout.activity_main);
mAdapter = new DashboardAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(1);
}
public static class DashboardAdapter extends FragmentPagerAdapter {
public DashboardAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FirstFragment();
case 1:
return new SecondFragment();
case 2:
return new ThirdFragment();
default:
return null;
}
}
}
}
I got Error inflating class fragment, so probably happens when I create the fragment
inflater.inflate(R.layout.first_fragment, container, false);
Because "control panel" is outside the ViewPager, thus the view cannot be inflated... Then what's the correct way of doing it?
Use a RelativeLayout as the root of your MainActivity.
The ViewPager should be the first child with match_parent.
Your control panel can be aligned at the bottom using layout_alignParentBottom="true". This will also make it on top of the ViewPager.

fragments: onCreateView is not called after fragment was added

I have simple app with fragments.
At the beginning list of fragments is empty.
And there are 2 buttons:
ADD FRAGMENT
REMOVE FRAGMENT
And following use-case:
Add fragment
Add fragment
Remove first fragment
Add fragment
As result onCreateView() on 4th step is not executed.
If I add fragment again on 5th step - onCreateView is executed again.
Why is it so? I didn't find right answer in google.
Source code:
public class MyActivity extends FragmentActivity {
private ViewPager pager;
private FragmentAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pager = (ViewPager) findViewById(R.id.pager);
final Button addButton = (Button) findViewById(R.id.add_button);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.addFragment(new MyFragment());
adapter.notifyDataSetChanged();
}
});
final Button removeButton = (Button) findViewById(R.id.remove_button);
removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adapter.removeFragment(0);
adapter.notifyDataSetChanged();
}
});
adapter = new FragmentAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
pager.setOffscreenPageLimit(10);
}
private class FragmentAdapter extends FragmentStatePagerAdapter {
final List<MyFragment> fragments = new ArrayList<MyFragment>();
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return fragments.get(i);
}
#Override
public int getCount() {
return fragments.size();
}
public void addFragment(MyFragment fragment) {
fragments.add(fragment);
}
public void removeFragment(int index) {
fragments.remove(index);
}
}
private class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment, container, false);
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/add_button"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remove first"
android:id="#+id/remove_button"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
OnCreateView() is only called when the actual Fragment is being drawn on the screen. Since you have removed a fragment at the beginning the pager no longer looks at the same fragment.
To better understand what is going on put a visible number on each of the fragments and then try adding and removing the fragments.
The issue is 'FragmentStatePagerAdapter' and the way it's implemented. The way to fix it is this:
Go to googlesource and grab the source for 'FragmentStatePagerAdapter'.
refactor (name, package,etc) to make it your own implementation.
Extend from your NEW version of 'FragmentStatePagerAdapter'
Modify your NEW version of 'FragmentStatePagerAdapter' using these steps below:
a) Change the mFragments.set(index, object) command to mFragments.add(index, object), in the the 'instantiateItem()' function.
b) Change the mFragments.set(index, object) command to mFragments.remove(index), in the 'destroyItem' function.
All of this assumes that you are using an ArrayList to hold fragments in your 'extends' class and that they are synced to match the ViewPager.
You will need to add a 'pageIndex' to each fragment, so that you can tell ViewPager when your item has 'moved' (due to deleting an item, that is NOT the LAST item).
This took several days to run down...hope it helps someone :-)

Update A ListView In One Fragment From A Second Fragment

I have a ViewPager that shows the user 2 fragments.
Fragment 1 contains a button with an onClickListener that adds an entry to the ListView contents in fragment 2. The new entry is a number generated by a random number generator.
Fragment 2 contains a ListView with some random numbers in.
I cannot find a way to refresh the list in fragment 2 from the button listener in fragment 1. How do i do this?
I have tried:
initializing and setting the list adapter in an onResume in
fragment 2.
Calling myViewPager.notifyDataSetChanged from fragment 1.
Neither of the above methods have worked. Any ideas?
Edit: Here is my code:
layout_main.xml
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
layout_frag_one.xml
<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" >
<Button
android:id="#+id/main_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Add Number" />
</RelativeLayout>
layout_frag_two
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
MainActivity
public class SlideActivity extends FragmentActivity {
private final static int FRAGMENT_NUMBER = 2;
private ViewPager pager;
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_mainpager);
pager = (ViewPager) findViewById(R.id.mainpager);
pager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
super.onCreate(savedInstanceState);
}
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int index) {
switch(index){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
default:
return new Fragment1();
}
}
public int getCount() {
return FRAGMENT_NUMBER;
}
}
}
You may need to implement some of this to get it working right:
http://developer.android.com/training/basics/fragments/communicating.html
And some more reading here:
http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

Categories

Resources