page viewer auto incrementing on swipe - android-fragments

I have videos link in an array, and I am using a vertical page viewer and Fragment instance to swipe between videos vertically. The first and the last fragments are working fine, but when I swipe or click on the first video that is index 0 of videos array, then the video of index 1 is playing and pausing, but the action is not happening for index 0. Please help me with a solution, I have been trying for past 2 days, and I am new to android studio.
package com.example.final_view_pager;
import android.annotation.TargetApi;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import java.util.ArrayList;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
public class MainActivity extends AppCompatActivity {
MyAdapter mAdapter;
VerticalViewPager mPager;
public static VideoView videoView;
private String videosArray[] = {
"android.resource://com.example.final_view_pager/" + R.raw.four,
"android.resource://com.example.final_view_pager/" + R.raw.six,
"android.resource://com.example.final_view_pager/" + R.raw.video,
"android.resource://com.example.final_view_pager/" + R.raw.video1,
"android.resource://com.example.final_view_pager/" + R.raw.video2,
"android.resource://com.example.final_view_pager/" + R.raw.video3,
"android.resource://com.example.final_view_pager/" + R.raw.video5,
"android.resource://com.example.final_view_pager/" + R.raw.video6
};
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyAdapter(getSupportFragmentManager(), videosArray);
mPager = findViewById(R.id.viewpager);
mPager.setAdapter(mAdapter);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Toast.makeText(getApplicationContext(), " current position is " + position, Toast.LENGTH_SHORT).show();
//Log.i("page", "on page scrolled");
}
#Override
public void onPageSelected(int position) {
Integer current_item = mPager.getCurrentItem();
Log.i("page", " cure pos " + current_item);
FragmentInstance.newInstance(position, videosArray[position]);
Log.i("page", "on page selected position is " + position);
}
#Override
public void onPageScrollStateChanged(int state) {
//Log.i("page", "on page scroll state changed");
}
});
}
public static class MyAdapter extends FragmentPagerAdapter {
String videosArray[];
//private long baseId = 0;
public MyAdapter(FragmentManager fm, String[] videosArr) {
super(fm);
videosArray = videosArr;
}
#Override
public int getCount() {
return videosArray.length;
//return 3;
//return NUMBER_OF_PAGES;
}
public void notifyChangeInPosition(int n) {
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
#Override
public Fragment getItem(int position) {
}
}
public static class FragmentInstance extends Fragment {
private static final String videourlname = "video_url";
private static final String indexs = "position";
String videourl;
Integer position;
static FragmentInstance newInstance(Integer position, String videourl) {
FragmentInstance f = new FragmentInstance();
Bundle args = new Bundle();
args.putString(videourlname, videourl);
args.putInt(indexs, position);
f.setArguments(args);
return f;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_one, container, false);
videoView = v.findViewById(R.id.video_view);
Uri uri = Uri.parse(videourl);
Toast.makeText(getContext(), "url is " + videourl, Toast.LENGTH_SHORT);
videoView.setVideoURI(uri);
Log.i("page", "playing position is " + position);
if (position == 1) {
Log.i("page", "position is different" + position);
videoView.start();
}
videoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("page", "clicked position is " + position);
if (videoView.isPlaying()) {
Log.i("page", "playing check position is" + position);
Toast.makeText(getContext(), " clicked position is " + position, Toast.LENGTH_SHORT);
videoView.pause();
} else {
Log.i("page", "playing else position is" + position);
Toast.makeText(getContext(), " clicked position is " + position, Toast.LENGTH_SHORT);
videoView.start();
}
}
});
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
videourl = getArguments() != null ? getArguments().getString(videourlname) : "Null";
position = getArguments() != null ? getArguments().getInt(indexs) : 0;
}
}
}

Related

SharedPreferences within a fragment

Once the user selects an item from a list in another fragment it brings you to this fragment. And I'm having issues trying to save the users rating that was selected. when the user goes back it should be the same rating that was previously selected.
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.Arrays;
public class infoFragment extends Fragment {
TextView degrees;
ImageView image;
String stringtext;
String [] hold;
private RatingBar rating;
SharedPreferences wmbPreference1;
SharedPreferences.Editor editor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.info_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
image = (ImageView) view.findViewById(R.id.imageView);
why can i not use "this"
rating =((RatingBar) view.findViewById(R.id.ratingBar)).setOnRatingBarChangeListener(this);
wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);
degrees =(TextView)view.findViewById(R.id.textView);
}
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
final int numStars = ratingBar.getNumStars();
editor = wmbPreference1.edit();
editor.putInt("numStars", numStars);
editor.commit();
int ratings = wmbPreference1.getInt("numStars", 0);
}
public void setText(final String string) {
Character[] hold;
if(string == "apple"){
String[] word = { " A \n", "B\n" };
degrees.setText(Arrays.toString(word).replaceAll("\\[|\\]", ""));;
image.setImageResource(R.drawable.APPLE);
}
Should I call onRatingChanged within the conditional statement for it to save?
if(string == "orange"){
String[] word = { " AA\n", "AB\n" };
degrees.setText(Arrays.toString(word).replaceAll("\\[|\\]", ""));;
image.setImageResource(R.drawable.bruce);
}
}
public void sentText(){
new MyTask().execute();
}
private class MyTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... strings) {
Bundle b = getArguments();
stringtext = b.getString("text");
return null;
}
protected void onPostExecute(String result){setText(stringtext);
}
}
}
Your Fragment should implement OnRatingBarChangeListener:
public class infoFragment extends Fragment implements OnRatingBarChangeListener
The other thing is that setOnRatingChangeListener does not return a value, so you can't assign the return value to rating as you did.
You should do:
rating = (RatingBar) view.findViewById(R.id.ratingBar);
rating.setOnRatingBarChangeListener(this);

Using Fragments In MainActivity For NavigationDrawerFragment in Android Studio

I have been trying to Design an App That has PANEL like Google Drawers.
• MainActivity
package skynet.com.testnavigationpanel;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
Intent i=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
// populate the navigation drawer
mNavigationDrawerFragment.setUserData("Falcon Shield", "We Protect Your Device!", BitmapFactory.decodeResource(getResources(), R.drawable.shieldavatar));
}
public void login_signup(View v)
{
switch(v.getId())
{
case R.id.log_in:
i=new Intent(this,Login.class);
startActivityForResult(i, 500);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
break;
case R.id.sign_up:
i=new Intent(this,Signup.class);
startActivityForResult(i, 500);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
#Override
public void onNavigationDrawerItemSelected(int position)
{
// update the main content by replacing fragments
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
public void onSectionAttached(int anInt) {
}
}
•NavigationDrawerFragment
package skynet.com.testnavigationpanel;
import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mActionBarDrawerToggle;
private DrawerLayout mDrawerLayout;
private RecyclerView mDrawerList;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition);
return view;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mActionBarDrawerToggle;
}
public DrawerLayout getDrawerLayout() {
return mDrawerLayout;
}
#Override
public void onNavigationDrawerItemSelected(int position) {
selectItem(position);
}
public List getMenu() {
List items= new ArrayList<>();
items.add(new NavigationItem(getString(R.string.homeFrag),getResources().getDrawable(R.drawable.ic_home)));
items.add(new NavigationItem(getString(R.string.loginFrag),getResources().getDrawable(R.drawable.ic_login)));
items.add(new NavigationItem(getString(R.string.signupFrag),getResources().getDrawable(R.drawable.ic_signup)));
items.add(new NavigationItem(getString(R.string.settingFrag),getResources().getDrawable(R.drawable.ic_setting )));
items.add(new NavigationItem(getString(R.string.shareFrag),getResources().getDrawable(R.drawable.ic_share )));
items.add(new NavigationItem(getString(R.string.aboutFrag),getResources().getDrawable(R.drawable.ic_about )));
return items;
}
public void showBackButton(){
if(getActivity()instanceof ActionBarActivity){
((ActionBarActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
* #param toolbar The Toolbar of the activity.
*/
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) {
mFragmentContainerView = (View) getActivity().findViewById(fragmentId).getParent();
mDrawerLayout = drawerLayout;
mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.myPrimaryDarkColor));
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) return;
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) return;
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public void openDrawer() {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer() {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
public void setUserData(String user, String email, Bitmap avatar) {
ImageView avatarContainer = (ImageView) mFragmentContainerView.findViewById(R.id.imgAvatar);
((TextView) mFragmentContainerView.findViewById(R.id.txtUserEmail)).setText(email);
((TextView) mFragmentContainerView.findViewById(R.id.txtUsername)).setText(user);
avatarContainer.setImageDrawable(new RoundImage(avatar));
}
public View getGoogleDrawer() {
return mFragmentContainerView.findViewById(R.id.googleDrawer);
}
public static class RoundImage extends Drawable {
private final Bitmap mBitmap;
private final Paint mPaint;
private final RectF mRectF;
private final int mBitmapWidth;
private final int mBitmapHeight;
public RoundImage(Bitmap bitmap) {
mBitmap = bitmap;
mRectF = new RectF();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
final BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint.setShader(shader);
mBitmapWidth = mBitmap.getWidth();
mBitmapHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
canvas.drawOval(mRectF, mPaint);
}
#Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRectF.set(bounds);
}
#Override
public void setAlpha(int alpha) {
if (mPaint.getAlpha() != alpha) {
mPaint.setAlpha(alpha);
invalidateSelf();
}
}
#Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
#Override
public int getIntrinsicWidth() {
return mBitmapWidth;
}
#Override
public int getIntrinsicHeight() {
return mBitmapHeight;
}
public void setAntiAlias(boolean aa) {
mPaint.setAntiAlias(aa);
invalidateSelf();
}
#Override
public void setFilterBitmap(boolean filter) {
mPaint.setFilterBitmap(filter);
invalidateSelf();
}
#Override
public void setDither(boolean dither) {
mPaint.setDither(dither);
invalidateSelf();
}
public Bitmap getBitmap() {
return mBitmap;
}
}
}
Kindly Guide me in Mentioning the Right code into Below Method of MainActivity.
onNavigationDrawerItemSelect(int position)
{
//codes for fragments That i dont Know how to write
}
My Fragment Class(Please Check the Code if its Right or needs to be changed)
package skynet.com.testnavigationpanel;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Evan on 28-Dec-15.
*/
public class HomeFragment extends Fragment {
public static HomeFragment newInstance(){
HomeFragment fragment=new HomeFragment();
return fragment;
}
public HomeFragment()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.activity_main,container,false);
return rootView;
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
((MainActivity)activity).onSectionAttached(1);
}
}
Same Goes with my Other fragments for login, signup, about, share, etc..with Relevant Changes in Layout id and Names.
Devs, Kindly Help ! Thanks

android change webview when change a tabstrip

i wonder if someone can help me get it to work, i want to change the webview url every time i change a tab in the tabstrip
i am a new developer so any kind of help will be great.
the main code of the pager and tabs
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.TransitionDrawable;
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.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.astuetz.PagerSlidingTabStrip;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
#InjectView(R.id.toolbar)
Toolbar toolbar;
#InjectView(R.id.tabs)
PagerSlidingTabStrip tabs;
#InjectView(R.id.pager)
ViewPager pager;
private MyPagerAdapter adapter;
private Drawable oldBackground = null;
private int currentColor;
private SystemBarTintManager mTintManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
setSupportActionBar(toolbar);
// create our manager instance after the content view is set
mTintManager = new SystemBarTintManager(this);
// enable status bar tint
mTintManager.setStatusBarTintEnabled(true);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
pager.setCurrentItem(1);
changeColor(getResources().getColor(R.color.green));
tabs.setOnTabReselectedListener(new PagerSlidingTabStrip.OnTabReselectedListener() {
#Override
public void onTabReselected(int position) {
Toast.makeText(MainActivity.this, "Tab reselected: " + position, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_contact:
QuickContactFragment.newInstance().show(getSupportFragmentManager(), "QuickContactFragment");
return true;
}
return super.onOptionsItemSelected(item);
}
private void changeColor(int newColor) {
tabs.setBackgroundColor(newColor);
mTintManager.setTintColor(newColor);
// change ActionBar color just if an ActionBar is available
Drawable colorDrawable = new ColorDrawable(newColor);
Drawable bottomDrawable = new ColorDrawable(getResources().getColor(android.R.color.transparent));
LayerDrawable ld = new LayerDrawable(new Drawable[]{colorDrawable, bottomDrawable});
if (oldBackground == null) {
getSupportActionBar().setBackgroundDrawable(ld);
} else {
TransitionDrawable td = new TransitionDrawable(new Drawable[]{oldBackground, ld});
getSupportActionBar().setBackgroundDrawable(td);
td.startTransition(200);
}
oldBackground = ld;
currentColor = newColor;
}
public void onColorClicked(View v) {
int color = Color.parseColor(v.getTag().toString());
changeColor(color);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentColor", currentColor);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentColor = savedInstanceState.getInt("currentColor");
changeColor(currentColor);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = {"Categories", "Home", "Top Paid", "Top Free", "Top Grossing", "Top New Paid",
"Top New Free", "Trending"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
return SuperAwesomeCardFragment.newInstance(position);
}
}
}
and the second code of the textview where i want to change it to webview.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class SuperAwesomeCardFragment extends Fragment {
private static final String ARG_POSITION = "position";
#InjectView(R.id.textView)
TextView textView;
private int position;
public static SuperAwesomeCardFragment newInstance(int position) {
SuperAwesomeCardFragment f = new SuperAwesomeCardFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card,container,false);
ButterKnife.inject(this, rootView);
ViewCompat.setElevation(rootView,50);
textView.setText("CARD "+position);
return rootView;
}
}
that's all for now, the layouts files are less important, i will deal with it later.
You should setOnPageChangeListener and use webview.loadUrl(url1);
tabsStrip.setOnPageChangeListener(new OnPageChangeListener() {
// This method will be invoked when a new page becomes selected.
#Override
public void onPageSelected(int position) {
switch(position)
{
case 0:
webview.loadUrl(url1);
break;
case 1:
webview.loadUrl(url2);
break;
case 2:
webview.loadUrl(url3);
break;
}
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Code goes here
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
// Code goes here
}
});

Android Flipboard App animation

I'm Implementing Flipboard Animation in my activity pageIndicatorActivity its showing an error i.e The method Page(NoteViewAdapter) in the type FlipViewController is not applicable for the arguments
(PageIndicatorActivity.NoteViewAdapter)
this is the error I'm facing
here is my code
package com.horizontalscrollviewwithpageindicator;
import java.util.ArrayList;
import com.aphidmobile.flip.FlipViewController;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class PageIndicatorActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageArra);
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
ArrayList<String> notes = new ArrayList<String>();
notes.add("Come");
notes.add("On");
notes.add("Flip");
notes.add("Me");
//You can also use FlipViewController.VERTICAL
FlipViewController flipView = new FlipViewController(this, FlipViewController.HORIZONTAL);
//We're creating a NoteViewAdapter instance, by passing in the current context and the
//values to display after each flip
flipView.Page(new NoteViewAdapter(this, notes));
setContentView(flipView);
}
public abstract class NoteViewAdapter extends BaseAdapter {
private LayoutInflater inflater;
private ArrayList<String> notes;
public NoteViewAdapter(Context currentContext, ArrayList<String> allNotes) {
inflater = LayoutInflater.from(currentContext);
notes = allNotes;
}
#Override
public int getCount() {
return notes.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View layout = convertView;
if (convertView == null) {
layout = inflater.inflate(R.layout.activity_main, null);
}
//Get's value from our ArrayList by the position
String note = notes.get(position);
TextView tView = (TextView) layout.findViewById(R.id.note);
tView.setText(note);
return layout;
}
}
private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
R.drawable.antartica3, R.drawable.antartica4,
R.drawable.antartica5, R.drawable.antartica6,
R.drawable.antartica7, R.drawable.antartica8 };
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Android: ActionBar, TabListener and support.v4.Fragment

I'm building an app with MainActivity which extends FragmentActivity and has an ActionBar with three tabs. At each tab I would like to attach a ParentFragment which should control the swipe among internal pages. The result should be that pressing the tabs the user should change from the different instances of the ParentFragment and swiping he should change among the TextViewFragments inside each ParentFragment.
Now I can perfectly switch among the three tabs, but the problem is that the ParentFragment is not correctly shown, it seems it's not even created because I can't even see the onCreate(), onCreateView() and onViewCreated() functions in the LogCat view.
I think that the problem resides in the custom TabListener class and its functions but I can't really understand what the problem is. I tried to search on many sites and I've looked into a lot of examples but none of them was related to the same situation.
What do I miss or what am I doing wrong here?
This is my MainActivity:
import java.util.Random;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
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;
import android.widget.Toast;
import com.viewpagerindicator.PageIndicator;
public class MainActivity extends FragmentActivity {
MyAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
private View mCustomView;
private static final Random RANDOM = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
ActionBar.LayoutParams params = new ActionBar.LayoutParams(
ActionBar.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.addTab(actionBar
.newTab()
.setIcon(getIcon(0, true))
.setTabListener(
new TabListener<ParentFragment>(this, "home",
ParentFragment.class)));
actionBar.addTab(actionBar
.newTab()
.setIcon(getIcon(1, false))
.setTabListener(
new TabListener<ParentFragment>(this, "apps",
ParentFragment.class)));
actionBar.addTab(actionBar
.newTab()
.setIcon(getIcon(2, false))
.setTabListener(
new TabListener<ParentFragment>(this, "settings",
ParentFragment.class)));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
}
public static class TabListener<T extends Fragment> implements
ActionBar.TabListener {
private Fragment mFragment;
private final FragmentActivity mActivity;
private final String mTag;
private final Class<T> mClass;
private final Bundle mArgs;
private FragmentTransaction fft;
public static final String TAG = TabListener.class.getSimpleName();
public TabListener(FragmentActivity activity, String tag, Class<T> clz) {
this(activity, tag, clz, null);
}
public TabListener(FragmentActivity activity, String tag, Class<T> clz,
Bundle args) {
mActivity = activity;
mTag = tag;
mClass = clz;
mArgs = args;
mFragment = mActivity.getSupportFragmentManager()
.findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
fft = mActivity.getSupportFragmentManager().beginTransaction();
fft.detach(mFragment);
fft.commit();
}
}
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
System.out.println(TAG + (" - ") + " -> mTag "
+ mTag + " selected!");
fft = mActivity.getSupportFragmentManager().beginTransaction();
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName());
fft.add(android.R.id.content, mFragment, mTag);
} else {
System.out.println(TAG + (" - ") + " -> Fragment con mTag = " + mTag
+ " trovato con tag!");
fft.attach(mFragment);
fft.commit();
}
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
mFragment = mActivity.getSupportFragmentManager()
.findFragmentByTag(mTag);
System.out.println(TAG + (" - ") + " -> mTag "
+ mTag + " unselected!");
if (mFragment != null && !mFragment.isDetached()) {
fft = mActivity.getSupportFragmentManager().beginTransaction();
fft.detach(mFragment);
fft.commit();
}
}
}
public Drawable getIcon(int tabPosition, boolean selected) {
switch (tabPosition) {
case 0:
return getResources().getDrawable(R.drawable.actionbar_home);
case 1:
return getResources().getDrawable(R.drawable.actionbar_apps);
case 2:
return getResources().getDrawable(R.drawable.actionbar_settings);
}
return null;
}
}
And this is my ParentFragment which exteds now the android.support.v4.app.Fragment class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.viewpagerindicator.IconPageIndicator;
import com.viewpagerindicator.PageIndicator;
public class ParentFragment extends Fragment {
public static final String TAG = ParentFragment.class.getSimpleName();
MyAdapter fragmentAdapter;
ViewPager mPager;
PageIndicator mIndicator;
public static ParentFragment newInstance() {
System.out.println(TAG + " - newInstance()");
System.out.println(TAG + " - " + methodName());
ParentFragment fragment = new ParentFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
System.out.println(TAG + " - onCreate()");
System.out.println(TAG + " - " + methodName());
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println(TAG + " - onCreateView()");
System.out.println(TAG + " - " + methodName());
fragmentAdapter = new MyAdapter(getFragmentManager());
View view = inflater.inflate(R.layout.simple_icons, container, false);
mPager = (ViewPager) view.findViewById(R.id.pager);
mPager.setAdapter(fragmentAdapter);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
System.out.println(TAG + " - onViewCreated()" );
System.out.println(TAG + " - " + methodName());
super.onViewCreated(view, savedInstanceState);
mIndicator = (IconPageIndicator) getActivity().findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
}
This is the MyAdapter class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import com.viewpagerindicator.IconPagerAdapter;
public class MyAdapter extends PagerAdapter {
FragmentManager myFragmentMgr;
private FragmentTransaction mCurTransaction;
protected static final String[] CONTENT = new String[] { "This", "Is", "A", "Test", };
protected static final int[] ICONS = new int[] {
R.drawable.icon_page_indicator,
R.drawable.icon_page_indicator,
R.drawable.icon_page_indicator,
R.drawable.perm_group_calendar,
R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms,
R.drawable.perm_group_location
};
private int mCount = CONTENT.length;
public MyAdapter(FragmentManager fm) {
super();
myFragmentMgr = fm;
}
#Override
public int getCount() {
return 3;
}
#Override
public Object instantiateItem(ViewGroup viewGroup, int position) {
ParentFragment fragment = ParentFragment.newInstance();
return fragment;
}
#Override
public void destroyItem(ViewGroup viewGroup, int position, Object obj) {
if (mCurTransaction == null) {
mCurTransaction = myFragmentMgr.beginTransaction();
}
mCurTransaction.detach((Fragment)obj);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return false;
}
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putInt(TextViewFragment.POSITION_KEY, position);
return TextViewFragment.newInstance(args);
}
#Override
public CharSequence getPageTitle(int position) {
return "Fragment # " + position;
}
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
and the last the TextViewFragment class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class TextViewFragment extends Fragment {
public static final String POSITION_KEY = "POSITION";
public static final String TITLE_KEY = "TITLE";
public static TextViewFragment newInstance(Bundle args) {
TextViewFragment fragment = new TextViewFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView textview = (TextView) view.findViewById(R.id.textViewPosition);
final int position;
if (getArguments() != null) {
position = getArguments().getInt(POSITION_KEY);
textview.setText(Integer.toString(position));
} else {
position = 0;
textview.setText("Child Fragment");
}
textview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Clicked Position: " + position,
Toast.LENGTH_LONG).show();
}
});
}
}
----- EDIT: SOLUTION -----
I cannot answer my own question due to "low reputation" but I share anyway the solution, in order to help someone else and hopefully to recover some votes.
I finally found the way to make things work for me, I hope this could be helpful for anyone else experiencing the same problem.
As I suspected, the problem was in TabListener. My problem was solved changing that part with this code:
public static class TabListener<T extends Fragment> implements
ActionBar.TabListener {
private Fragment mFragment;
private final FragmentActivity mActivity;
private final String mTag;
private final Class<T> mClass;
private final Bundle mArgs;
private FragmentTransaction fft;
public TabListener(FragmentActivity activity, String tag, Class<T> clz) {
this(activity, tag, clz, null);
}
public TabListener(FragmentActivity activity, String tag, Class<T> clz,
Bundle args) {
mActivity = activity;
mTag = tag;
mClass = clz;
mArgs = args;
System.out.println(TAG + " - " + methodName() + " - Constructor of TabListener -> mTag = "
+ mTag);
// Check to see if we already have a fragment for this tab, probably
// from a previously saved state. If so, deactivate it, because our
// initial state is that a tab isn't shown.
mFragment = mActivity.getSupportFragmentManager()
.findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
fft = mActivity.getSupportFragmentManager().beginTransaction();
fft.detach(mFragment);
fft.commit();
mActivity.getSupportFragmentManager()
.executePendingTransactions();
}
}
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
Fragment tmp = mActivity.getSupportFragmentManager()
.findFragmentByTag(mTag);
fft = mActivity.getSupportFragmentManager().beginTransaction();
if (mFragment == null) {
System.out.println(TAG + " - " + methodName() + " - add mFragment " + mTag);
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
fft.add(android.R.id.content, mFragment, mTag);
fft.commit();
mActivity.getSupportFragmentManager()
.executePendingTransactions();
} else {
System.out.println(TAG + " - " + methodName() + " - attach mFragment " + mTag);
// If it exists, simply attach it in order to show it
fft.attach(mFragment);
fft.commit();
mActivity.getSupportFragmentManager()
.executePendingTransactions();
}
}
#Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
System.out.println(TAG + " - " + methodName() + " - mFragment " + mTag);
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
mFragment = mActivity.getSupportFragmentManager()
.findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
System.out.println(TAG + " - " + methodName() + " - detach mFragment " + mTag);
fft = mActivity.getSupportFragmentManager().beginTransaction();
fft.detach(mFragment);
fft.commit();
mActivity.getSupportFragmentManager()
.executePendingTransactions();
}
}
public static final String TAG = TabListener.class.getSimpleName();
private static final int CLIENT_CODE_STACK_INDEX;
static {
// Finds out the index of "this code" in the returned stack trace -
// funny but it differs in JDK 1.5 and 1.6
int i = 0;
for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
i++;
if (ste.getClassName().equals(TabListener.class.getName())) {
break;
}
}
CLIENT_CODE_STACK_INDEX = i;
}
public static String methodName() {
if (Thread.currentThread().getStackTrace().length < CLIENT_CODE_STACK_INDEX)
return Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX]
.getMethodName() + "()";
else
return new String(
"methodName() - stackTrace index is out of bound");
}
}
The fundamental difference was the addition after each commit() of the following line:
mActivity.getSupportFragmentManager().executePendingTransactions();
This problem was really poorly documented and probably happens only in particular conditions, but I hope this solution saves some time to anyone else having the same issues!
Thanks for the answer, I had this exact same problem with the support library where the fragments will be overlaid ontop of each other when i tried to switch between tabs. There were a couple of unused variables in the solution so I cleaned it up a bit:
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private final FragmentActivity mActivity;
private final String mTag;
private final Class<T> mClass;
private FragmentTransaction fft;
public TabListener(FragmentActivity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
// Check to see if we already have a fragment for this tab, probably
// from a previously saved state. If so, deactivate it, because our
// initial state is that a tab isn't shown.
mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
fft = mActivity.getSupportFragmentManager().beginTransaction();
fft.detach(mFragment);
fft.commit();
mActivity.getSupportFragmentManager()
.executePendingTransactions();
}
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
fft = mActivity.getSupportFragmentManager().beginTransaction();
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(R.id.content_view, mFragment, mTag);
//fft.add(android.R.id.content, mFragment, mTag);
fft.commit();
mActivity.getSupportFragmentManager().executePendingTransactions();
} else {
// If it exists, simply attach it in order to show it
fft.attach(mFragment);
fft.commit();
mActivity.getSupportFragmentManager().executePendingTransactions();
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
if (mFragment != null && !mFragment.isDetached()) {
fft = mActivity.getSupportFragmentManager().beginTransaction();
fft.detach(mFragment);
fft.commit();
mActivity.getSupportFragmentManager().executePendingTransactions();
}
}
}

Resources