App need to open some websites when i touch buttons. There are 2 tabs (2 fragments) with different buttons (1 button = 1 link)
When i click a Button that need to open WebView (to open a link) application crash. I think, mistake is somewhere in AFragment.java
main.java (it's good 99,9%)
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
public static Context appContext;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContext = getApplicationContext();
//ActionBar
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab PTab = actionbar.newTab().setText("One");
ActionBar.Tab DTab = actionbar.newTab().setText("Two");
Fragment OneFragment = new AFragment();
Fragment TwpFragment = new BFragment();
PTab.setTabListener(new MyTabsListener(OneFragment));
DTab.setTabListener(new MyTabsListener(TwoFragment));
actionbar.addTab(PTab);
actionbar.addTab(DTab);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
}
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
//Toast.makeText(MainActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}
AFragment.java:
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
public class AFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
SavedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.afragment, container, false);
}
// On Button Click
public void openIt(View view) {
Intent intent = new Intent(view.getContext(), openPage.class);
startActivity(intent);
}
}
openPage.class:
import android.webkit.WebView;
import android.app.Activity;
import android.os.Bundle;
public class openPage extends Activity {
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://safhkalfsd.com");
}
}
Layouts are fine 99,99%
i put
android:onClick="openIt"
in afragment.xml inside Button
THANK YOU
SOLVED!
I need to put:
// On Button Click
public void openIt(View view) {
Intent intent = new Intent(view.getContext(), openPage.class);
startActivity(intent);
}
in MainActivity, not in 'AFragment'.
Related
this code was working perfectly when i was using navigation drawer activity after making some changes to my project and start using bottom navigation activity it just wont work and give my the error of incompatible types .. i tried every possible answer related to this issue but i get the same error
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.TextView;
public class HomeActivity extends AppCompatActivity {
private TextView mTextMessage;
SearchFragment searchFragment;
private FrameLayout Eframe;
private HomeFragment homeFragment;
private BottomNavigationView eNav;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Eframe = findViewById(R.id.main_frame);
searchFragment = new SearchFragment();
setFragment(searchFragment);
eNav = findViewById(R.id.Nav);
eNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.Search:
> setFragment(searchFragment);
return true;
case R.id.Home:
mTextMessage.setText(R.string.title_dashboard);
return true;
case R.id.Profile:
mTextMessage.setText(R.string.title_notifications);
return true;
case R.id.Notifications:
mTextMessage.setText(R.string.title_notifications);
return true;
case R.id.Menu:
mTextMessage.setText(R.string.title_notifications);
return true;
default:
return false;
}
}
});
}
private void setFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.commit();
}
}
instead of extends AppCompatActivity
write extends Fragment.
I have FAB and TabLayout with viewpager in mainAcitivty. I want to update fragment of viewpager when user provide input by FAB. Trying to send data via Bundle but always Bundle is null while receiving from fragment.
I think my problem is in receiving data. To which fragment method I should use to receive data?
Here is my MainActivity
package com.example.shahalam.rvfabvptl;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText title, description;
FloatingActionButton fab;
ViewPager mPager;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = findViewById(R.id.viewPager);
tabLayout = findViewById(R.id.tabLayout);
fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_box,null);
title = mView.findViewById(R.id.titleDialogBox);
description = mView.findViewById(R.id.descriptionDialogBox);
Button btnOK = mView.findViewById(R.id.btnOk);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
final FragmentOne fragOne = new FragmentOne();
Bundle mBundle = new Bundle();
mBundle.putString("title", title.getText().toString());
mBundle.putString("description", description.getText().toString());
//PASS OVER THE BUNDLE TO OUR FRAGMENT
FragmentOne myFragment = new FragmentOne();
myFragment.setArguments(mBundle);
ft.add(R.id.linearLayoutFragmentOne,fragOne);
ft.commit();
dialog.cancel();
}
});
}
});
ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(mPager);
}
}
And here is my Fragment class:
package com.example.shahalam.rvfabvptl;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class FragmentOne extends Fragment {
public FragmentOne() {
}
RecyclerView fragOneRecyclerView;
List<MyDataModel> myDataModels = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one,container,false);
fragOneRecyclerView = view.findViewById(R.id.fragmentOneRecyclerView);
fragOneRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
final RecyclerViewAdapter adapterFragmentOne = new RecyclerViewAdapter(getContext(),myDataModels);
fragOneRecyclerView.setAdapter(adapterFragmentOne);
Bundle mBundle =getArguments();
String title="if Bundle is null", description="No description";
if (mBundle != null) {
title = this.getArguments().getString("title");
description = this.getArguments().getString("description");
}
MyDataModel mOne4 = new MyDataModel(title,description);
myDataModels.add(mOne4);
adapterFragmentOne.notifyDataSetChanged();
return view;
}
}
You are creating two different objects of your Fragment FragmentOne ,
and setting the bundle to object myFragment and passing another fragment object fragOne in FragmentTransition. which is wrong , use
the below code.
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentOne fragOne = new FragmentOne();
Bundle mBundle = new Bundle();
mBundle.putString("title", title.getText().toString());
mBundle.putString("description", description.getText().toString());
//PASS OVER THE BUNDLE TO OUR FRAGMENT
fragOne.setArguments(mBundle);
ft.add(R.id.linearLayoutFragmentOne,fragOne);
ft.commit();
dialog.cancel();
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
}
});
I'm working with a fragment but its always throwing the error that it cannot start the activity because the fragmentis not attached to the activity,
kindly assist me figure out where I'm messing
Below is my code for the Fragment and Activity:
Fragment
package com.sarham.kabs.fruity;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.support.v7.app.ActionBarDrawerToggle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import adapters.CategoriesListAdapter;
/**
* Created by Kabunyi Wanja on 22/03/2015.
*/
public class CategoriesFragment extends ListFragment {
private ListView categoriesListView;
private String[] categoriesArray = getResources().getStringArray(R.array.drawer_list);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.categories_fragment, container, false);
categoriesListView = (ListView)v.findViewById(android.R.id.list);
//setCategoriesListAdapter();
//Log.d("ADAPTER: ", "Adapter has been set for listview");
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setCategoriesListAdapter();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
//set adapter to categoriesListView
public void setCategoriesListAdapter(){
categoriesListView.setAdapter(new CategoriesListAdapter(getActivity(), categoriesArray));
}
}
Activity
package com.sarham.kabs.fruity;
import android.content.res.Configuration;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener{
private DrawerLayout drawerLayout;
private ListView listView;
private String[] planets;
private ActionBarDrawerToggle drawerListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
listView = (ListView)findViewById(R.id.drawerListView);
planets = getResources().getStringArray(R.array.planets);
listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, planets));
listView.setOnItemClickListener(this);
drawerListener = new ActionBarDrawerToggle(this, drawerLayout,R.string.drawer_open, R.string.drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
Toast.makeText(MainActivity.this,"Drawer Open", Toast.LENGTH_LONG).show();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Toast.makeText(MainActivity.this, "Drawer Closed", Toast.LENGTH_LONG).show();
}
};
drawerLayout.setDrawerListener(drawerListener);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CategoriesFragment categories = new CategoriesFragment();
addFragment(R.id.drawerLayout, categories, "CATEGORIES");
}
#Override
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
drawerListener.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerListener.onConfigurationChanged(newConfig);
}
#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.
if(drawerListener.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, planets[position]+" Was selected", Toast.LENGTH_SHORT).show();
selectItem(position);
switch (position){
case 0:
CategoriesFragment categories = new CategoriesFragment();
addFragment(R.id.drawerLayout, categories, "CATEGORIES");
break;
case 1:
Toast.makeText(this, "Settings was selected", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(this, "Exit was selected", Toast.LENGTH_SHORT).show();
finish();
break;
default:
}
}
public void selectItem(int position){
listView.setItemChecked(position, true);
setTitle(planets[position]);
}
//set ActionBar title
public void setTitle(String title){
getSupportActionBar().setTitle(title);
}
//call this method to add a fragment
public void addFragment(int containerViewId, Fragment fragment, String tag){
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(containerViewId, fragment, tag);
transaction.commit();
}
}
Below is the LogCat ouput:
Caused by: java.lang.IllegalStateException: Fragment CategoriesFragment{41545e80} not attached to Activity
at android.support.v4.app.Fragment.getResources(Fragment.java:619)
at com.sarham.kabs.fruity.CategoriesFragment.<init>(CategoriesFragment.java:21)
at com.sarham.kabs.fruity.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5020)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.access$600(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1300)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
On carefull analysis of the Fragment lifecycle, Its not possible to carry out operations like fetching of string resources using the getResources().getStringArray(...) as I was doing, this has to be done within the method onActivityCreated(...)
I want to detect when a particular fragment of three fragments I have set up with a ViewPager comes on to screen. I have 3 fragments in the viewpager and have set up the viewpager with
mViewPager.setOffscreenPageLimit(2);
so all three fragments are constructed at once (since it stores 2 on each side). I checked that Fragment.onResume() is called just once and not when each fragment comes to the foreground. Is there another callback to ensure I can catch this event and send some analytics signal for it?
Thanks
You can use the ViewPager.setOnPageChangeListener() to set a ViewPager.OnPageChangeListener().
Use the listener for the selected page based on its position in the PagerAdapter.
Here's my sample app:
package net.ynotapps.testviewpagerfragment;
import android.support.annotation.Nullable;
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.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
#InjectView(R.id.pager)
ViewPager pager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
CustomPagerAdapter adapter = new CustomPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// Put Code here //
// Example code //
if (position == 2) {
Toast.makeText(MainActivity.this, "Found Position 2 fragment", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public static class CustomPagerAdapter extends FragmentPagerAdapter {
public CustomPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
CustomFragment fragment = new CustomFragment();
Bundle bundle = new Bundle();
bundle.putString("display_text", String.format("Fragment %d is here.", position));
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return 5;
}
}
public static class CustomFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
TextView tv = new TextView(getActivity());
tv.setText(getArguments().getString("display_text"));
return tv;
}
}
}
ViewPager source code:
// Dispatch the change to any listeners
if (mAdapterChangeListeners != null && !mAdapterChangeListeners.isEmpty()) {
for (int i = 0, count = mAdapterChangeListeners.size(); i < count; i++) {
mAdapterChangeListeners.get(i).onAdapterChanged(this, oldAdapter, adapter);
}
}
So, you can use the ViewPager.addOnAdapterChangeListener to listen the callback.