I have an application which which uses swipe views. I used the template provided by android studio to create the swipe views. The template provided by android studio provides 3 fragments to swipe between which are working fine, I can swipe back and fourth between these no problem.
The problem I am having is creating a 4th fragment. I have created the Java file, the XML and have updated my MainActivity to account for the 4th tab. The 4th tab is showing in the menu and I can swipe to the 4th tab. But, when I try to swipe back to any of the other tabs from the 4th tab the app crashes.
The error I am getting in the Android Monitor is:
12-07 14:08:11.951 2586-2586/com.example.application.placepicker
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.application.placepicker, PID: 2586
android.view.InflateException: Binary XML file line #11: Binary XML file
line #11: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #11: Error
inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #11:
Duplicate id 0x7f0d00a1, tag null, or parent id 0xffffffff with another
fragment for com.google.android.gms.maps.SupportStreetViewPanoramaFragment
at
android.support.v4.app.FragmentManagerImpl.onCreateView
(FragmentManager.java:3447)
at
android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView
(LayoutInflaterCompatHC.java:47)
at android.view.LayoutInflater$FactoryMerger.onCreateView
(LayoutInflater.java:189)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:769)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at com.example.application.placepicker.Tab2.onCreateView(Tab2.java:29)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at android.support.v4.app.FragmentManagerImpl.moveToState
(FragmentManager.java:1299)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState
(FragmentManager.java:1528)
at android.support.v4.app.BackStackRecord.executeOps
(BackStackRecord.java:753)
at android.support.v4.app.FragmentManagerImpl.executeOps
(FragmentManager.java:2363)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether
(FragmentManager.java:2149)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps
(FragmentManager.java:2103)
at android.support.v4.app.FragmentManagerImpl.execSingleAction
(FragmentManager.java:1984)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss
(BackStackRecord.java:626)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate
(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1268)
at android.support.v4.view.ViewPager.setCurrentItemInternal
(ViewPager.java:668)
at android.support.v4.view.ViewPager.setCurrentItemInternal
(ViewPager.java:630)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:611)
at android.support.design.widget.TabLayout
$ViewPagerOnTabSelectedListener.onTabSelected(TabLayout.java:2191)
at android.support.design.widget.TabLayout.dispatchTabSelected
(TabLayout.java:1164)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1157)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1127)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1426)
at android.support.design.widget.TabLayout$TabView.performClick
(TabLayout.java:1536)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit
$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
My MainActivity is:
public class TabbedActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
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);
}
#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_tabbed, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1 tab1 = new Tab1();
return tab1;
case 1:
Tab2 tab2 = new Tab2();
return tab2;
case 2:
Tab3 tab3 = new Tab3();
return tab3;
case 3:
Tab4 tab4 = new Tab4();
return tab4;
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Places";
case 1:
return "Street View";
case 2:
return "Steps";
case 3:
return "Weather";
}
return null;
}
}
}
My Tab4.java is:
public class Tab4 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab4, container, false);
return rootView;
}
}
Anything else you need to know to find a solution please let me know
Thanks
Edit:
This is the XML file of tab4
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.application.placepicker.TabbedActivity$PlaceholderFragment">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Weather Fragment" />
</RelativeLayout>
This is the XML of Tab1 which is working fine:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.application.placepicker.TabbedActivity$PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button_places"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:textColor="#android:color/white"
android:text="Launch place picker"
android:width="350dp"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/section_label" />
<TextView
android:id="#+id/tvPlace"
android:layout_marginTop="64dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAlignment="center"
android:textColor="#3F51B5"
android:textSize="24dp"
android:layout_below="#+id/textViewUserEmail"
android:layout_alignParentStart="true" />
</RelativeLayout>
Related
I have a problem I don't know how to navigate from one fragment to another, practically the first fragment has a listview and by clicking on a value in the list I would like to open another fragment, I paste the various codes, Help me please
Main Activity
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView btnNav=findViewById(R.id.navigationBottom);
btnNav.setOnNavigationItemSelectedListener(navListner);
//Salve lo stato del fragment
if(savedInstanceState==null){
//Setting Home Fragment as main fragment
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new PlaceFragment()).commit();
}
}
//Listner Nav Bar
private BottomNavigationView.OnNavigationItemSelectedListener navListner = new
BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment selectedFragment=null;
switch (item.getItemId()){
case R.id.place:
selectedFragment=new PlaceFragment();
break;
case R.id.commercial:
selectedFragment=new CommercialFragment();
break;
case R.id.emergency:
selectedFragment=new EmergencyFragment();
break;
}
//Begin Transaction
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container,selectedFragment).commit();
return true;
}
};
}
Main Layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/navigationBottom"/>
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/navigationBottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/menu"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:foregroundGravity="center"/>
Fragment Activity
public class PlaceFragment extends Fragment {
public PlaceFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_place, container, false);
}
}
Fragment layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PlaceFragment">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listplace"
android:entries="#array/place_visit"/>
The crash is when i switch the page from 2 to 0 or 1.
And when i Comment the auto Complete Fragment at activity_maps.xml
Please help me.
--------- beginning of crash
12-04 01:31:01.005 12693-12693/com.handsomelee.gotroute E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.handsomelee.gotroute, PID: 12693
android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #10: Duplicate id 0x7f0f00e4, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.location.places.ui.PlaceAutocompleteFragment
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2315)
at android.app.FragmentController.onCreateView(FragmentController.java:98)
at android.app.Activity.onCreateView(Activity.java:5901)
at android.support.v4.app.BaseFragmentActivityApi14.onCreateView(BaseFragmentActivityApi14.java:41)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:67)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at com.handsomelee.gotroute.Services.GoogleMapSystem.onCreateView(GoogleMapSystem.java:41)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2261)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1750)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:792)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2590)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2377)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2332)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2209)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:649)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:145)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1238)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:663)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:625)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:617)
at com.handsomelee.gotroute.MainActivity$1.onTabSelected(MainActivity.java:73)
at android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1165)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1158)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1427)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1537)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
--------- beginning of system
this is my MainActivity.java
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
if(tab1 == null){
tab1 = new MapsActivity(R.id.mapView, R.layout.activity_maps, GoogleMap.MAP_TYPE_NORMAL);
}
return tab1;
case 1:
if(tab2 == null)
tab2 = new CarParkingActivity();
return tab2;
case 2:
if(tab3 == null)
tab3 = new ReportActivity();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
MapsActivity.java
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
rootView = layoutInflater.inflate(layoutActivityId, viewGroup, false);
mapView = ((MapView) rootView.findViewById(mapViewId));
mapView.onCreate(bundle);
mapView.getMapAsync(this);
addOn();
return rootView;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(googleMapType);
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
mMap.setOnMapLongClickListener(this);
}
}
activity_maps.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.handsomelee.gotroute.Controller.ReportActivity">
<fragment
android:layout_width="0dp"
android:layout_height="50dp"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
android:id="#+id/placeSearch"
android:layout_weight="0.67"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"/>
<com.google.android.gms.maps.MapView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="#+id/mapView"
android:layout_weight="0.78"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:apiKey="#string/test_google_api"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintTop_toBottomOf="#+id/placeSearch"/>
</android.support.constraint.ConstraintLayout>
ReportActivity.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_report, container, false);
spinner = (Spinner) rootView.findViewById(R.id.spinner);
String[] array_Spiner = getResources().getStringArray(R.array.reports_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(rootView.getContext(), R.layout.support_simple_spinner_dropdown_item, array_Spiner);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
~
});
return rootView;
}
activity_report.xml
<?xml version="1.0" encoding="utf-8"?>`
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.handsomelee.gotroute.Controller.ReportActivity">
<Spinner
android:layout_width="0dp"
android:layout_height="50dp"
android:id="#+id/spinner"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:overlapAnchor="false"
android:dropDownWidth="match_parent"
app:layout_constraintHorizontal_bias="0.0"/>
</android.support.constraint.ConstraintLayout>
SOLVED.
The problem seems like is the fragment id duplicated when the view is created.
so I add the Code below at my MapActivity to remove it.
#Override
public void onDestroyView() {
super.onDestroyView();
android.app.FragmentManager fm = getActivity().getFragmentManager();
android.app.Fragment fragment = fm.findFragmentById(R.id.placeSearch);
android.app.FragmentTransaction ft = fm.beginTransaction();
ft.remove(fragment);
ft.commit();
}
The Problem:
In my onCreate() on my main activity, I am trying to set the text value of a TextView in my fragment which is displayed by a viewpager. When I try to get my fragment instance, It always returns null.
Solutions I Tried:
Almost every solution related to this problem on SO gives me the same result(NPE).
My Code is below as well as some explanation...
Home.java Activity (My Main Activity):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Show the home layout
setContentView(R.layout.home);
// Setup the toolbar
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Now setup our tab bar
TabLayout tabLayout = (TabLayout)findViewById(R.id.homeTabs);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
// Setup the view pager
ViewPager viewPager = (ViewPager)findViewById(R.id.viewPager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
// Start our service controller
Intent startServiceController = new Intent(this, ServiceController.class);
startService(startServiceController);
Fragment viewFragment = pagerAdapter.getRegisteredFragment(viewPager.getCurrentItem());
if(viewFragment == null){
Log.v("Fragment", "NULL");
}
}
After setting up the pageAdapter and viewpager, I try to access the fragment thats being shown. The code for my PagerAdapter is below...
PagerAdapter:
public class PagerAdapter extends SmartFragmentStatePagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ParkListFragment();
case 1:
return new MapFragment();
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
CharSequence title;
switch (position){
case 0:
title = "Spaces Near You";
break;
case 1:
title = "Map";
break;
default:
title = "N/A";
break;
}
return title;
}
}
SmartFragmentStatePagerAdapter:
public abstract class SmartFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
// Sparse array to keep track of registered fragments in memory
private SparseArray<Fragment> registeredFragments = new SparseArray<>();
public SmartFragmentStatePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Register the fragment when the item is instantiated
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
// Unregister when the item is inactive
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
// Returns the fragment for the position (if instantiated)
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
I really don't understand what the issue is. I have tried many things. What I don't want to use is this:
String tag="android:switcher:" + viewId + ":" + index;
ParkListFragment.java:
public class ParkListFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.park_list_fragment, container, false);
}
}
ParkList Fragment Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/confidenceText"
android:textAlignment="center"
android:textSize="24sp"
android:textColor="#android:color/primary_text_light"
android:padding="10dp"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/activityText"
android:textAlignment="center"
android:textSize="24sp"
android:textColor="#android:color/primary_text_light"
android:padding="10dp"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
Stack Trace: Pastebin
So after hours of trial and error, the only thing that worked for me was this SO post:
ViewPager Fragments are not initiated in onCreate
I'm making an Android app that uses an appBarLayout with tabs in it and webViews that load an external URL underneath it. In the toolbar menu I want to add a refresh option that refreshes only the current tab. I couldn't figure out how to get it working in my specific case. I already tried this solution but when I press the refresh button, the app crashes.
EDIT: I think the only part I need to edit is if (id == R.id.action_refresh) in my MainActivity.java. But because I have 4 tabs (Tab0, Tab1 etc.) I think it shouldn't say Tab0.webview.reload();, but just the current tab which is open.
Here is my MainActivity.java
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private 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);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(3);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
//TODO
return true;
}
if (id == R.id.action_refresh) {
//What comes here?
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab0 tab0 = new Tab0();
return tab0;
case 1:
Tab1 tab1 = new Tab1();
return tab1;
case 2:
Tab2 tab2 = new Tab2();
return tab2;
case 3:
Tab3 tab3 = new Tab3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Tab 0";
case 1:
return "Tab 1";
case 2:
return "Tab 2";
case 3:
return "Tab 3";
}
return null;
}
}
}
My activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.my.app.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:background="#android:color/holo_red_light">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="#android:color/holo_red_light"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="44dp"
android:background="#android:color/holo_red_light"
app:tabMode="scrollable" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" >
</android.support.v4.view.ViewPager>
</android.support.design.widget.CoordinatorLayout>
My Tab0.java
public class Tab0 extends Fragment {
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.tab0, container, false);
webview = (WebView)rootView.findViewById(R.id.webview0);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setBuiltInZoomControls(true);
CookieManager.getInstance().setAcceptCookie(true);
webview.loadUrl("https://www.google.com");
return rootView;
}
}
My tab0.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.my.app.MainActivity$SectionsPagerAdapter">
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webview0"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
Can someone help me with implementing the refresh button?
Thanks in advance
The WebView.reload() should be the way to go for you as mentioned in the post you refered.
If your app crash because of it then you probably do soemthing wrong. What is the crash error?
Use following in the onOptionsItemSelected method:
if (id == R.id.action_refresh) {
((WebView) mSectionsPagerAdapter.getItem(0).getView().findViewById(R.id.webview0)).reload();
return true;
}
I've implemented TabLayout from the support library, but it overwrites the ActionBar that i need.
This is the activity that sets it up and inflates the tabs and loads the fragment for the tab.
public class TabsActivity extends android.support.v4.app.FragmentActivity {
FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
setTitle("Fuel Logger");
ActionBar a = getActionBar();
ViewPager vp = (ViewPager) findViewById(R.id.viewpager);
vp.setAdapter(new FragmentPagerAdapter(
getSupportFragmentManager(), TabsActivity.this
));
TabLayout tabLayout = (TabLayout) findViewById(R.id.fuel_sliding_tabs);
tabLayout.setupWithViewPager(vp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.fuel_menu, menu);
MenuItem refresh = menu.findItem(R.id.action_settings);
refresh.setEnabled(true);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_settings:
break;
case R.id.action_favorite:
return true;
default:
}
return super.onOptionsItemSelected(item);
}
}
and the xml is just the view pager and tab layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
style="#style/FuelTabLayout"
android:id="#+id/fuel_sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1.27"
android:background="#android:color/white"
android:layout_alignParentBottom="true"
android:layout_below="#+id/fuel_sliding_tabs" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#android:drawable/ic_menu_set_as"
app:layout_anchorGravity="bottom|right|end"
app:backgroundTint="#color/colorAccent"
android:layout_gravity="right"
android:cropToPadding="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp" />
</RelativeLayout>
and an example of fragments code which is more or less the same for each fragments class
Public class SummaryFragment extends android.support.v4.app.Fragment {
public static final String ARG_PAGE = "SUMM_PAGE";
private int mTab;
public static SummaryFragment newInstance(int page){
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
SummaryFragment frag = new SummaryFragment();
frag.setArguments(args);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTab = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_summary, null);
return view;
}
first add ToolBar , and use LinearLayout witch have horizontal orientation
and set the in the style NoActionBar
hope its help you