Disable swipe in tabbed activity (Android Studio) - java

i want to disable the swipe function in the tabbed activity. I tried some examples i found but it didn't worked or the code was completely different.
Here is my code:
MainActivity.java:
package com.example;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
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 {
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);
// 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);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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 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) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
return FragmentOne.newInstance("a","b");
case 1:
return FragmentTwo.newInstance("a","b");
case 2:
return FragmentThree.newInstance("a","b");
case 3:
return FragmentFour.newInstance("a","b");
case 4:
return FragmentFive.newInstance("a","b");
default:
return FragmentThree.newInstance("a","b");
}
}
#Override
public int getCount() {
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "One";
case 1:
return "Two";
case 2:
return "Three";
case 3:
return "Four";
case 4:
return "Five";
}
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_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
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.example.MainActivity"
android:background="#1d2935">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
</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.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="#dimen/fab_margin"
android:src="#mipmap/icon_plus_normal"
app:backgroundTint="#1d2935" />
</android.support.design.widget.CoordinatorLayout>

You need to create Custom ViewPager Class this way .
public class CustomViewPager extends ViewPager {
private boolean swipeable = false;
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
// Call this method in your motion events when you want to disable or enable
// It should work as desired.
public void setSwipeable(boolean swipeable) {
this.swipeable = swipeable;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
return (this.swipeable) ? super.onInterceptTouchEvent(arg0) : false;
}
Now
CustomViewPager ViewPagerObj = (CustomViewPager)findViewById(R.id.container);
ViewPagerObj.setSwipeable(false);
You should add this in your XML
<Your_packagename.CustomViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />

The accepted answer does not work for me. Beginners can just use this kotlin file instead of the accepted answer java file.
class CustomViewPager: ViewPager {
private var swipeable = false
constructor(context: Context) : super(context)
constructor(context:Context, attrs: AttributeSet) : super(context, attrs)
fun setSwipeable(swipeable:Boolean) {
this.swipeable = swipeable
}
override fun onInterceptTouchEvent(arg0: MotionEvent):Boolean {
return if ((this.swipeable)) super.onInterceptTouchEvent(arg0) else false
}
override fun onTouchEvent(event:MotionEvent):Boolean {
return if (this.swipeable) super.onTouchEvent(event) else false
}
}

Related

Imageview to VideoView using fragment

I am trying to make an app with navigation drawer using fragment, where on the home screen there should be images and when you click the image it should take you to that particular image's fragment and video starts playing. But unfortunately I can't see any image on the home screen (maybe I am making mistake in layout). Please help me out. Thanks in advance.
Code below :-
main xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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"
android:id="#+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context="com.hangout.google.heedbasketball.MainActivity"
tools:openDrawer="start"
tools:deviceIds= "tv"
tools:ignore="MergeRootFrame">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimaryDark"
android:id="#+id/toolbar"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:elevation="4dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/i1"
android:src="#drawable/arena_reaction"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/i2"
android:src="#drawable/frequentflyer_diop"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/i3"
android:src="#drawable/frequentflyer_tyus"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragement_container" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu"/>
</android.support.v4.widget.DrawerLayout>
main java file
package com.hangout.google.heedbasketball;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
abstract class MainActivity4 extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this );
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle
(this,drawer,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_sound:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new SoundFragment()).commit();
break;
case R.id.nav_notifications:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new NotificationsFragment()).commit();
break;
case R.id.nav_sponsors:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new SponsorsFragment()).commit();
break;
case R.id.nav_about:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new AboutFragment()).commit();
break;
case R.id.nav_contact_us:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new ContactusFragment()).commit();
break;
case R.id.nav_privacy:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new PrivacyFragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new FirstFragment()).commit();
fragment = new FirstFragment();
break;
case 1:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new SecondFragment()).commit();
fragment = new SecondFragment();
case 2:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container,new ThirdFragment()).commit();
fragment = new ThirdFragment();
break;
default:
fragment = new FirstFragment();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
public void onBackpressed() {
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
} else {
onBackPressed();
}
}
}
Here is the java fragment for one video I have defined in the same way for other videos too
package com.hangout.google.heedbasketball;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.VideoView;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link FirstFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link FirstFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class FirstFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FirstFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FirstFragment.
*/
// TODO: Rename and change types and number of parameters
public static FirstFragment newInstance(String param1, String param2) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
//My video code here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
VideoView v1 = (VideoView) findViewById(R.id.v1);
v1.setVideoURI(Uri.parse("https://myvideo.mp4"));
v1.start();
v1.requestFocus();
v1.setKeepScreenOn(true);
}
}
private Object findViewById(int v1) {
return 0;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
xml file fragment for the video
<?xml version="1.0" encoding="utf-8"?>
<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=".FirstFragment"
android:background="#color/colorPrimaryDark">
<!-- TODO: Update blank fragment layout -->
<VideoView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/v1" />
</RelativeLayout>
You have created findViewById function in on create which returns 0.
You need a video reference from layout which you are inflating.
Something similar to this.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
// see the difference
VideoView v1 = (VideoView) view.findViewById(R.id.v1);
v1.setVideoURI(Uri.parse("https://myvideo.mp4"));
v1.start();
v1.requestFocus();
v1.setKeepScreenOn(true);
return view;
}

Handling Navigation Items with Tabs and Fragments

I have created a navigation drawer and added a tablayout like this
activity_main
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
app_bar_main
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
android:layout_gravity="bottom"
app:tabSelectedTextColor="#fffaf0"/>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
I get the result shown below:
However, I tried to add fragments to the tabs so that each navigate item opens a screen that has two tabs "First Semester" and "Second Semester" whose contents are held in the fragments xml but its not working.
MainActivity
package com.lini.bdevelopers.geomaticshandbook;
//import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ViewPager viewPager;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//SectionsPagerAdapter mSectionPagerAdapter =
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
viewPager = findViewById(R.id.viewpager);
//setupViewPager(viewPager);
tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
// Create adapter for the view pager
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstSemester(), "First Semester");
adapter.addFragment(new SecondSemester(), "Second Semester");
viewPager.setAdapter(adapter);
}
private void setupViewPager2(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstSemester2(), "First Semester");
adapter.addFragment(new SecondSemester2(), "Second Semester");
viewPager.setAdapter(adapter);
}
private void setupViewPager3(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstSemester3(), "First Semester");
adapter.addFragment(new SecondSemester3(), "Second Semester");
viewPager.setAdapter(adapter);
}
private void setupViewPager4(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstSemeste4r(), "First Semester");
adapter.addFragment(new SecondSemester4(), "Second Semester");
viewPager.setAdapter(adapter);
}
private void setupViewPager5(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstSemester5(), "First Semester");
adapter.addFragment(new SecondSemester5(), "Second Semester");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.year1) {
setupViewPager(viewPager);
} else if (id == R.id.year2) {
setupViewPager2(viewPager);
} else if (id == R.id.year3) {
setupViewPager3(viewPager);
} else if (id == R.id.year4) {
setupViewPager4(viewPager);
} else if (id == R.id.year5) {
setupViewPager5(viewPager);
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
The code above binds the FirstSemester() and SecondSemester() fragments to all the navigation items. This may not be the right way to go about it, so I need suggestions and help, thanks.
Secondly
How do I change the AppBar title to the title of the Navigation item selected?
Secondly How do I change the AppBar title to the title of the
Navigation item selected?
In the onNavigationItemSelected() method in your MainActivity class.. you can do something like this:
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.year1) {
getSupportActionBar().setTitle("Year 1");
setupViewPager(viewPager);
} else if (id == R.id.year2) {
getSupportActionBar().setTitle("Year 2");
setupViewPager2(viewPager);
} else if (id == R.id.year3) {
getSupportActionBar().setTitle("Year 3");
setupViewPager3(viewPager);
} else if (id == R.id.year4) {
getSupportActionBar().setTitle("Year 4");
setupViewPager4(viewPager);
} else if (id == R.id.year5) {
getSupportActionBar().setTitle("Year 5");
setupViewPager5(viewPager);
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
As for your first question, you are displaying a viewpager (first and second semester) for any item clicked in the navigation drawer so you shouldn't be expecting a normal-looking code. Crude method though but it's not too poor in efficiency.
I hope this helps.. Merry coding!
If you want to first create YearOne fragment and add the semesters to each Year then you first need to add your YearOne, YearTwo etc fragments to the navigation drawer menu.
I created a simple app to illustrate this some days back https://github.com/mbobiosio/TabLayout
You can attach your TabLayout simply like this in YearOneFragment
mViewPager.setAdapter(new FragmentsAdapter(getChildFragmentManager(), getActivity()));
mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
});
I will share what i used in my application. You can reuse the single fragment. Have a look at this
Mainactivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
{
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setTitle(R.string.app_name); //Toolbar title at start.
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment;
if (id == R.id.year1) {
fragment = new YearFragment(); //Root Fragment then add semester fragment.
loadFragment(fragment);
Bundle data = new Bundle();
data.putString("YEAR","FIRST YEAR"); //Pass year value
fragment.setArguments(data);
toolbar.setTitle("FIRST YEAR");
}
if (id == R.id.year2) {
fragment = new YearFragment();//If your view for fragment is different then create new fragment and change here.
loadFragment(fragment);
Bundle data = new Bundle();
data.putString("YEAR","SECOND YEAR"); //Pass year value
fragment.setArguments(data);
toolbar.setTitle("SECOND YEAR");
}
.
.
.
. //Add upto required navigation items.
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.commit();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
Year Fragment
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
public class YearFragment extends Fragment {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private TabLayout mTabLayout;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.frag_year,container,false);
mTabLayout = rootview.findViewById(R.id.sliding_tabs);
mSectionsPagerAdapter = new SectionsPagerAdapter(getActivity().getSupportFragmentManager());
mViewPager = rootview.findViewById(R.id.vp_container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
String year = getArguments().getString("YEAR",""); //Here you can get year value change code according to year value.
}
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
String[] titles = {"FIRST SEMESTER"," SECOND SEMESTER"};
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
if(position == 0) {
return FirstSemester.newInstance(year);
}
else {
return SecondSemester.newInstance(year);
}
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
}
}
frag_year.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_scrollFlags="scroll"
app:tabIndicatorColor="#color/colorAccent"
app:tabIndicatorHeight="3dp"
app:tabMode="fixed"
app:tabMaxWidth="0dp"
app:tabGravity="fill"
app:tabTextColor="#color/textColor" />
<android.support.v4.view.ViewPager
android:id="#+id/vp_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/sliding_tabs" />
FirstSemester.java
public class FirstSemester extends Fragment {
private static String yearValue = "";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.frag_firstsem,container,false);
if(yearValue.equals("FIRST YEAR"))
{
//Add Code as per your need.
}
return rootview;
}
public static FirstSemester newInstance(String Year) {
FirstSemester fragment = new FirstSemester();
yearValue = Year;
return fragment;
}
frag_firstsem.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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">
//Add your views for Semster fragment.
</android.support.constraint.ConstraintLayout>
Hope it will helps.! And i create bundle and pass year value which is used only your framents view for all navigation items are same.So you can change values according to year otherwise if your nav item views are different you should create seperate fragments for Years & seperate for semester too..

How to call a fragment from menu

I am very new to java and android development. So, even after reading many tutorials(e.g. this, this), I can't figure out how to call a fragment from a bottomnevigationmenu item.
Currently, I have:
MainActivity.java
package com.example.myapplication;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private void loadCalFragment() {
String string1="Hello",string2 = "Hii";
CalFragment fragment = CalFragment.newInstance(string1,string2);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.commit();
}
private TextView mTextMessage;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Context context = getApplicationContext();
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
Toast toasth = Toast.makeText(context , R.string.title_home, Toast.LENGTH_LONG);
toasth.show();
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
Toast toastd = Toast.makeText(context , R.string.title_dashboard, Toast.LENGTH_LONG);
toastd.show();
loadCalFragment();
return true;
case R.id.navigation_notifications:
mTextMessage.setText(R.string.title_location);
Toast toastn = Toast.makeText(context , R.string.title_location, Toast.LENGTH_LONG);
toastn.show();
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
}
activaty_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myapplication.MainActivity">
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginStart="#dimen/activity_horizontal_margin"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:text="#string/title_home"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</android.support.constraint.ConstraintLayout>
Now, when I am adding a fragment using android-studio, it has created the xml file. My target is to create a datepicker in this fragment and show it. But, I don't know how to do that.
fragment_cal.xml
<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="com.example.myapplication.CalFragment">
<!-- TODO: Update blank fragment layout -->
<DatePicker
android:id="#+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:calendarViewShown="false"
android:datePickerMode="spinner" />
</FrameLayout>
and a corresponding java file:
calFragment.java
package com.example.myapplication;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link CalFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link CalFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class CalFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CalFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment CalFragment.
*/
// TODO: Rename and change types and number of parameters
public static CalFragment newInstance(String param1, String param2) {
CalFragment fragment = new CalFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cal, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
My AndroidManifest.xml is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
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>
When I am trying to attach the CalFragment() call to the nevigation menu as:
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
Toast toastd = Toast.makeText(context , R.string.title_dashboard, Toast.LENGTH_LONG);
toastd.show();
CalFragment();
return true;
its giving error: Error:(32, 21) error: cannot find symbol method CalFragment()
I will be grateful if somebody kindly help me in it.
You are using same name for fragment CalFragment() and method CalFragment()
change to below:
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
Toast toastd = Toast.makeText(context , R.string.title_dashboard, Toast.LENGTH_LONG);
toastd.show();
loadCalFragment();
return true;
When your are calling fragment, create loadCalFragment(); method
Create method like below in your Activity class , you are not passing two string values to your fragment newInstance pass using CalFragment fragment = CalFragment.newInstance(string1,string2); pass your actual data here i used demo data:
private void loadCalFragment() {
String string1,string2 = "Hii"
CalFragment fragment = CalFragment.newInstance(string1,string2);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.commit();
}
Update your code from my Code (Activity):
package com.example.myapplication;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Context context = getApplicationContext();
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
Toast toasth = Toast.makeText(context , R.string.title_home, Toast.LENGTH_LONG);
toasth.show();
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
Toast toastd = Toast.makeText(context , R.string.title_dashboard, Toast.LENGTH_LONG);
toastd.show();
loadCalFragment();
return true;
case R.id.navigation_notifications:
mTextMessage.setText(R.string.title_location);
Toast toastn = Toast.makeText(context , R.string.title_location, Toast.LENGTH_LONG);
toastn.show();
return true;
}
return false;
}
};
private void loadCalFragment() {
CalFragment fragment = CalFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_frame, fragment);
ft.commit();
}
}
And CalFragment Code Here :
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class CalFragment extends Fragment {
public CalFragment() {
// 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_cal, container, false);
}
}
Here is the full answer.
activity_main.xml
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="#layout/app_tab_bar">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
app_tab_bar.xml
<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:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="#layout/activity_main" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:itemBackground="#android:color/white"
android:foreground="?attr/selectableItemBackground"
app:itemIconTint="#color/colorAccent"
app:itemTextColor="#color/colorAccent"
app:menu="#menu/navigation" />
</android.support.design.widget.CoordinatorLayout>
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
// load the first fragment by default
loadFragment(new Frag_one());
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.navigation_explore:
fragment = new Frag_one();
loadFragment(fragment);
return true;
case R.id.navigation_saved:
fragment = new Frag_two();
loadFragment(fragment);
return true;
case R.id.navigation_inbox:
fragment = new Frag_three();
loadFragment(fragment);
return true;
case R.id.navigation_profile:
fragment = new Frag_four();
loadFragment(fragment);
return true;
}
return false;
}
};
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
In order to display a fragment you have to define a container in xml file.
Framelayout serves as placeholder for your fragments. So in your mainactivity.xml you need to define the container as I did in my code.

Errors when trying to implement Swipe Views in android

Sorry for the code dump, I'm new to android and don't know where the problem is. I'm trying to implement swipe views in my android app and I'm having some trouble. I tried following this tutorial and this video but I'm getting some errors. I want the tabbed interface in my MainActivity
Here is my MainActivity.java
package com.loomius.loomius;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new FixedTabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
}
}
I'm getting this error for getSupporFragmentManager()
'FixedTabsPagerAdapter(android.app.FragmentManager)' in 'com.loomius.loomius.FixedTabsPagerAdapter' cannot be applied to '(android.support.v4.app.FragmentManager)'
and here is my FixedTabsPagerAdapter.java
package com.loomius.loomius;
import android.app.FragmentManager;
import android.content.Context;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.app.Fragment;
import values.MatchesFragment;
import values.SuggestedSongsFragment;
import values.UserFragment;
public class FixedTabsPagerAdapter extends FragmentPagerAdapter{
public FixedTabsPagerAdapter (FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 4;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return new SearchFragment();
case 1:
return new UserFragment();
case 2:
return new MatchesFragment();
case 3:
return new SuggestedSongsFragment();
default:
return null;
}
}
Context context;
#Override
public CharSequence getPageTitle (int position) {
switch(position) {
case 0:
return context.getResources().getString(R.string.search_frag_title);
case 1:
return context.getResources().getString(R.string.user_frag_title);
case 2:
return context.getResources().getString(R.string.matches_frag_title);
case 3:
return context.getResources().getString(R.string.sugg_frag_title);
default:
return null;
}
}
}
I'm getting this error for the return type Fragment in the overridden method getItem
'getItem(int)' in 'com.loomius.loomius.FixedTabsPagerAdapter' clashes with 'getItem(int)' in 'android.support.v13.app.FragmentPagerAdapter'; attempting to use incompatible return type
I put the android.support.v4.view.ViewPager widget in my activity_main.xml right below the android.support.v7.widget.Toolbar widget.
Look at your FixedTabPagerAdapter constructor, you are trying to catch the reference of android.app.FragmentManager instance while passing the fragment manager of type android.support.v4.app.FragmentManagerwhich are two different classes.
Change the type of FragmentManager in your FixedTabPageAdapter to android.support.v4.app.FragmentManager and it should fix the issue.
For sliding pages with tabs do following.
Download or copy following two files on github and paste your project.
this is same as on developers.google.com except setDistributeEvenly method.
https://github.com/google/iosched/blob/master/android/src/main/java/com/google/samples/apps/iosched/ui/widget/SlidingTabLayout.java
https://github.com/google/iosched/blob/master/android/src/main/java/com/google/samples/apps/iosched/ui/widget/SlidingTabStrip.java
activity_main.xml
<your.package.name.SlidingTabLayout
android:clickable="true"
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</your.package.name.SlidingTabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
MyAdapter.java (Here i used two pages only)
class MyPagerAdapter extends FragmentPagerAdapter
{
String[] title = {"All","Favourites"};
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
if (position==0)
fragment= new All();
if (position==1)
fragment= new Favourites();
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return title[position];
}
}
tab_view.xml (view of tab only , if you want u can also use ImageView here)
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/tab_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text=""
android:padding="15dp"
android:textStyle="bold"
android:textSize="25dp"
/>
</FrameLayout>
MainActivity.java
private SlidingTabLayout tabLayout;
private ViewPager pager;
tabLayout= (SlidingTabLayout) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
tabLayout.setCustomTabView(R.layout.tab_view,R.id.tab_title);
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
tabLayout.setDistributeEvenly(true);
tabLayout.setViewPager(pager);

How to use Navigation Drawer without duplicate code?

I have created a Navigation Drawer following a tutorial, but now I have a problem. How can I use it in multiple activities without duplicating the code?
I tried extending the main activity, but I found some problems with Toolbar. There's some other way?
Thanks, this is my code.
MainActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
class NavItem {
String mTitle;
int mIcon;
public NavItem(String title, int icon) {
mTitle = title;
mIcon = icon;
}
}
class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
public int getCount() {
return mNavItems.size();
}
public Object getItem(int position) {
return mNavItems.get(position);
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, parent, false);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.title);
ImageView iconView = (ImageView) view.findViewById(R.id.icon);
titleView.setText( mNavItems.get(position).mTitle );
iconView.setImageResource(mNavItems.get(position).mIcon);
return view;
}
}
ListView mDrawerList;
RelativeLayout mDrawerPane;
private static String TAG = MainActivity.class.getSimpleName();
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
ArrayList<NavItem> mNavItems = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavItems.add(new NavItem(getString(R.string.home), R.drawable.ic_action_home));
mNavItems.add(new NavItem(getString(R.string.company), R.drawable.ic_action_company));
mNavItems.add(new NavItem(getString(R.string.services), R.drawable.ic_action_services));
mNavItems.add(new NavItem(getString(R.string.solutions), R.drawable.ic_action_solutions));
mNavItems.add(new NavItem(getString(R.string.case_history), R.drawable.ic_action_case_history));
mNavItems.add(new NavItem(getString(R.string.contacts), R.drawable.ic_action_contacts));
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerLayout.closeDrawer(mDrawerPane);
if (position == 0) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else if (position == 1) {
Intent intent = new Intent(getApplicationContext(), CompanyActivity.class);
startActivity(intent);
}
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Log.d(TAG, "onDrawerClosed: " + getTitle());
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item);
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
}
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true" >
<RelativeLayout
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"
app:layout_behavior="#string/appbar_scrolling_view_behavior" >
<ImageView
android:contentDescription="#string/app_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/logo" />
</RelativeLayout>
<include layout="#layout/side_menu" />
<include layout="#layout/toolbar" />
</android.support.design.widget.CoordinatorLayout>
side_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" >
<RelativeLayout
android:id="#+id/mainContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<RelativeLayout
android:layout_width="280dp"
android:layout_height="match_parent"
android:id="#+id/drawerPane"
android:layout_gravity="start">
<ListView
android:id="#+id/navList"
android:layout_width="280dp"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:background="#FFF" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
toolbar.xml:
<android.support.design.widget.AppBarLayout 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="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay" >
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
Create a baseactivity with your drawer inside and then extend base activity to all activities in which you want drawer.
And instead of calling setcontentview() in oncreate inheriting activities use layout inflator
Check this post
How to Display Navigation Drawer in all activities?
Here is part of real code from my project. #Bind is from awesome Butterknife library. AbstractToolbarActivity it's a sub class of the AppCompatActivity that follows the same logic (avoiding duplicating code of initializing toolbars)
public abstract class AbstractDrawerActivity extends AbstractToolbarActivity {
#Bind(R.id.drawer_layout) DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mDrawerToggle;
protected void initDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open,
R.string.drawer_close);
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
}
#Override protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
initDrawer();
mDrawerToggle.syncState();
}
#OnClick(R.id.drawer_user_name) protected void openProfile() {
final Intent profile = new Intent(this, ProfileActivity.class);
startActivity(profile);
}
// here some onclicks etc, other methods
#Override protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
}
}
#Override public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
} else {
super.onBackPressed();
}
}
#Override protected void onPause() {
super.onPause();
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawers();
}
}
}
And AbstractToolbarActivity.java:
public abstract class AbstractToolbarActivity extends AppCompatActivity {
#Bind(R.id.action_bar) Toolbar mToolbar;
#Override protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
initToolbar();
}
protected void initToolbar() {
setSupportActionBar(mToolbar);
}
}

Categories

Resources