Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a fragment to a ViewPager? addView crashes my app

I'm using the default Swipe Tab Fragment code that Android starts with when you start a new Android application. I've figured out how to modify my data and use the tabs, but I haven't figured out how to add a simple fragment to what's already there. I wanted to add a infobar on the top of the tabs or right below them. I'm sure it's simple, I just can't figure out how lol. I learn by examples.

I've tried adding a view to viewpager, but my app is crashing, and I believe I'm totally doing it wrong.

In my MainActivity: ...

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    SubBarFragment infobar = new SubBarFragment();
    mViewPager.addView(infobar.getView());      
.....[extra code for menus and things]

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
....[code to show specific tabs and return the tab's fragment]

infobarfragment.java

public class InfobarFragment extends Fragment {

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.infobar, container, false);
        return view;
      }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" />

infobar.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="horizontal" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_wifi" />

    <TextView
        android:id="@+id/statusText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Wifi Status Information" />

</LinearLayout>
like image 522
CREW Avatar asked Apr 26 '13 08:04

CREW


People also ask

How do you get ViewPager fragments?

ViewPager save Fragment in FragmentManager with particular tags, So We can get ViewPager's fragment by FragmentManager class by providing tag. And ViewPager provide tag to each fragment by following syntax : Fragment page = getSupportFragmentManager(). findFragmentByTag("android:switcher:" + R.

Can we add activity in ViewPager?

You can't use ViewPager to swipe between Activities . You need to convert each of you five Activities into Fragments , then combine everything in one FragmentActivity with the Adapter you use with ViewPager .

How do you call ViewPager fragment from activity?

You'll just need to cast it to the real fragment class if you want to call a specific method. int pos = viewpager. getCurrentItem(); Fragment activeFragment = adapter. getItem(pos); if(pos == 0) ((NPListFragment)activeFragment).

How do I use ViewPager?

You can create swipe views using AndroidX's ViewPager widget. To use ViewPager and tabs, you need to add a dependency on ViewPager and on Material Components to your project. To insert child views that represent each page, you need to hook this layout to a PagerAdapter .

How do I add a viewpager to an existing layout?

Steps for implementing viewpager: Adding the ViewPager widget to the XML layout (usually the main_layout). Creating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class. An adapter populates the pages inside the Viewpager.

What is the use of fragmentmanager in Android?

A FragmentManager manages Fragments in Android, specifically, it handles transactions between fragments. A transaction is a way to add, replace, or remove fragments. getPageTitle (int pos): (optional) Similar to getItem () this methods returns the title of the page at index pos.

How to remove all views from a pager page?

//remove the pages. basically call to method removeAllViews from `ViewPager` pagerAdapter.removePages (); pagerAdapter.addPage (pass your fragment); After the advice of Peri Hartman, it started to work after I set null do ViewPager adapter and put the adapter again after the views removed. Before this the page 0 doesnt showed its list contents.

Is it possible to update viewpager dynamically?

Update ViewPager dynamically? Although we see it often, using POSITION_NONE does not seem to be the way to go as it is very inefficient memory-wise. Here in this question, we should consider using Alvaro's approach:


1 Answers

you can follow this approach:

just Use fragments for each view in a pager.

write the below code in onCreate() method of the FragmentActivity.

List<Fragment> fragments = new Vector<Fragment>();

//for each fragment you want to add to the pager
Bundle page = new Bundle();
page.putString("url", url);
fragments.add(Fragment.instantiate(this,MyFragment.class.getName(),page));

//after adding all the fragments write the below lines

this.mPagerAdapter  = new PagerAdapter(super.getSupportFragmentManager(), fragments);

mPager.setAdapter(this.mPagerAdapter);

A sample fragment definition:

public class MyFragment extends Fragment {


public static MyFragment newInstance(String imageUrl) {

final MyFragment mf = new MyFragment ();

    final Bundle args = new Bundle();
    args.putString("somedata", "somedata");
    mf.setArguments(args);

    return mf;
}

public MyFragment() {}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String data = getArguments().getString("somedata");
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflate and locate the main ImageView
    final View v = inflater.inflate(R.layout.my_fragment_view, container, false);
    //... 
    return v;
}

FragmentPagerAdapter

public class MyFragmentAdapter extends FragmentPagerAdapter {

public static int pos = 0;

private List<Fragment> myFragments;

public MyFragmentAdapter(FragmentManager fm, List<Fragment> myFrags) {
    super(fm);
    myFragments = myFrags;
}

@Override
public Fragment getItem(int position) {

    return myFragments.get(position);

}

@Override
public int getCount() {

    return myFragments.size();
}

@Override
public CharSequence getPageTitle(int position) {

    setPos(position);

    String PageTitle = "";

    switch(pos)
    {
        case 0:
                PageTitle = "page 1";
                break;
        case 1:
                PageTitle = "page 2";
                break;
        case 2:
                PageTitle = "page 3";
                break;
        case 3:
                PageTitle = "page 4";
                break;
        case 4:
                PageTitle = "page 5";
                break;
        case 5: 
                PageTitle = "page 6";
                break;
        case 6:
                PageTitle = "page 7";
                break;
    }
    return PageTitle;
}

public static int getPos() {
    return pos;
}

 public static void setPos(int pos) {
    MyFragmentAdapter.pos = pos;
 }
}
like image 99
SKK Avatar answered Oct 11 '22 15:10

SKK