Swiping through fragments then app crashed - java

Like a title , how can i fix it
Error
java.lang.RuntimeException:
com.example.doanlttbdd.MainActivity#28acf243 must implement
OnFragmentInteractionListener
There is MainActivity
public class MainActivity extends AppCompatActivity {
private Toolbar mToolbar;
private ViewPager viewPager;
private TabLayout tabLayout;
private TabsAccessorAdapter tabsAccessorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar= findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("F9");
viewPager= findViewById(R.id.main_tabs_paper);
tabsAccessorAdapter= new TabsAccessorAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsAccessorAdapter);
tabLayout= findViewById(R.id.main_tabs);
tabLayout.setupWithViewPager(viewPager);
}
Here is myAdapter
public TabsAccessorAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int i) {
switch (i){
case 0:
ChatsFragment chatsFragment=new ChatsFragment();
return chatsFragment;
case 1:
GroupsFragment groupsFragment=new GroupsFragment();
return groupsFragment;
case 2:
ContactsFragment contactsFragment=new ContactsFragment();
return contactsFragment;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Chats";
case 1:
return "Groups";
case 2:
return "Contacts";
default:
return null;
}
}
My chatsfragment
public class ChatsFragment extends Fragment {
public ChatsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_chats, container, false);
}
the other fragment just like this
i think it is bacause i'm using androidx so i cannot find any solution to fix it in the internet
RedLine in this (getSupportFragmentManager())

The quick solution first then the explanation
public class MainActivity extends AppCompatActivity implements OnFragmentInteractionListener
It is gonna red lint the MainActivity, alt + enter and choose the solution it will add the missing methods.
The problem is one of your fragments need the parent activity implements that interface to be used as a callback. Probably the fragment is doing something like this
#Override
onAttach...
if context is casteable to the Interface then initialize a field, otherwise crash with the message
These are common patterns. The callback in the parent activity is used to coordinate with other fragments.It is a way to know when something happen on a fragment and then do something on other. The exception throwed is to make sure you implement the needed interface.
This also probably happen for using the fragment wizarf on Android Studio but not reading the checkbox Include callback...

Create a new project.
create a pager adapter TabsPagerAdapter.java
import info.androidhive.tabsswipe.GamesFragment;
import info.androidhive.tabsswipe.MoviesFragment;
import info.androidhive.tabsswipe.TopRatedFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment();
case 1:
// Games fragment activity
return new GamesFragment();
case 2:
// Movies fragment activity
return new MoviesFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
Now create First Tab View fragment_top_rated.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fa6a6a" >
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Design Top Rated Screen"
android:textSize="20dp"
android:layout_centerInParent="true"/>
</RelativeLayout>
now create TopRatedFragment.java
import info.androidhive.tabsswipe.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TopRatedFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
return rootView;
}
}
similarly repeat step 3 and 4 to create GamesFragment and MoviesFragment and their XML
now create MainActivity.java
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import info.androidhive.tabsswipe.R;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}

Related

Android Studio, how add fragments to my tab menu?

I found a tab navigation snippet online and I wonder how to add multiple fragment to it.
I would like to make it work that way:
If i choose first position in menu, it will open fragment_one.xml.
If i choose second position in menu, it will open fragment_two.xml.
Currently, I have only 1 fragment and I dont know how add more.
package com.example.myapp;
import java.util.Locale;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_omnie, container, false);
return rootView;
}
}
}
Well you need to create 3 diffrent fragments Like your "PlaceholderFragment"
and In SectionPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position)
{
case 0: return PlaceholderFragment.newInstance(position + 1);
case 1: return FirstFragment(position + 1);
case n: return nthFragment(position + 1);
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
or take a look at this tutorial
http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/

Android fragment app errors

I have this calendar app that I am trying to add into a tabs action bar. But when I join all the code together to try and complete the app i get many errors.
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class
It tells me that I should try and add it into the android manifest but as they are fragments surely you cant add fragments to the android manifest, anyway here is my code...
package com.idkstudios.shiftcalculator;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import com.idkstudios.shiftcalculator.tab.TabsPagerAdapter;
public class MainActivity extends AppCompatActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter adapter;
private ActionBar actionBar;
/**
* Tab titles
*/
private String[] tabTitles = {"Hours List", "Calendar", "Pay"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getSupportActionBar();
adapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
/**
* For adding tabs
*/
for(String tabs : tabTitles){
actionBar.addTab(actionBar.newTab().setText(tabs).setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onTabSelected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.support.v4.app.FragmentTransaction ft) {
}
}
That was my main activity this is the three fragments,
package com.idkstudios.shiftcalculator.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import com.idkstudios.shiftcalculator.R;
import com.idkstudios.shiftcalculator.calendar.adapter.CalendarAdapter;
import com.idkstudios.shiftcalculator.calendar.util.CalendarCollection;
import java.util.GregorianCalendar;
/**
* Created by Toby on 02/09/2015.
*/
public class CalendarFragment extends Fragment {
/**
* The basic variables that you will need for the calendar
*/
public GregorianCalendar cal_month, cal_month_copy;
private CalendarAdapter cal_adapter;
private TextView tv_month;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
* Sets up the basic layout file, we return this later
*/
View rootView = inflater.inflate(R.layout.fragment_calendar, container, false);
cal_month = (GregorianCalendar) GregorianCalendar.getInstance();
cal_month_copy = (GregorianCalendar) cal_month.clone();
cal_adapter = new CalendarAdapter(getActivity(), cal_month, CalendarCollection.date_collection_arr);
tv_month = (TextView) getActivity().findViewById(R.id.tv_month);
tv_month.setText(android.text.format.DateFormat.format("MMMM yyyy", cal_month));
ImageButton previous = (ImageButton) getActivity().findViewById(R.id.ib_prev);
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setPreviousMonth();
refreshCalendar();
}
});
ImageButton next = (ImageButton) getActivity().findViewById(R.id.Ib_next);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setNextMonth();
refreshCalendar();
}
});
GridView gridview = (GridView) getActivity().findViewById(R.id.gv_calendar);
gridview.setAdapter(cal_adapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
((CalendarAdapter) parent.getAdapter()).setSelected(v,position);
String selectedGridDate = CalendarAdapter.day_string
.get(position);
String[] separatedTime = selectedGridDate.split("-");
String gridvalueString = separatedTime[2].replaceFirst("^0*","");
int gridvalue = Integer.parseInt(gridvalueString);
if ((gridvalue > 10) && (position < 8)) {
setPreviousMonth();
refreshCalendar();
} else if ((gridvalue < 7) && (position > 28)) {
setNextMonth();
refreshCalendar();
}
((CalendarAdapter) parent.getAdapter()).setSelected(v,position);
((CalendarAdapter) parent.getAdapter()).getPositionList(selectedGridDate, getActivity());
}
});
return rootView;
}
protected void setNextMonth() {
if (cal_month.get(GregorianCalendar.MONTH) == cal_month
.getActualMaximum(GregorianCalendar.MONTH)) {
cal_month.set((cal_month.get(GregorianCalendar.YEAR) + 1),
cal_month.getActualMinimum(GregorianCalendar.MONTH), 1);
} else {
cal_month.set(GregorianCalendar.MONTH,
cal_month.get(GregorianCalendar.MONTH) + 1);
}
}
protected void setPreviousMonth() {
if (cal_month.get(GregorianCalendar.MONTH) == cal_month
.getActualMinimum(GregorianCalendar.MONTH)) {
cal_month.set((cal_month.get(GregorianCalendar.YEAR) - 1),
cal_month.getActualMaximum(GregorianCalendar.MONTH), 1);
} else {
cal_month.set(GregorianCalendar.MONTH,
cal_month.get(GregorianCalendar.MONTH) - 1);
}
}
public void refreshCalendar() {
cal_adapter.refreshDays();
cal_adapter.notifyDataSetChanged();
tv_month.setText(android.text.format.DateFormat.format("MMMM yyyy", cal_month));
}
}
The second fragment
package com.idkstudios.shiftcalculator.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import com.idkstudios.shiftcalculator.R;
import com.idkstudios.shiftcalculator.calendar.adapter.AndroidListAdapter;
import com.idkstudios.shiftcalculator.calendar.util.CalendarCollection;
import java.util.ArrayList;
/**
* Created by Toby on 02/09/2015.
*/
public class HoursListFragment extends Fragment implements View.OnClickListener{
private ListView lv_android;
private AndroidListAdapter list_adapter;
private Button btn_calender;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_hours, container, false);
CalendarCollection.date_collection_arr = new ArrayList<CalendarCollection>();
CalendarCollection.date_collection_arr.add(new CalendarCollection("2015-04-01","John Birthday"));
CalendarCollection.date_collection_arr.add(new CalendarCollection("2015-04-04","Client Meeting at 5 p.m."));
CalendarCollection.date_collection_arr.add(new CalendarCollection("2015-04-06","A Small Party at my office"));
CalendarCollection.date_collection_arr.add(new CalendarCollection("2015-05-02","Marriage Anniversary"));
CalendarCollection.date_collection_arr.add(new CalendarCollection("2015-04-11","Live Event and Concert of sonu"));
getWidget();
return rootView;
}
public void getWidget(){
btn_calender = (Button) getActivity().findViewById(R.id.btn_calender);
btn_calender.setOnClickListener(this);
lv_android = (ListView) getActivity().findViewById(R.id.lv_android);
list_adapter = new AndroidListAdapter(getActivity(), R.layout.list_item, CalendarCollection.date_collection_arr);
lv_android.setAdapter(list_adapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_calender:
startActivity(new Intent(getActivity(), CalendarFragment.class));
break;
default:
break;
}
}
}
And finally the third which I havent actually coded yet,
package com.idkstudios.shiftcalculator.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.idkstudios.shiftcalculator.R;
/**
* Created by Toby on 02/09/2015.
*/
public class PayFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pay, container, false);
return rootView;
}
}
Here is the android manifest if you needed it
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.idkstudios.shiftcalculator" >
<application
android:allowBackup="true"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here is the adapter class for the main activity
package com.idkstudios.shiftcalculator.tab;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.idkstudios.shiftcalculator.fragments.CalendarFragment;
import com.idkstudios.shiftcalculator.fragments.HoursListFragment;
import com.idkstudios.shiftcalculator.fragments.PayFragment;
/**
* Created by Toby on 02/09/2015.
*/
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fragmentManager){
super(fragmentManager);
}
#Override
public Fragment getItem(int index) {
switch(index){
case 0:
return new HoursListFragment();
case 1:
return new CalendarFragment();
case 2:
return new PayFragment();
}
return null;
}
#Override
public int getCount() {
/**
* This value is equal to the number of tabs you have in the bar
*/
return 3;
}
}
I did think about having a second plan. The three fragments all came from a activity class, so i copied and pasted the code from the activity class into the fragment so that might be where the issue is. I thought about having the original acitivty classes and just start a new intent from the fragment class to the activity class. But then what would the point of the fragment class be then. Im not too sure if this idea would work in the first place.
Any help would be much appreicated. And if you need any more code please let me know and I will happily provide it, whether that is some of the adapters or the xml code.
Thanks Toby.
HoursListFragment.onClick() has this buggy statement:
startActivity(new Intent(getActivity(), CalendarFragment.class));
As you already know, a fragment is not an activity. Did you mean to pass MainActivity.class instead of CalendarFragment.class?
i think problem is your viewpager adapter,
and your MainActivity is better to extend FragmentActivity
because you want to use fragments
then define three fields in MainActivity class like this
CalendarFragment calenderFragment = new CalendarFragment ();
HoursListFragment hourListFragment = new HoursListFragment ();
PayFragment payFragment = new PayFragment ();
and one integer as NUMBER_OF_VIEWPAGER_PAGES
or shorter variable name like NUM_PAGE
public static final int NUM_PAGES = 3;
and make an adapter to your view pager , like this
private class MyAdapter extends FragmentStatePagerAdapter {
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return tabTitles[0] ;
case 1:
return tabTitles[1] ;
default:
return tabTitles[2] ;
}
}
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return calenderFragment;
case 1:
return hourListFragment;
case 2:
return payFragment;
default:
return null;
}
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
finally set adapter to your viewPager
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));

actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) produce NullPointerException

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.ParseAnalytics;
import com.parse.ParseUser;
import adapter.SectionPargerAdapter;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener
{
public static final String TAG = MainActivity.class.getSimpleName();
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionPargerAdapter mSectionPargerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseAnalytics.trackAppOpened(getIntent());
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser == null) {
navigateToLogin();
} else {
Log.i(TAG, currentUser.getUsername());
}
final ActionBar actionBar = getActionBar();
// actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionPargerAdapter = new SectionPargerAdapter(this, getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionPargerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
for (int i = 0; i < mSectionPargerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText( mSectionPargerAdapter.getPageTitle(i))
.setTabListener(MainActivity.this));}
}
});
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
private void navigateToLogin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int itemId = item.getItemId();
//noinspection SimplifiableIfStatement
if (itemId == R.id.action_logout) {
ParseUser.logOut();
navigateToLogin();
}
return super.onOptionsItemSelected(item);
}
}
I face actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) has produce NullPointerException. How can I fix this error? I don't know how to fix. In tutorial video, this has no error but tutorial use with Eclipse. I use Android Studio. Please tell me how to fix? Thanks you very much!
Take a look at this one over here. This guy implements it very nice. However i would not suggest working with actionBar tabs because if you want to upgrade your app to later versions this method is deprecated. So you dont use the actionBar and you can use the following if you would like
YourAdapter mAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_demo);
// ViewPager and its adapters use support library
// fragments, so use getSupportFragmentManager.
mAdapter = new YourAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAdapter);
}
The Adapter:
public class YourAdapter extends FragmentStatePagerAdapter {
private String[] titles = { "Item 1", "Item 2", "Item 3" };
public YourAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch(i){
case 0:{
return new FragementA();
}case 1:{
return new FragmentB();
}case 2:{
return new FragmentC();
}
}
}
#Override
public int getCount() {
return titles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
The Fragment that you will return and implementation of the onCreateView Method:
public static class FragmentA extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_layout_file, container, false);
//Simple implementation how to target text view in your layout
TextView tv = (TextView)rootView.findViewById(R.id.my_text_view);
return rootView;
}
}
The real problem is in res/values/style.xml and res/values-v14/style.xml in the AppBaseTheme (in two styles).
If change Theme.AppCompat.Light and Theme.AppCompat.Light.DarkActionBar by Theme.Holo.Light and Theme.Holo.Light.DarkActionBar in manifest down android:minSdkVersion to version 11, it SOLVES the problem...
But it generates another problem: you lose AppCompat.Light theme...
But error NullExceptionPointer in actionbar.setNavigationmode is solved..

Can someone show me a simple working implementation of PagerSlidingTabStrip?

Here is the library: https://github.com/astuetz/PagerSlidingTabStrip
I'm trying to implement it but my app keeps crashing on startup. I've tried to understand the sample app that is posted but don't think I'm doing something right. Here is my code:
MainActivity.java
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.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.astuetz.PagerSlidingTabStrip;
public class MainActivity extends FragmentActivity {
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
}
private Drawable.Callback drawableCallback = new Drawable.Callback() {
#Override
public void invalidateDrawable(Drawable who) {
getActionBar().setBackgroundDrawable(who);
}
#Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
handler.postAtTime(what, when);
}
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
handler.removeCallbacks(what);
}
};
public class MyPagerAdapter extends FragmentPagerAdapter{
private final String[] TITLES = {"T1","T2"};
public MyPagerAdapter(FragmentManager fm){
super(fm);
}
public CharSequence getPageTitle(int position){
return TITLES[position];
}
#Override
public Fragment getItem(int i) {
return null;
}
#Override
public int getCount() {
return TITLES.length;
}
}
}
And here is activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="edu.purdue.test.app.MainActivity">
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
tools:context=".MainActivity" />
</RelativeLayout>
You're not instantiating any of the fragments you wish to become tabs in the FragmentPagerAdapter, getItem method. Instead you're returning null and therefore there are no views to fill the viewpager. I can see you've checked out his sample project, maybe take a closer look at the fragments you're trying to add to the viewpager. The above answer looks like a sound implementation.
Here is an example that I am using right now,
public class Formulario extends FragmentActivity implements ActionBar.TabListener {
private static final FragmentTransaction transaction = null;
public String ambitorec;
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "tab 1", "tab 2", "tab 3" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_formulario);
ambitorec = getIntent().getStringExtra("ambito");
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
also you need to add the adapter, in this case :
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// tab 1 fragment activity
return new Formulario1Fragment();
case 1:
// tab2 fragment activity
return new Formulario2Fragment();
case 2:
// tab 3 fragment activity
return new MultimediaFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
hope it helps, if you need more help ill try to explain
In FragmentPagerAdapter#getItem, you are not instantiating any of the fragments you want to become tabs. Instead of returning a fragment, you're returning null, which means there are no views to fill the viewpager. I see you've looked over his sample project, so look over the fragments you're trying to add to the viewpager again. The above response appears to be a second implementation.

Getting error in showing activity via Fragment

I am trying to show one my pages in fragments but it is giving me an error.
I have created a separate Class file called FragmentContacts.java, from where i show the layout of activity_contacts.xml.
FragmentContacts Java Code:
package me.example.app;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentContacts extends FragmentActivity {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.activity_contacts, container, false);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// setUserVisibleHint(true);
}
}
Fragment Code:
public Fragment getItem(int arg0) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
//Fragment fragment = new DummySectionFragment();
//Bundle args = new Bundle();
//args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
//fragment.setArguments(args);
//return fragment;
switch (arg0) {
// Open FragmentTab1.java Error on return fragmenttab1
case 0:
FragmentContacts fragmenttab1 = new FragmentContacts();
return fragmenttab1;
return null;
}
Resolved!
This what I did:
1) I made Fragment Class separately for each tab.
2) Then i used the case in order to show each activity in their respective tab.
(sorry for my lack of technical words.)
Solution:
package me.example.app;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class HomeActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the four
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch (arg0){
case 0:
Fragment fragmentContacts = new FragmentContacts();
return fragmentContacts;
case 1:
Fragment fragmentMissed = new FragmentMissed();
return fragmentMissed;
case 2:
Fragment fragmentRecent = new FragmentRecent();
return fragmentRecent;
case 3:
Fragment fragmentGroups = new FragmentGroups();
return fragmentGroups;
}
return null;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
/**Contacts*/
public static class FragmentContacts extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentContacts() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_contacts,
container, false);
return rootView;
}
}
/**Missed Call*/
public static class FragmentMissed extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentMissed() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_missed,
container, false);
return rootView;
}
}
/**Recent Call*/
public static class FragmentRecent extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentRecent() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_recent,
container, false);
return rootView;
}
}
/**Groups*/
public static class FragmentGroups extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public FragmentGroups() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_group,
container, false);
return rootView;
}
}
}

Categories