android Multiple View Pager in Single Activity not showing second View Pager - android

I have 2 view pagers in a activity
<android.support.v4.view.ViewPager
android:id="#+id/latestProductSwipeCard"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/popularProductSwipeCard"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
and I created an adapter
public class ProductSwipePageAdapter extends FragmentPagerAdapter {
List<Product> products;
public ProductSwipePageAdapter(FragmentManager fm) {
super(fm);
}
public ProductSwipePageAdapter(FragmentManager fm, List<Product> products) {
super(fm);
this.products = products;
}
#Override
public Fragment getItem(int position) {
return ProductCardFragment.newInstance(products.get(position));
}
#Override
public int getCount() {
return products.size();
}}
And i setting the pager
productSwipePageAdapter1 = new ProductSwipePageAdapter(getFragmentManager(), allProducts);
latestProductSwipeCard.setAdapter(productSwipePageAdapter1);
productSwipePageAdapter2 = new ProductSwipePageAdapter(getFragmentManager(), allProducts1);
popularProductSwipeCard.setAdapter(productSwipePageAdapter2);
As a Result it showing only one view pager
enter image description here

if you not set specific height of view pager than ViewPager access all height
so if you show both ViewPager than you set Weight property in your XMl
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/latestProductSwipeCard"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<android.support.v4.view.ViewPager
android:id="#+id/popularProductSwipeCard"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>

See This Example Its Working for me
activity_main.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">
<android.support.v4.view.ViewPager
android:id="#+id/latestProductSwipeCard"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<android.support.v4.view.ViewPager
android:id="#+id/popularProductSwipeCard"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
fragment_main.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fragment"/>
</RelativeLayout>
MainActivity.java
package com.stackoverflowtesting;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
ViewPager mViewPager1 = (ViewPager) findViewById(R.id.latestProductSwipeCard);
mViewPager1.setAdapter(mSectionsPagerAdapter);
// Set up the ViewPager with the sections adapter.
ViewPager mViewPager2 = (ViewPager) findViewById(R.id.popularProductSwipeCard);
mViewPager2.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}

Related

Change TextView values with method inside Fragment (NullPointerException)

I'm trying to make an app (for learning purposes) where I have a few tabs with scrollable content.
I have a collapsing app bar with a ViewPager for the main layout and three identical layouts with a TextView inside a NestedScrollView where the only difference is the image on top of the text. I also have three fragment classes with the same code inside. Everything worked fine.
But since I'm using the same layout in each tab, I thought that instead of a xml file and a java class for each tab, I could just have one of each and then somehow change the content for each tab inside my Adapter.
So I tried to just create a method to do that inside my tabFragment class. But I can't seem to find a way to modify the TextView. I keep getting a NullPointerException every time.
What am I missing?
Is my approach wrong? If so, what would be a better one? How do I solve this?
Thank you in advance :)
Here's my fragment class right now (the only one remaining ):
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.example.tablayoutwithscrollview.R;
public class TabFragment extends Fragment {
private TextView textView;
private int text, image;
public TabFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.tab1, container, false);
//textView = view.findViewById(R.id.textView);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
textView = getView().findViewById(R.id.textView);
}
public void setTabContent(int text, int image)
{
textView.setText(text);
textView.setCompoundDrawablesWithIntrinsicBounds(0,image,0,0);
}
}
My adapter class:
import android.content.Context;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.tablayoutwithscrollview.Tabs.TabFragment;
public class MyAdapter extends FragmentPagerAdapter {
private static int tabCount;
Context context;
public MyAdapter(FragmentManager fm, int tabCount, Context context){
super(fm);
this.tabCount = tabCount;
this.context = context;
}
#Override
public Fragment getItem(int position) {
TabFragment fragment;
switch (position)
{
case 0:
fragment = new TabFragment();
fragment.setTabContent(R.string.lorem_ipsum, R.drawable.jackfruit);
return fragment;
case 1:
fragment = new TabFragment();
fragment.setTabContent(R.string.lorem_ipsum, R.drawable.guava);
return fragment;
case 2:
fragment = new TabFragment();
fragment.setTabContent(R.string.lorem_ipsum, R.drawable.pomegranate);
return fragment;
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position)
{
switch (position)
{
case 0:
return context.getString(R.string.tab1_title);
case 1:
return context.getString(R.string.tab2_title);
case 2:
return context.getString(R.string.tab3_title);
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
MainActivity:
package com.example.tablayoutwithscrollview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
populatesTabLayout(tabLayout);
MyAdapter myAdapter = new MyAdapter(getSupportFragmentManager(), tabLayout.getTabCount(), this);
viewPager.setAdapter(myAdapter);
tabLayout.setupWithViewPager(viewPager);
}
private void populatesTabLayout(TabLayout tabLayout)
{
for (int i = 0; i<3; i++)
{
tabLayout.addTab(tabLayout.newTab());
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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/coordLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapseToolBar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:toolbarId="#+id/toolbar">
<ImageView
android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="#drawable/strawberry" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"></androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.CollapsingToolbarLayout>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:visibility="visible" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
And my tab layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/tabNestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableTop="#drawable/jackfruit"
android:text="#string/lorem_ipsum" />
</androidx.core.widget.NestedScrollView>
Here's how it's supposed to work (from before when each tab had a fragment class and a layout file):
The problem is that the created TabFragment instance has not been attached to the activity yet, therefore the textView does not inflated at that point.
You should pass the text to the TabFragment instance as an argument in the MyAdapter#getItem(..) method.
...
case 0:
fragment = new TabFragment();
Bundle args = new Bundle();
args.putString("key", textString);
fragment.setArguments(args);
return fragment
...
After that set the text for the TextView instance in the onViewCreated(...) method:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = getView().findViewById(R.id.textView);
textView.setText(getArguments().getString("key"));
}
Or you can see a nice example at the Android Reference.

Nested fragment with viewpager where viewpager not loading the fragments

I have a activity in which i am loading a fragment
Home fragmentA = new Home();
android.support.v4.app.FragmentTransaction fragmentTransactionA = getSupportFragmentManager().beginTransaction();
fragmentTransactionA.replace(R.id.mainFrame, fragmentA);
fragmentTransactionA.commitAllowingStateLoss();
in my home fragment i have a slidingtablayout and viewpager
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="mobile.data.woises.fragment.Home">
<mobile.data.woises.tabs.SlidingTabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/main_color"
app:tabIndicatorColor="#0bbea5"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white"/>
</FrameLayout>
and my java code of my home fragment is this
public class Home extends Fragment {
View infHome;
SlidingTabLayout slidingTabLayout;
ViewPager viewPager;
private FragmentPageAdapterHome Pa;
CharSequence Titles[] = {"Requirements", "Notification"};
int Numboftabs = 2;
public Home() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
infHome = inflater.inflate(R.layout.fragment_home2, container, false);
return infHome;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
slidingTabLayout = (SlidingTabLayout) infHome.findViewById(R.id.sliding_tabs);
viewPager = (android.support.v4.view.ViewPager) infHome.findViewById(R.id.viewpager);
// adapter = new ViewPagerAdapter(getResources(), getChildFragmentManager());
// FragmentManager fragmentManager = getChildFragmentManager();
Pa = new FragmentPageAdapterHome(getChildFragmentManager(), Titles, Numboftabs, getActivity().getApplicationContext());
viewPager.setAdapter(Pa);
slidingTabLayout.setSelectedIndicatorColors(Color.parseColor("#0bbea5"));
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setViewPager(viewPager);
}
}
And my FragmentPageAdapterHome is this
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import android.view.ViewGroup;
import java.util.HashMap;
import java.util.Map;
import mobile.data.woises.fragment.Notification;
import mobile.data.woises.fragment.Requirements;
/*import com.example.uday.innohabit.fragments.FragA;
import com.example.uday.innohabit.fragments.FragB;
import com.example.uday.innohabit.fragments.FragC;*/
/**
* Created by Uday on 05-11-2015.
*/
public class FragmentPageAdapterHome extends FragmentPagerAdapter {
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private Context mContext;
private String WoisesId;
CharSequence Titles[];
int NumofTabs;
//int icons[] = {R.drawable.search,R.drawable.cart,R.drawable.quickorder};
//String tabTitle;
public FragmentPageAdapterHome(FragmentManager fm, CharSequence mTitles[],
int mNumbOfTabsumb, Context context) {
super(fm);
this.Titles = mTitles;
this.NumofTabs = mNumbOfTabsumb;
mFragmentManager = fm;
mFragmentTags = new HashMap<Integer, String>();
mContext = context;
// TODO Auto-generated constructor stub
}
#Override
public Fragment getItem(int arg0) {
Log.d("FragmentPageAdapterHome","Arg="+arg0);
switch (arg0) {
case 0:
Requirements requirements = new Requirements();
return requirements;
case 1:
Notification notification = new Notification();
return notification;
default:
break;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return NumofTabs;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object obj = super.instantiateItem(container, position);
if (obj instanceof Fragment) {
// record the fragment tag here.
Fragment f = (Fragment) obj;
String tag = f.getTag();
mFragmentTags.put(position, tag);
}
return obj;
}
public Fragment getFragment(int position) {
String tag = mFragmentTags.get(position);
if (tag == null)
return null;
return mFragmentManager.findFragmentByTag(tag);
}
}
all the Log in the Requirement and the notification fragment is being displayed in Logcat that means the function is being called but the fragment is not being displayed please help me where i am making the mistake .
I was using the getsupportfragmentmanager() but someone on stack overflow posted that i should use the getChildFragmentManager() when it is nested fragment .
what should i do .please help me i am unable to figure out what is problem.
You set your ViewPagers height to 0px. layout_weight is a feature from LinearLayout, since you are using FrameLayout, nothing is shown. Possible fixes:
<LinearLayout 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"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="mobile.data.woises.fragment.Home">
<mobile.data.woises.tabs.SlidingTabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/main_color"
app:tabIndicatorColor="#0bbea5"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#android:color/white"/>
</LinearLayout>
//or:
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="mobile.data.woises.fragment.Home">
<mobile.data.woises.tabs.SlidingTabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/main_color"
app:tabIndicatorColor="#0bbea5"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#android:color/white"/>
</FrameLayout>
Also, don't use px, since your layouts will look different on different screens. Use dp (density points) instead!

android switching one fragment for another

edit: still haven't figure this out
Okay, so I have 2 fragments. The first fragment (fragment_main) is a every "page" of a ViewPager of 3 fragments. There is one button on fragment_main, and I want it so that when I click this button, I replace the ViewPager's fragment (fragment_main), with a new fragment (fragment2). Here's my main Activity:
package com.example.wyatt.listtest;
import java.util.Locale;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
return PlaceholderFragment.newInstance(position + 1);
case 1:
return PlaceholderFragment.newInstance(position + 1);
case 2:
return PlaceholderFragment.newInstance(position + 1);
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Button b;
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
b = (Button) rootView.findViewById(R.id.buttonNew);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//I would like to switch fragment_main
//for fragment 2 when this is clicked
}
});
return rootView;
}
}
public static class ReplacementFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static ReplacementFragment newInstance(int sectionNumber) {
ReplacementFragment fragment = new ReplacementFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public ReplacementFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment2, container, false);
return rootView;
}
}
}
here's the xml for mainActivity:
<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" >
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:screenOrientation="portrait"
android:layout_alignParentTop="true">
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:textColor="#000" />
</android.support.v4.view.ViewPager>
here's fragment_main 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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<TextView android:id="#+id/section_label" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_below="#+id/section_label"
android:layout_centerHorizontal="true"
android:text="test" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="new fragment"
android:id="#+id/buttonNew"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
here is fragment2 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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<TextView android:id="#+id/section_label" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!-- This should be EditText, not EditTexta -->
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:text="done"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
If you just want to swap out fragments from the main fragment (which uses a viewpager), then you can just call the Activitiy's support fragment manager and swap the fragments.
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Adding 1 as the default value for new instance of ReplacementFragment
//because I'm not sure what it's purpose is from your code's static constructor.
ReplacementFragment frag = ReplacementFragment.newInstance(1);
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container, frag);
ft.commit();
}
});
Also, R.id.container is in reference to a FrameLayout that contains the ViewPager / ReplaceFragment when you swap back and forth. Create this by modifying your main xml file:
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:screenOrientation="portrait"
android:layout_alignParentTop="true">
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:textColor="#000" />
</android.support.v4.view.ViewPager>
</FrameLayout>
As you can see, we are using the FrameLayout as a container for your desired fragments for your main Activity. Initially, you use it for holding the ViewPager with it's three sliding screens, and upon button click you use the fragment manager from your activity to replace the fragment that is lives in your FrameLayout container.
***Note: Depending on if you are using these imports:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
You will get a crash using SupportFragmentManager, instead you FragmentManager, or just switch the imports to above.

Android - ActionBarActivity with ViewPager

i have a problem with ActionBarActivity and ViewPager.
On my "main-activity" which is a ActionBarActivity i have some tabs, which are fragments.
I want to implement the "swipe-feature" between these tabs.
I've already read the following tutorial:
http://developer.android.com/training/implementing-navigation/lateral.html
Actually i have implemented the whole code, but my app wont work. :(
There is no "swipe-feature" between the tabs.
Here is my code of the main-activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hauptmenue_extended);
try {
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// ViewPager ...
pagerAdapter = new CollectionPagerAdapter(
getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(1);
viewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// Add all tabs to the actionbar...
Tab tabB = actionBar.newTab();
tabB.setText("Home");
tabB.setIcon(R.drawable.icon_home);
tabB.setTabListener(new TabListener<Startmenue_activity>(this,
"Start", Startmenue_activity.class, viewPager));
actionBar.addTab(tabB);
Tab tabA = actionBar.newTab();
tabA.setText("");
tabA.setIcon(R.drawable.icon_nachrichten_sel);
tabA.setTabListener(new TabListener<Nachrichten_activity>(this,
"News", Nachrichten_activity.class, viewPager));
actionBar.addTab(tabA);
Tab tabC = actionBar.newTab();
tabC.setText("");
tabC.setIcon(R.drawable.icon_favoriten);
tabC.setTabListener(new TabListener<Favoriten_activity>(this,
"Favs", Favoriten_activity.class, viewPager));
actionBar.addTab(tabC);
And my adapter looks like this:
public class CollectionPagerAdapter extends FragmentPagerAdapter {
final int NUM_ITEMS = 3; // number of tabs
List<Fragment> fragments = new ArrayList<Fragment>();
public Fragment getItem(int pos) {
return fragments.get(pos);
}
public void addFragment(Fragment f) {
fragments.add(f);
}
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
Fragment home_Fragment = new Startmenue_activity();
addFragment(home_Fragment);
Fragment news_Fragment = new Nachrichten_activity();
addFragment(news_Fragment);
Fragment favoriten_Fragment = new Favoriten_activity();
addFragment(favoriten_Fragment);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
}
Oh and my XML of the main-activity looks like this:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Hauptmenue_extended" >
<!-- The ViewPager -->
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<!-- The main content view -->
<FrameLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#fff"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.view.ViewPager>
</android.support.v4.widget.DrawerLayout>
There's a bunch of things that I don't fully understand about your code, for example, why are you putting a ListView inside the ViewPager?. Anyways if you want to implement some tabs with the swipe feature. Here is how do it:
First the 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/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top" />
</android.support.v4.view.ViewPager>
Now the activity:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new SampleAdapter(this, getSupportFragmentManager()));
}
}
The adapter:
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class SampleAdapter extends FragmentStatePagerAdapter {
Context ctxt = null;
public SampleAdapter(Context ctxt, FragmentManager mgr) {
super(mgr);
this.ctxt = ctxt;
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new SimpleFragment("Hi");
case 1:
return new SimpleFragment("There");
case 2:
return new SimpleFragment("Fella");
}
return null;
}
#Override
public String getPageTitle(int position) {
switch (position) {
case 0:
return "First Tab";
case 1:
return "Second Tab";
case 2:
return "Third Tab";
}
return null;
}
}
And the SimpleFragment:
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
#SuppressLint("ValidFragment")
public class SimpleFragment extends Fragment {
String text;
public SimpleFragment(String string) {
text = string;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment, container, false);
TextView textview = (TextView) root.findViewById(R.id.textView1);
textview.setText(text);
return root;
}
}
And the fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Hope this helps :)
Try this out. But I've not tested it.
http://wptrafficanalyzer.in/blog/swipable-navigation-tabs-using-actionbarcompat-library/

Android : Fragment code causes crash of the application

This is my Menu java code that include fragments in a swipe view interface where i had separate activity for each fragment. I encounter a application class by calling this activity and i wish that someone could help me to solve my problem as i'm a beginner in android programming. Your help is very appreciated.
package com.example.lazynumber;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class MainMenu extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch(position){
case 0:
Fragment fragment = new GetNumberFragment();
return fragment;
case 1:
Fragment fragment2 = new QRFragment();
return fragment2;
case 2:
Fragment fragment3 = new ProfileFragment();
return fragment3;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class GetNumberFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public GetNumberFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_get_number_intro,
container, false);
return rootView;
}
}
#SuppressLint("ValidFragment")
public class QRFragment extends Fragment{
public QRFragment(){};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView2 = inflater.inflate(R.layout.qrintro, container, false);
Button testingButton = (Button)findViewById(R.id.goinQRPay);
testingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goTesting();
}
});
return rootView2;
}
}
private void goTesting(){
Intent goTesting = new Intent(this, Testingbutton.class);
startActivity(goTesting);
}
public static class ProfileFragment extends Fragment{
public ProfileFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView3 = inflater.inflate(R.layout.activity_profile_setting, container, false);
return rootView3;
}
}
}
These are my xml codes for reference if needed.
first one is the mainmenu xml
<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=".MainMenu" >
<!--
This title strip will display the currently visible page title, as well as the page
titles for adjacent pages.
-->
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
And this next xml is the one that i needed to have a function which is QRFragment activity xml interface.
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".QRIntro" >
<ImageView
android:id="#+id/qrintropic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/qrlazy" />
<Button
android:id="#+id/goinQRPay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/qrintropic"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="#string/buttontoqr" />"
</RelativeLayout>
The fragments need to be inserted into some kind of container layout like a FrameLayout. if you add that then you can use this method to replace the fragment
public static void replaceFragment(Activity activity, int containerlayoutId, Fragment newFragment) {
FragmentTransaction transaction = activity.getFragmentManager().beginTransaction().replace(containerlayoutId, newFragment);
transaction.commit();
activity.getFragmentManager().executePendingTransactions();
}

Categories

Resources