In my android application I have two .xaml layouts like activity_1 and activity_2 and I want to change these layout's activity through 2 swipeable tabs because after that i want to add more tabs: and below is my activity:
package com.example.hakslogin;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.view.View.OnClickListener;
public class LoginSuccess extends ActionBarActivity {
static final String LOG_TAG = "SlidingTabsBasicFragment";
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_success);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setAdapter(new SamplePagerAdapter());
mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_success, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class SamplePagerAdapter extends PagerAdapter {
/**
* #return the number of pages to display
*/
#Override
/* public int getCount() { //I am not using this method
return 5;
}*/
/**
* #return true if the value returned from
* {#link #instantiateItem(ViewGroup, int)} is the same object
* as the {#link View} added to the {#link ViewPager}.
*/
#Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
#Override
/*public CharSequence getPageTitle(int position) { //I am not using this //method because I am giving name of tabs in SlidingTabLayout.java class
return pageTitle + " " + (position + 1);
}*/
// END_INCLUDE (pageradapter_getpagetitle)
/**
* Instantiate the {#link View} which should be displayed at
* {#code position}. Here we inflate a layout from the apps resources
* and then change the text view to signify the position.
*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Inflate a new layout from our resources
View view = getLayoutInflater().inflate(R.layout.activity_login_success,
container, false);
container.addView(view);
// Retrieve a TextView from the inflated View, and update it's text
// --comment by me
//TextView title = (TextView) view.findViewById(R.id.item_title);
//title.setText(String.valueOf(position + 1));
Log.i(LOG_TAG, "instantiateItem() [position: " + position + "]");
return view;
}
/**
* Destroy the item from the {#link ViewPager}. In our case this is
* simply removing the {#link View}.
*/
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
Log.i(LOG_TAG, "destroyItem() [position: " + position + "]");
}
}
}
And I am doing above the same code into my another activity like below:
package com.example.hakslogin;
import com.example.android.common.view.SlidingTabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableRow;
import android.widget.TextView;
public class AddChildActivity extends ActionBarActivity {
static final String LOG_TAG = "SlidingTabsBasicFragment";
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_child);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setAdapter(new SamplePagerAdapter());
mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_child, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class SamplePagerAdapter extends PagerAdapter {
/*#Override
public int getCount() {
return 5;
}*/
#Override
public boolean isViewFromObject(View view, Object o) {
return o == view;
}
/*#Override
public CharSequence getPageTitle(int position) {
return pageTitle + " " + (position + 1);
}*/
// END_INCLUDE (pageradapter_getpagetitle)
/**
* Instantiate the {#link View} which should be displayed at
* {#code position}. Here we inflate a layout from the apps resources
* and then change the text view to signify the position.
*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
// Inflate a new layout from our resources
View view = getLayoutInflater().inflate(R.layout.activity_add_child,
container, false);
container.addView(view);
// Retrieve a TextView from the inflated View, and update it's text
// --comment by me
//TextView title = (TextView) view.findViewById(R.id.item_title);
//title.setText(String.valueOf(position + 1));
Log.i(LOG_TAG, "instantiateItem() [position: " + position + "]");
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
Log.i(LOG_TAG, "destroyItem() [position: " + position + "]");
}
}
}
and below is SlidingTabLayout.java class:
package com.example.android.common.view;
import com.example.hakslogin.LoginSuccess;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.TextView;
public class SlidingTabLayout extends HorizontalScrollView {
/**
* Allows complete control over the colors drawn in the tab layout. Set with
* {#link #setCustomTabColorizer(TabColorizer)}.
*/
public interface TabColorizer {
/**
* #return return the color of the indicator used when {#code position} is selected.
*/
int getIndicatorColor(int position);
/**
* #return return the color of the divider drawn to the right of {#code position}.
*/
int getDividerColor(int position);
}
private static final int TITLE_OFFSET_DIPS = 24;
private static final int TAB_VIEW_PADDING_DIPS = 16;
private static final int TAB_VIEW_TEXT_SIZE_SP = 12;
private int mTitleOffset;
private int mTabViewLayoutId;
private int mTabViewTextViewId;
private ViewPager mViewPager;
private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;
String value = "";
private final SlidingTabStrip mTabStrip;
// public SlidingTabLayout() {
// TODO Auto-generated constructor stub
//}
public SlidingTabLayout(Context context) {
this(context, null);
}
public SlidingTabLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Disable the Scroll Bar
setHorizontalScrollBarEnabled(false);
// Make sure that the Tab Strips fills this View
setFillViewport(true);
mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);
mTabStrip = new SlidingTabStrip(context);
addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
/**
* Set the custom {#link TabColorizer} to be used.
*
* If you only require simple custmisation then you can use
* {#link #setSelectedIndicatorColors(int...)} and {#link #setDividerColors(int...)} to achieve
* similar effects.
*/
public void setCustomTabColorizer(TabColorizer tabColorizer) {
mTabStrip.setCustomTabColorizer(tabColorizer);
}
/**
* Sets the colors to be used for indicating the selected tab. These colors are treated as a
* circular array. Providing one color will mean that all tabs are indicated with the same color.
*/
public void setSelectedIndicatorColors(int... colors) {
mTabStrip.setSelectedIndicatorColors(colors);
}
/**
* Sets the colors to be used for tab dividers. These colors are treated as a circular array.
* Providing one color will mean that all tabs are indicated with the same color.
*/
public void setDividerColors(int... colors) {
mTabStrip.setDividerColors(colors);
}
/**
* Set the {#link ViewPager.OnPageChangeListener}. When using {#link SlidingTabLayout} you are
* required to set any {#link ViewPager.OnPageChangeListener} through this method. This is so
* that the layout can update it's scroll position correctly.
*
* #see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
*/
public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
mViewPagerPageChangeListener = listener;
}
/**
* Set the custom layout to be inflated for the tab views.
*
* #param layoutResId Layout id to be inflated
* #param textViewId id of the {#link TextView} in the inflated view
*/
public void setCustomTabView(int layoutResId, int textViewId) {
mTabViewLayoutId = layoutResId;
mTabViewTextViewId = textViewId;
}
/**
* Sets the associated view pager. Note that the assumption here is that the pager content
* (number of tabs and tab titles) does not change after this call has been made.
*/
public void setViewPager(ViewPager viewPager) {
mTabStrip.removeAllViews();
mViewPager = viewPager;
if (viewPager != null) {
viewPager.setOnPageChangeListener(new InternalViewPagerListener());
populateTabStrip();
}
}
/**
* Create a default view to be used for tabs. This is called if a custom tab view is not set via
* {#link #setCustomTabView(int, int)}.
*/
protected TextView createDefaultTabView(Context context) {
TextView textView = new TextView(context);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
textView.setTypeface(Typeface.DEFAULT_BOLD);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// If we're running on Honeycomb or newer, then we can use the Theme's
// selectableItemBackground to ensure that the View has a pressed state
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
outValue, true);
textView.setBackgroundResource(outValue.resourceId);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
// If we're running on ICS or newer, enable all-caps to match the Action Bar tab style
//textView.setAllCaps(true);
//textView.setAllCaps(true);
}
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
textView.setPadding(padding, padding, padding, padding);
return textView;
}
String names[] = {"Home","Add Child"};//,"Add Item", "Questions", "Answer"};
int len = names.length;
private void populateTabStrip() {
final PagerAdapter adapter = mViewPager.getAdapter();
final View.OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < names.length ; i++) {// i++) {;adapter.getCount()
View tabView = null;
TextView tabTitleView = null;
if (mTabViewLayoutId != 0) {
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
false);
tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabTitleView == null && TextView.class.isInstance(tabView)) {
tabTitleView = (TextView) tabView;
}
LoginSuccess.pageTitle = names[i].toString();
tabTitleView.setText(names[i].toString());//adapter.getPageTitle(i)
tabView.setOnClickListener(tabClickListener);
mTabStrip.addView(tabView);
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mViewPager != null) {
scrollToTab(mViewPager.getCurrentItem(), 0);
}
}
private void scrollToTab(int tabIndex, int positionOffset) {
final int tabStripChildCount = mTabStrip.getChildCount();
if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
return;
}
View selectedChild = mTabStrip.getChildAt(tabIndex);
if (selectedChild != null) {
int targetScrollX = selectedChild.getLeft() + positionOffset;
if (tabIndex > 0 || positionOffset > 0) {
// If we're not at the first child and are mid-scroll, make sure we obey the offset
targetScrollX -= mTitleOffset;
}
scrollTo(targetScrollX, 0);
}
}
private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
private int mScrollState;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int tabStripChildCount = mTabStrip.getChildCount();
if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
return;
}
mTabStrip.onViewPagerPageChanged(position, positionOffset);
View selectedTitle = mTabStrip.getChildAt(position);
int extraOffset = (selectedTitle != null)
? (int) (positionOffset * selectedTitle.getWidth())
: 0;
scrollToTab(position, extraOffset);
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
#Override
public void onPageScrollStateChanged(int state) {
mScrollState = state;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageScrollStateChanged(state);
}
}
#Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
}
private class TabClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
if (v == mTabStrip.getChildAt(i)) {
mViewPager.setCurrentItem(i);
return;
}
}
}
}
}
I am using this link, and its show me two tabs on any first activity but the problem is that its show layout multiple times one on my activity layout and on sliding page layout, Kindly suggest me what can I handle it, waiting for reply Thanks.
Related
I'm trying to populate 3 ListFragments that are in a Tabbed ViewPager Layout. (Using one of the templates in Android Studio.)
I have been able to successfully put items into the SQLite DB, but I'm having a hard time populating the ListView(s). It would be easy if things weren't static, but the static-ness simply adds to the complexity.
package com.example.listapp;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ListFragment;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
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.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import static com.example.listapp.ItemData.Items.ORDERB;
import static com.example.listapp.ItemData.Items.TABLE_NAME;
import static com.example.listapp.ItemData.Items.TYPE;
import static com.example.listapp.ItemData.Items.LIST_TEXT;
public class MainActivity extends AppCompatActivity {
private ItemData ItemsDb;
String listText = null;
public static String[] FROM = { LIST_TEXT };
public static int[] TO = { R.id.list_text };
public static final Uri CONTENT_URI = Uri.parse("content://"
+ "com.example.listapp" + "/" + TABLE_NAME);
/**
* 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ItemsDb = new ListData(getApplicationContext());
Intent saveIntent = getIntent();
listText = saveIntent.getStringExtra(ItemCreate.EXTRA_MESSAGE);
if (rlistText != null) {
SQLiteDatabase db = ItemsDb.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ORDERB, System.currentTimeMillis());
values.put(ITEM_TEXT, listText);
db.insertOrThrow(TABLE_NAME, null, values);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
public void createItem(View view) {
Intent intent = new Intent(this, ItemCreate.class);
startActivity(intent);
}
#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).
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 "List1";
case 1:
return "List2";
case 2:
return "List3";
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends ListFragment {
/**
* 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) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Cursor cursor = getActivity().getContentResolver().query(CONTENT_URI, FROM, null, null, "_ID DESC");
ListView listItems = getListView();
ListAdapter adapter = new SimpleCursorAdapter(getContext(), R.layout.list_item, cursor, FROM, TO, 0);
listItems.setAdapter(adapter);
}
}
}
The adapter does get properly set, but I get the following error when I run the code:
E/ActivityThread: Failed to find provider info for com.example.listapp
What am I doing wrong?
I am developing a podcast app and I have two pages right now. A listening page and a list of podcasts page. I placed my MainActivity at the bottom of this question with my object and singleton classes.
So my problem is when I navigate from the second page (the list of podcasts) back to the first page (Now Playing) where there will be a media player added shortly.
The code to move from Page 2 to Page 1 is:
mViewPager.setCurrentItem(0, true); // now playing
but when I call something like this directly after the above statement:
home_title.setText(app.getCurrentPodcast().getTitle());
I get a NullPointerException.
I'm confused on how to update a TextView from another fragment within a PlaceHolder class which uses a standard ViewPager object. I want to be able to update the home_title from another fragment or thread but I don't know how. Help?
Podcast Object:
package Objects;
/**
* XmlPodcastObject.java
*
* This object is designed to handle the XML content from the podcasts on the Prindle Site
*
* #author Alexander Miller, 2016
*/
public class XmlPodcastObject {
private String title;
private String podcastUrl;
private String storyUrl;
private String content;
private String summary;
private String timeOfStream;
/**
* XmlPodcastObject
*
* XmlPodcastObject contains all of the information for podcasts streamed on the app.
* #param titl String title of the podcast
* #param imageUr String image url of the podcast
* #param storyUr String url for the story of the podcast
* #param conten String all of the content explaining the podcast
* #param summar String a breif summary of the content
* #param timeOfStrea String duration of the podcast in HH:mm:ss
*/
public XmlPodcastObject(String titl, String imageUr, String storyUr, String conten, String summar, String timeOfStrea)
{
this.title = titl;
this.podcastUrl = imageUr;
this.storyUrl = storyUr;
this.content = conten;
this.summary = summar;
this.timeOfStream = timeOfStrea;
}
public XmlPodcastObject()
{
}
//=========================================================================================
// <Getters/Setters>
//=========================================================================================
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPodcastUrl() {
return podcastUrl;
}
public void setPodcastUrl(String imageUrl) {
this.podcastUrl = imageUrl;
}
public String getStoryUrl() {
return storyUrl;
}
public void setStoryUrl(String storyUrl) {
this.storyUrl = storyUrl;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getTimeOfStream() {
return timeOfStream;
}
public void setTimeOfStream(String timeOfStream) {
this.timeOfStream = timeOfStream;
}
//=========================================================================================
// </Getters/Setters>
//=========================================================================================
}
Singleton:
package Utils;
import java.util.ArrayList;
import Objects.XmlPodcastObject;
/**
* Created by depauw on 12/3/15.
*/
public class App {
private ArrayList<XmlPodcastObject> podcastArray;
private XmlPodcastObject currentPodcast;
private static App ourInstance = new App();
public static App getInstance() {
return ourInstance;
}
public App() {
}
public ArrayList<XmlPodcastObject> getPodcastArray() {
return podcastArray;
}
public int getPodcastArraySize(){
try{
return podcastArray.size();
}
catch(NullPointerException e)
{
return 0;
}
}
public void setPodcastArray(ArrayList<XmlPodcastObject> podcastArray) {
this.podcastArray = podcastArray;
}
public XmlPodcastObject getCurrentPodcast() {
return currentPodcast;
}
public void setCurrentPodcast(XmlPodcastObject currentPodcast) {
this.currentPodcast = currentPodcast;
}
}
MainActivity:
package edu.depauw.prindle.examiningethics;
import android.content.Context;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
import Objects.XmlPodcastObject;
import Utils.App;
import Utils.PodcastListArrayAdapter;
import Utils.XMLParser;
/*
* - hambuger icon no swipe functionality.
* - move settings to new activity, access via menu option
* - add singleton class for cache
* - once a day notification of new RSS feed object
*/
public class MainActivity extends AppCompatActivity {
private static boolean developerMode = false;
/**
* 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private static ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Microphone action coming soon.", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
}
#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).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.section_podcast_list);
case 1:
return getString(R.string.section_now_playing);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment{
private ListView Listv;
private SwipeRefreshLayout swipeContainer;
private static App app;
private TextView home_title;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private PodcastListArrayAdapter podcastListArrayAdapter;
/**
* 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() {
app = new App();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = null;
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1)
{
rootView = inflater.inflate(R.layout.fragment_home, container, false);
home_title = (TextView) rootView.findViewById(R.id.home_media_layout_track_title);
try
{
home_title.setText(app.getCurrentPodcast().getTitle());
}
catch (NullPointerException e)
{
e.printStackTrace();
}
if (app.getPodcastArraySize() == 0 && isNetworkAvailable())
{
new AsyncTaskParseJson(false).execute();
}
}
else {
rootView = inflater.inflate(R.layout.fragment_podcast_list, container, false);
// UI binding
swipeContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeContainer);
swipeContainer.setColorSchemeColors(Color.rgb(253, 221, 100), Color.rgb(0, 0, 0));
Listv = (ListView) rootView.findViewById(R.id.fragment_podcast_list_podcast_listview);
TextView textView = (TextView) rootView.findViewById(R.id.fragment_podcast_list_section_label);
// Setup refresh listener which triggers new data loading
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Your code to refresh the list here.
// Make sure you call swipeContainer.setRefreshing(false)
// once the network request has completed successfully.
if (isNetworkAvailable()) {
new AsyncTaskParseJson(true).execute();
} else {
Toast.makeText(getActivity(), "No internet connection found.", Toast.LENGTH_LONG).show();
}
}
});
// Onclick listener to return to the listening page.
Listv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mViewPager.setCurrentItem(0, true); // now playing
app.setCurrentPodcast(app.getPodcastArray().get(position));
}
});
if (app.getPodcastArraySize() == 0 && isNetworkAvailable())
{
new AsyncTaskParseJson(true).execute();
}
else if(app.getPodcastArraySize() != 0)
{
podcastListArrayAdapter = new PodcastListArrayAdapter(getActivity(), R.layout.fragment_podcast_list_item, app.getPodcastArray());
}
else
{
// error
Log.d(""+this.getClass().getName(),"Error 1");
}
textView.setText("Podcasts");
}
return rootView;
}
/**
* isNetworkAvailable
*
* #return boolean true is internet is connected or connecting. False if off or none found.
*/
private boolean isNetworkAvailable()
{
ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/**
* AsyncTaskParseJson
*
* This asynchronous task downloads all of the podcasts available and
* returns a ListView compatible set of content.
*/
public class AsyncTaskParseJson extends AsyncTask<String, String, String>
{
ArrayList<XmlPodcastObject> array = new ArrayList<>();
private boolean setToArray;
public AsyncTaskParseJson(boolean setToArray)
{
this.setToArray = setToArray;
}
// All static variables
static final String URL = "http://examiningethics.org/feed/podcast/";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_LINK = "link";
static final String KEY_DESC = "description";
static final String KEY_ENCLOSURE = "enclosure";
static final String KEY_SUMMARY = "itunes:summary";
static final String KEY_DURATION = "itunes:duration";
#Override
protected void onPreExecute(){}
#Override
protected String doInBackground(String... arg0)
{
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++)
{
Element e = (Element) nl.item(i);
XmlPodcastObject obj = new XmlPodcastObject(parser.getValue(e, KEY_TITLE),
parser.getValue(e, KEY_ENCLOSURE), parser.getValue(e, KEY_LINK),
parser.getValue(e, KEY_DESC), parser.getValue(e, KEY_SUMMARY),
parser.getValue(e, KEY_DURATION));
if(developerMode)
{
Log.d("PodcastActivity ONCLICK", "Title: " + obj.getTitle() + " " +
"Podcast Link: " + obj.getPodcastUrl() + " " +
"Story Link: " + obj.getStoryUrl() + " " +
"Duration: " + obj.getTimeOfStream() + " " +
"Content: " + obj.getContent() + " " +
"Summary: " + obj.getSummary());
}
array.add(obj);
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg)
{
app.setPodcastArray(array);
if(setToArray) {
podcastListArrayAdapter = new PodcastListArrayAdapter(getActivity(), R.layout.fragment_podcast_list_item, array);
Listv.setAdapter(podcastListArrayAdapter);
app.setCurrentPodcast(array.get(0));
}
else
{
app.setCurrentPodcast(array.get(0));
home_title.setText(app.getCurrentPodcast().getTitle());
}
try {
if (swipeContainer.isRefreshing()) {
swipeContainer.setRefreshing(false);
}
}catch (NullPointerException e)
{
e.printStackTrace();
}
}
}
}
}
I think, I found an error.
Look into onCreateView. You have if/else there, and only in the first branch home_title is being initialised, not in the second one.
So you have Activity -> ViewPager -> (Page1 - PlaceHolder fragment with home_title initialized) && (Page2 - PlaceHolder fragment without home_title initialized)
You call
mViewPager.setCurrentItem(0, true);
from the second page(fragment). But it knows nothing about home_title! I.e. you're calling not the home_title from the first page, but home_title from the second page (which, again, is not initialized!).
There're multiple possible ways of fixing it.
The simplest for you would be to
Make home_title public (or introduce a getter for it)
Then call it this way:
mViewPager.setCurrentItem(0, true);
mSectionsPagerAdapter.getItem(0).home_title.setText(app.getCurrentPodcast().getTitle());
I.e. explicitly call home_title from the first page.
In this case it'd be over engineering, but you can also think about EventBus as a way to organize cross-fragment collaboration. It'd make it bit cleaner (imho)
And my last 5 cents - you'll make your own life simpler, if you keep different fragments in separate classes. This logic in onCreateView is hardly maintainable.
First, sorry for my low programming skills. I'm trying to write my first Java application for Android (actually I never studied Java but I get along with that most of all).
Anyway, I'm trying to make this app closing on Back button press. This is the code with the [errors] - they're at the page bottom.
package com.ecpay.book_database_test;
import java.io.File;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.KeyEvent;
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.ListView;
import android.widget.TextView;
public class MainActivity extends Activity implements ActionBar.TabListener {
Button newbook_btn;
Button empty_btn;
TextView nobooks_txt;
/**
* 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.v13.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.fragment_main);
// Switch to NewbookActivity through newbook_btn
newbook_btn = (Button)findViewById(R.id.newbook_btn);
newbook_btn.setOnClickListener(
new View.OnClickListener() {
public void onClick(View aView) {
Intent toAnotherActivity = new Intent(aView.getContext(), NewbookActivity.class);
startActivityForResult(toAnotherActivity, 0);
}
}
);
// Check if Database has registered data, to check if nobook_txt has to be shown or not
nobooks_txt = (TextView)findViewById(R.id.textView1);
final File DatabaseFile = new File("/data/data/com.ecpay.book_database_test/databases/mydatabase.db");
if (DatabaseFile.exists()) {
nobooks_txt.setVisibility(View.INVISIBLE);
//nobooks_text.setVisibility(View.VISIBLE);
//nobooks_text.setVisibility(View.GONE);
}
// Empty all the Database through empty_btn
empty_btn = (Button)findViewById(R.id.empty_btn);
empty_btn.setOnClickListener(
new View.OnClickListener() {
public void onClick(View aView) {
DbAdapter db = new DbAdapter(getApplicationContext());
db.open();
DatabaseFile.delete();
db.fetchAllBooks();
db.close();
}
}
);
// Display Database values
ListView BookList = (ListView)findViewById(R.id.listView1);
DbAdapter db = new DbAdapter(getApplicationContext());
db.open();
Cursor cursor = db.fetchAllBooks();
startManagingCursor(cursor);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.book, cursor, new String[]{DbAdapter.KEY_TITLE,DbAdapter.KEY_AUTHOR},new int[]{R.id.booktitle,R.id.bookauthor});
BookList.setAdapter(adapter);
int TitleCol = cursor.getColumnIndex(DbAdapter.KEY_TITLE);
int AuthorCol = cursor.getColumnIndex(DbAdapter.KEY_AUTHOR);
if(cursor.moveToFirst()) {
while (cursor.moveToNext());
}
db.close();
}
#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);
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();
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* 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).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
/**
* 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) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView textView = (TextView) rootView
.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
#Override
[1] public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
[2] finish();
}
[3] return super.onKeyDown(keyCode, event);
}
}
}
Thank you.
You should move your onKeydown out from Fragment since it should work with the Activity. Move
#Override
[1] public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
[2] finish();
}
[3] return super.onKeyDown(keyCode, event);
}
out of the inner-class PlaceholderFragment. (P.S Fragments don't have onKeyDown callback.)
Example:
}
#Override
[1] public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
[2] finish();
}
[3] return super.onKeyDown(keyCode, event);
}
}
I`m trying to use FragmentPagerAdapter but when trying to run it- there is an error:
02-22 22:48:53.328: W/dalvikvm(830): Unable to resolve superclass of
Linfo/androidhive/tabsswipe/SlideActivity$FragmentPagerAdapter; (94)
02-22 22:48:53.328: W/dalvikvm(830): Link of class
'Linfo/androidhive/tabsswipe/SlideActivity$FragmentPagerAdapter;'
failed 02-22 22:48:53.328: E/dalvikvm(830): Could not find class
'info.androidhive.tabsswipe.SlideActivity$FragmentPagerAdapter',
referenced from method
info.androidhive.tabsswipe.SlideActivity.onCreate
my code:
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.SlideFragment;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class SlideActivity extends FragmentActivity {
private static final int NUM_PAGES = 5;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new FragmentPagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_screen_slide, menu);
menu.findItem(R.id.action_previous).setEnabled(mPager.getCurrentItem() > 0);
MenuItem item = menu.add(Menu.NONE, R.id.action_next, Menu.NONE,
(mPager.getCurrentItem() == mPagerAdapter.getCount() - 1)
? R.string.action_finish
: R.string.action_next);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_previous:
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
return true;
case R.id.action_next:
// will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
return true;
}
return super.onOptionsItemSelected(item);
}
public static class FragmentPagerAdapter extends FragmentStatePagerAdapter {
public FragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return SlideFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
already tried to build path, clean and import android.support.v13.app.FragmentPagerAdapter;
There is the SlideFragment class if it could help...
package info.androidhive.tabsswipe;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A fragment representing a single step in a wizard. The fragment shows a dummy title indicating
* the page number, along with some dummy text.
*
* <p>This class is used by the {#link CardFlipActivity} and {#link
* ScreenSlideActivity} samples.</p>
*/
public class SlideFragment extends Fragment {
/**
* The argument key for the page number this fragment represents.
*/
public static final String ARG_PAGE = "page";
/**
* The fragment's page number, which is set to the argument value for {#link #ARG_PAGE}.
*/
private int mPageNumber;
/**
* Factory method for this fragment class. Constructs a new fragment for the given page number.
*/
public static SlideFragment create(int pageNumber) {
SlideFragment fragment = new SlideFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public SlideFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
ViewGroup rootView = (ViewGroup) inflater
.inflate(R.layout.fragment_slide, container, false);
// Set the title view to show the page number.
return rootView;
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return mPageNumber;
}
}
thanks.
You are using the FragmentStatePagerAdapter from v13 instead of v4. Thats the problem. In version 13 the FragmentManager that is used is the one on android 3.5 and higher, In version 4 of the support library the FragmentManager is the supportFragmentManager.
If you switch to v4, it should work by just adding this constructor on your FragmentPagerAdapter class:
/** Constructor of the class */
public FragmentPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
in my application which implements swipe ,, i have been used the fragment ,, but it work on one layout with various title for tabs ,, can i implements it using multiple layouts
this is my code what are the changes must i include in my code to show in every section different layout
package net.justanotherblog.swipeview;
import java.util.Locale;
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.TextView;
public class MainActivity extends FragmentActivity {
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 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);
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.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#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 DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
package net.justanotherblog.swipeview;
import java.util.Locale;
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.TextView;
public class MainActivity extends FragmentActivity {
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 app.
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, FragmentOne.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentTwo.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentThree.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentFour.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentFive.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentSix.class.getName()));
mSectionsPagerAdapter=newSectionsPagerAdapter(super.getSupportFragmentManager(),fragments);
// 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);
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) {
int _pos = position % 6;
return fragments.get(_pos);
}
#Override
public int getCount() {
// Show 3 total pages.
return 6;
}
#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 FragmentOne extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy, container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
like this you can add n number of Fragments in your viewpager.
Hin
You can use an array whit your layout id and when you make right swipe add + 1 or if you make left swpie substract -1.
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
int[] values = new int[] {
R.id.layout1,
R.id.Layout2,
R.id.Layout3 };
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
return false;
}
/**
* left to right swipe
*/
if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//next layout
setContentView(values +1);
/**
* right to left
*/
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
//prev layout
setContentView(values -1);
}
}
} catch (Exception e) {
}
return false;
}
Cheers