How to combine BottomNavigationView and ViewPager? - java

I need help to combine ViewPager and BottomNavigationView. But when I swipe the screen as ViewPager works, the fragment become stacked with another fragment. How do I fix this?
Stacked fragment
On normal fragment before swiped
Here is my code :
MainActivity.java
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
private BottomNavigationView mBottomNavigation;
private ViewPager viewPager;
private ViewPagerAdapter mViewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new HomeFragment());
mBottomNavigation = findViewById(R.id.buttom_navigation);
mBottomNavigation.setOnNavigationItemSelectedListener(this);
viewPager = findViewById(R.id.view_pager);
mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mViewPagerAdapter);
}
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container_frame_layout, fragment);
ft.commit();
return true;
}
return false;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.menu_home:
fragment = new HomeFragment();
break;
case R.id.menu_favorite:
fragment = new FavoriteFragment();
break;
case R.id.menu_account:
fragment = new AccountFragment();
break;
}
return loadFragment(fragment);
}
activity_main.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/container_frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/buttom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:layout_alignParentBottom="true"
app:itemIconTint="#ffff"
app:itemTextColor="#ffff"
app:menu="#menu/item_menu"/>
</RelativeLayout>
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new HomeFragment();
case 1:
return new FavoriteFragment();
case 2:
return new AccountFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
Thanks in advance!

Change this code in MainActivity
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_home:
viewPager.setCurrentItem(0);
break;
case R.id.menu_favorite:
viewPager.setCurrentItem(1);
break;
case R.id.menu_account:
viewPager.setCurrentItem(2);
break;
}
return true;
}
Add this code for select bottomNavigation Tab.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
mBottomNavigation.getMenu().findItem(R.id.menu_home).setChecked(true);
break;
case 1:
mBottomNavigation.getMenu().findItem(R.id.menu_favorite).setChecked(true);
break;
case 2:
mBottomNavigation.getMenu().findItem(R.id.menu_account).setChecked(true);
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});

As the answer of Mr. #Chintan , I replaced :
return new FooFragment();
to
viewPager.setCurrentItem(index);
And remove loadFragment() function, it's perfectly works now. Thank you very much!

binding.bottomNavigation.setOnClickMenuListener(model -> {
switch (model.getId()) {
case 1:
binding.viewPager.setCurrentItem(0);
break;
case 2:
binding.viewPager.setCurrentItem(1);
break;
case 3:
binding.viewPager.setCurrentItem(2);
break;
case 4:
binding.viewPager.setCurrentItem(3);
break;
}
return null;
});

Related

Fragment not loading with bottom navigation view

Hi i'm making app where i'm using bottom navigation to navigate through the fragments but my problem is when i click the app is loaded fragments are not visible in frame layout and even when i click bottom navigation it is just showing blank page
below is my code for main activity
I searched for this problem on google but looks like i'm the only one having this problem
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener{
FrameLayout frameLayout;
FragmentManager fragmentManager;
Fragment fragment;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
if(findViewById(R.id.frame_container)!=null){
if(savedInstanceState!=null){
return;
}
}
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_nav);
//bottomNavigationView.setOnNavigationItemSelectedListener(this);
//final SeekBar sb = (SeekBar) findViewById(R.id.sb);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()){
case R.id.navigation_home:
fragment = new HomeFragment();
loadFragment(fragment);
return true;
case R.id.navigation_feed:
fragment = new FeedFragment();
loadFragment(fragment);
return true;
case R.id.navigation_event:
fragment = new EventsFragment();
loadFragment(fragment);
return true;
case R.id.navigation_nearby:
fragment = new NearbyFragment();
loadFragment(fragment);
return true;
case R.id.navigation_profile:
fragment = new ProfileFragment();
loadFragment(fragment);
return true;
}
return false;
}
private void loadFragment(Fragment fragment) {
// load fragment
//HomeFragment homeFragment = new HomeFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment,null);
// transaction.addToBackStack(null);
/* Comment this line and it should work!*/
//transaction.addToBackStack(null);
transaction.commit();
}
}
and my xml
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fillViewport="true"
android:fitsSystemWindows="true"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="match_parent"
android:layout_height="0dp"
app:menu="#menu/navigation"
android:backgroundTint="#color/nav_color"
app:itemIconTint="#color/bottom_nav_fore_color"
android:background="?android:attr/windowBackground"
android:layout_weight="0.1">
</android.support.design.widget.BottomNavigationView>
</LinearLayout>
Your code seems correct , uncomment this line and then check :
bottomNavigationView.setOnNavigationItemSelectedListener
(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = ItemOneFragment.newInstance();
break;
case R.id.action_item2:
selectedFragment = ItemTwoFragment.newInstance();
break;
case R.id.action_item3:
selectedFragment = ItemThreeFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, selectedFragment);
transaction.commit();
return true;
}
});
Hope this helps !
Remove this :
implements BottomNavigationView.OnNavigationItemSelectedListener
You don't set Your setOnNavigationItemSelectedListener means you are not setting fragment to bottom navigation drawer that why no fragment is viewing.
First add setOnNavigationItemSelectedListener to bottomnavigation
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
Then add this code-:
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment=null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
loadFragment(fragment);
return true;
case R.id.navigation_feed:
fragment = new FeedFragment();
loadFragment(fragment);
return true;
case R.id.navigation_event:
fragment = new EventsFragment();
loadFragment(fragment);
return true;
case R.id.navigation_nearby:
fragment = new NearbyFragment();
loadFragment(fragment);
return true;
case R.id.navigation_profile:
fragment = new ProfileFragment();
loadFragment(fragment);
return true;
}
return false;
}
};

I got my app Crash when i swipe in viewpager and tab in tablayout [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
activity_viber.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:menu="#menu/home_menu">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tablayout"
android:background="#color/colorPrimaryDark"/>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/viewpager"/>
</LinearLayout>
viber.java
public class Viber extends AppCompatActivity {
private PagesAdapter pageadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viber);
TabLayout tab = (TabLayout)findViewById(R.id.tablayout);
tab.addTab(tab.newTab().setText("Contact").setIcon(R.drawable.ic_contact_phone_black_24dp));
tab.addTab(tab.newTab().setText("Add").setIcon(R.drawable.ic_person_add_black_24dp));
tab.addTab(tab.newTab().setText("Message").setIcon(R.drawable.ic_message_black_24dp));
pageadapter = new PagesAdapter(getSupportFragmentManager());
final ViewPager viewPager = (ViewPager)findViewById(R.id.viewpager);
viewPager.setAdapter(pageadapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab));
tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.search:
Toast.makeText(this,"Clicked",Toast.LENGTH_SHORT).show();
//startActivity(new Intent(this,Search.class));
break;
case R.id.publicacc:
//startActivity(new Intent(Viber.this,Search.class));
Toast.makeText(this,"Clicked",Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
}
PagesAdapter.java
public class PagesAdapter extends FragmentPagerAdapter {
int nooffrags=3;
public PagesAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
ContactFragment cf = new ContactFragment();
return cf;
case 1:
return new AddContactFragment();
case 3:
return new MessageFragment();
default:
return null;
}
}
#Override
public int getCount() {
return nooffrags;
}
}
I had added 3 tab and when i swipe the view pager it will load for a sec and crash and same in tab.When tabbed load for a sec and crash. And also it the optionitemselected when i check for the item being clicked or not it clicked but when i click with startActivity(new Intent(this,Search.this)); it again crash the system or app any solution.
inside your PagesAdapter.java inside your getItem(int Position) add case 2: because when you swap to 3 it gets the position value 2 and Case 2 is not available so it will return default value i.e. null and you will get nullPointerException
in PagesAdapter.java: case 3: should be case 2:
use this because Case 2 is not available so it will return default value
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
ContactFragment cf = new ContactFragment();
return cf;
case 1:
return new AddContactFragment();
case 2:
return new MessageFragment();
default:
return null;
}
}
instead of this
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
ContactFragment cf = new ContactFragment();
return cf;
case 1:
return new AddContactFragment();
case 3:
return new MessageFragment();
default:
return null;
}
}

ViewPager setAdapter = NullPointerException

I'm trying to implement ViewPager in the new fashion way with the PagerSlidingTabStrip library. I think that code is fine, but I'm getting an error when I'm trying to set the adapter to the ViewPager. My code worked fine before I started using PagerSlidingTabStrip, but that code is now deprecated.
Error:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.adrissa.klea/com.adrissa.klea.MainActivity}:
java.lang.NullPointerException Caused by:
java.lang.NullPointerException at
com.adrissa.klea.MainActivity.onInt(MainActivity.java:103) at
br.liveo.navigationliveo.NavigationLiveo.mountListNavigation(NavigationLiveo.java:248)
at
br.liveo.navigationliveo.NavigationLiveo.onCreate(NavigationLiveo.java:104)
at android.app.Activity.performCreate(Activity.java:5451)
This is the implementation of the ViewPager:
public class MainActivity extends NavigationLiveo implements
br.liveo.interfaces.OnItemClickListener, NavigationDrawerFragment.NavigationDrawerCallbacks,
ActionBar.TabListener {
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private HelpLiveo mLiveo;
ViewPager mViewPager;
FragmentPagerAdapter mSectionsPagerAdapter;
String category;
public static ArrayList<String> categoriesForSellClass = new ArrayList<String>();
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
public void onInt(Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//user information NavDrawer
this.userName.setText("Name");
this.userEmail.setText("Email");
this.userPhoto.setImageResource(R.drawable.selfie);
this.userBackground.setImageResource(R.drawable.nav_drawer_bg);
//setup navigation drawer
mLiveo = new HelpLiveo();
mLiveo.add(getString(R.string.home), R.drawable.home);
mLiveo.add(getString(R.string.my_adverts), R.drawable.price);
mLiveo.add(getString(R.string.messages), R.drawable.envelope);
mLiveo.addSeparator();
mLiveo.add(getString(R.string.settings), R.drawable.settings);
mLiveo.add(getString(R.string.log_out), R.drawable.power);
with(this, Navigation.THEME_LIGHT).startingPosition(0)
.addAllHelpItem(mLiveo.getHelp())
.setOnClickUser(onClickPhoto)
.setOnPrepareOptionsMenu(onPrepare)
.build();
mTitle = getTitle();
mSectionsPagerAdapter = new MyPagerAdapter(
getSupportFragmentManager());
final ActionBar actionBar = getSupportActionBar();
//actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
//here is line 103 \/
mViewPager.setAdapter(mSectionsPagerAdapter);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(mViewPager);
// 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.
tabs
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
mViewPager.requestTransparentRegion(mViewPager);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Categories");
query.findInBackground(new FindCallback<ParseObject>() {
#SuppressLint("NewApi")
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
categoriesForSellClass.add("Alle");
categoriesForSellClass.add("Favoritter");
for (int i = 0; i < objects.size(); i++) {
ParseObject pObject = objects.get(i);
category = pObject.getString("name");
categoriesForSellClass.add(category);
}
// onSucced(objects);
} else {
}
}
});
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, AllFragment.newInstance(position + 1))
.commit();
}
private View.OnClickListener onClickPhoto = new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "onClickPhoto :D", Toast.LENGTH_SHORT).show();
closeDrawer();
}
};
private OnPrepareOptionsMenuLiveo onPrepare = new OnPrepareOptionsMenuLiveo() {
#Override
public void onPrepareOptionsMenu(Menu menu, int position, boolean visible) {
}
};
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onItemClick(int position) {
Fragment mFragment;
FragmentManager mFragmentManager = getSupportFragmentManager();
mFragment = null;
switch (position){
case 2:
//mFragment = new ViewPagerFragment();
break;
default:
//mFragment = MainFragment.newInstance(mHelpLiveo.get(position).getName());
break;
}
if (mFragment != null){
mFragmentManager.beginTransaction().replace(R.id.container, mFragment).commit();
}
}
The PagerAdapter class:
public class MyPagerAdapter extends FragmentPagerAdapter implements PagerSlidingTabStrip.IconTabProvider{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
final int[] ICONS = new int[] {
R.drawable.ic_action_camera,
R.drawable.ic_action_person,
R.drawable.ic_action_important,
R.drawable.ic_action_time,
R.drawable.ic_action_map
};
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new AllFragment();
case 1:
return new ProfileFragment();
case 2:
return new ThirdFragment();
case 3:
return new ProfileFragment();
case 4:
return new MapFragment().newInstance(new LatLng(55.7200,
10.5700));
}
return null;
}
#Override
public int getPageIconResId(int i) {
return ICONS[i];
}
}
main_activity.xml
<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">
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f3f6f7"></android.support.v4.view.ViewPager>
</RelativeLayout>
Any help is appreciated!
Looks like you've changed the name of onCreate(Bundle args) to onInt():
#Override
public void onInt(Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
Change the method name back to onCreate().

Doesn't re-load fragments ViewPager

I have a problem with fragments and the ViewPager, my ViewPager is composed of five tabs, each one is a Fragment.
On the first load I don't have problem with these load, but when I open another fragment (Ahead the main), and go back to the main, the fragments where I was, and those, has been removed (invisible).
For fix that I need to "get away" for two pages before the central page loads.
Everything is only in API 21 (5.0.1), with Android Studio.
MainActivity.java:
public class MainActivity extends FragmentActivity {
private MainActivityFragment frag_MainActivity;
private CreditsFragment frag_Credits;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frag_MainActivity = new MainActivityFragment(this);
frag_Credits = new CreditsFragment();
switchFrag("main");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_home) {
switchFrag("main");
return true;
} else if (id == R.id.action_credits) {
switchFrag("credits");
return true;
}
return super.onOptionsItemSelected(item);
}
public void switchFrag(String view){
Fragment frag = new Fragment();
if(view.equals("main")){
getActionBar().show();
frag = new MainActivityFragment(this);
} else if(view.equals("credits")){
getActionBar().hide();
frag = new CreditsFragment();
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, frag)
.addToBackStack(null).commit();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
switchFrag("main");
return true;
}
return super.onKeyUp(keyCode, event);
}
public void closeApp() {
finish();
System.exit(0);
}
And the XML (activity_main.xml):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</RelativeLayout>
MainActivityFragment.java:
public class MainActivityFragment extends Fragment implements ActionBar.TabListener {
private ViewPager viewPager;
private MyAdapter mAdapter;
private ActionBar actionBar;
private String[] tabs = { "Lun", "Mar", "Merc", "Gio", "Ven"};
MainActivity main;
public MainActivityFragment(MainActivity instance) {
main = instance;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewPager = (ViewPager) main.findViewById(R.id.pager);
actionBar = main.getActionBar();
mAdapter = new MyAdapter(main.getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
if(actionBar.getTabCount() == 0){
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {}
XML (fragment_settings.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"
tools:context=".MainActivityFragment">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
If the Adapter is needed, here it is:
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 5;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
switch(position){
case 0:
return new LunFragment();
case 1:
return new MarFragment();
case 2:
return new MerFragment();
case 3:
return new GioFragment();
case 4:
return new VenFragment();
}
return null;
}
}
Replace mAdapter = new MyAdapter(main.getSupportFragmentManager()); with mAdapter = new MyAdapter(main.getChildFragmentManager());. You need to create the fragments as inner fragments of your MainActivityFragment.

Unable to start activity. Caused by: android.view.InflateException:

LogCat Error:
https://github.com/Heromine/tempapp1/issues/2
Can anybody tell me, why I am getting this error?
I don't understand what i am doing wrong:
MainActivity.java:
public class MainActivity extends ActionBarActivity {
// UI elements
public static Toolbar toolbar;
public static ViewPager viewPager;
private AppSectionsPagerAdapter mAppSectionsPagerAdapter;
// Tab titles
private String[] tabs = {"Home", "Note"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences("prefs", 0);
boolean firstRun = settings.getBoolean("firstRun", true);
if (firstRun) { // here run your first-time instructions, for example :
startActivity(new Intent(this, MyIntro.class));
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstRun", false);
editor.commit();
}
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action/tool bar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar); // Setting toolbar with setSupportActionBar()
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(mAppSectionsPagerAdapter);
/* ViewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
swipeLayout.setEnabled(false);
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
swipeLayout.setEnabled(true);
break;
}
return false;
}
});
*/
// Adding Tabs
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(viewPager);
tabs.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections
// change toolbar title
if (position == 0)
toolbar.setTitle(getResources().getString(R.string.app_name));
}
});
}
#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) {
switch (item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent("android.intent.action.SettingsActivity"));
return true;
case R.id.action_donate:
startActivity(new Intent("android.intent.action.DonateActivity"));
return true;
case R.id.action_rate:
Intent i2 = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.service.beta.servicenotesbeta"));
startActivity(i2);
return super.onOptionsItemSelected(item);
default:
return super.onOptionsItemSelected(item);
}
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int i) {
switch (i) {
case 0:
return new Fragment_main();
case 1:
return new Fragment_second();
/*case 2:
return new Fragment_third();
case 3:
return new Fragment_fourth();*/
default:
return null;
}
}
#Override
public int getCount() {
return 2; //3-4
}
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/ToolBarStyle"
android:id="#+id/toolbar"/>
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true" />
</RelativeLayout>
</LinearLayout>
Please tell me what i am doing wrong
I put the issue link because when i put the issue code it gives me an error
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String java.lang.CharSequence.toString()' on a null object reference
at com.astuetz.PagerSlidingTabStrip.notifyDataSetChanged(PagerSlidingTabStrip.java:200)
at com.astuetz.PagerSlidingTabStrip.setViewPager(PagerSlidingTabStrip.java:182)
at com.service.beta.servicenotesbeta.MainActivity.onCreate(MainActivity.java:67)
there is a problem with <com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
have you looked at https://github.com/astuetz/PagerSlidingTabStrip/ for further infos?
Go to AppSectionsPagerAdapter.java and add this piece of code necessary to provide a title that your PagerSlidingTabStrip can obtain.
#Override
public CharSequence getPageTitle(int position) {
if (position == 0)
{
return "Movies";
}
if (position == 1)
{
return "Events";
}
return null;
}
I fixed, the problem was that i didn't add the titles to the tabs

Categories

Resources