play song in fragment - java

Hello in my project I am to play a song when I click on a button and this button is is a fragment layout but I don't now if I need to put the code in the fragment or in the MainActivity. So here I put it in the fragment and the "protected" of the protected void is underline in red same for the "(this, resId)". Can someone help thanks a lot.
here is my fragment.java
public class thekairi78 extends Fragment {
private AdView adView;
private MediaPlayer mPlayer = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.thekairi78, container,
false);
Button regarde = (Button) getView().findViewById(R.id.regarde);
regarde.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playSound(R.raw.regarde);
}
});
adView = new AdView(getActivity());
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
adView.setAdSize(AdSize.SMART_BANNER);
LinearLayout layout = (LinearLayout) rootView.findViewById(R.id.layout_admob);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
return rootView;
}
#Override
protected void onPause() {
if(mPlayer != null && mPlayer.isPlaying()){
mPlayer.pause();
}
super.onPause();
}
private void playSound(int resId){
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
mPlayer = MediaPlayer.create(this, resId);
mPlayer.start();
}
}
and here my MainActivity.java
public class MainActivity extends AppCompatActivity {
private MediaPlayer mPlayer = null;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
InterstitialAd mInterstitialAd;
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdRequest adRequest = new AdRequest.Builder().build();
interstitial = new InterstitialAd(MainActivity.this);
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
displayInterstitial();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
thekairi78 tab1 = new thekairi78();
return tab1;
case 1:
kenny tab2 = new kenny();
return tab2;
case 2:
autres tab3 = new autres();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "TheKairi78";
case 1:
return "Kenny";
case 2:
return "Autres SoundBox";
}
return null;
}
}
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
#Override
protected void onPause() {
if(mPlayer != null && mPlayer.isPlaying()){
mPlayer.pause();
}
super.onPause();
}
private void playSound(int resId){
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
mPlayer = MediaPlayer.create(this, resId);
mPlayer.start();
}
}

Related

Error to retrieve image from firebase for recycler view in fragment

I want to retrieve image for recycler view in fragment
code of MovieActivity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
Intent intent = new Intent(this, LoadingActivity.class);
startActivity(intent);
setupViewFragment();
}
setupToolbar();
setupBottomNavigation();
}
private void setupViewFragment() {
// show discover movies fragment by default
DiscoverMoviesFragment discoverMoviesFragment = DiscoverMoviesFragment.newInstance();
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), discoverMoviesFragment, R.id.fragment_container);
}
private void setupBottomNavigation() {
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_home:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), HomeFragment.newInstance(),
R.id.fragment_container);
//startActivity(new Intent(getApplicationContext()
//,HomeActivity.class));
return true;
case R.id.action_discover:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), DiscoverMoviesFragment.newInstance(),
R.id.fragment_container);
return true;
case R.id.action_favorites:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), FavoritesFragment.newInstance(),
R.id.fragment_container);
return true;
}
return false;
}
});
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
`
code for HomeFragment :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
Intent intent = new Intent(this, LoadingActivity.class);
startActivity(intent);
setupViewFragment();
}
setupToolbar();
setupBottomNavigation();
}
private void setupViewFragment() {
// show discover movies fragment by default
DiscoverMoviesFragment discoverMoviesFragment = DiscoverMoviesFragment.newInstance();
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), discoverMoviesFragment, R.id.fragment_container);
}
private void setupBottomNavigation() {
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_home:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), HomeFragment.newInstance(),
R.id.fragment_container);
//startActivity(new Intent(getApplicationContext()
//,HomeActivity.class));
return true;
case R.id.action_discover:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), DiscoverMoviesFragment.newInstance(),
R.id.fragment_container);
return true;
case R.id.action_favorites:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), FavoritesFragment.newInstance(),
R.id.fragment_container);
return true;
}
return false;
}
});
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
code for HomeAdapter :
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
private OnItemClickListener mListener;
public HomeAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.get()
.load(uploadCurrent.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.centerInside()
.fit()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
doWhatever.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onWhatEverClick(position);
return true;
case 2:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener {
void onItemClick(int position);
void onWhatEverClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
}
this is the error :
`C:\Users\User\Desktop\PopularMovies\app\src\main\java\com\ajdi\yassin\popularmovies\ui\movieslist\home\HomeFragment.java:65: error: incompatible types: HomeFragment cannot be converted to Context
mAdapter = new HomeAdapter(HomeFragment.this, mUploads);`
Please use getApplicationContext() ,because HomeFragment.this is consider as an Activity and in your HomeAdapter constructor you have passed Context.
Replace:
mAdapter = new HomeAdapter(HomeFragment.this, mUploads);
To:
mAdapter = new HomeAdapter(getApplicationContext(), mUploads);

How to close Unity without closing the entire app when changing fragments in Android Studio?

I have an app that the user can go through different fragments using BottomNavigationView and one of those fragments is a Unity3D application. So when i open the Unity fragment it works but when i open another fragment and open the Unity fragment back it crashes how do i fix this here is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
BottomNavigationView mBottomNavigationView;
NavController mNavController;
NavDestination mDestination;
AppBarConfiguration appBarConfiguration;
String tab;
private boolean doubleBackToExitPressedOnce ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean b = this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_main);
ActionBar mActionBar = getSupportActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater li = LayoutInflater.from(this);
View customView = li.inflate(R.layout.top_menu_custom, null);
mActionBar.setCustomView(customView);
mActionBar.setDisplayShowCustomEnabled(true);
mBottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
ImageButton profileButton = (ImageButton) customView.findViewById(R.id.profile_button);
ImageButton notificationButton = (ImageButton) customView.findViewById(R.id.noti_button);
profileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment profileFragment = new ProfileFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,profileFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
notificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NotificationFragment notificationFragment = new NotificationFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,notificationFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
mBottomNavigationView.setItemIconTintList(null);
mBottomNavigationView.setItemTextColor(ColorStateList.valueOf(getColor(R.color.black)));
mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard,R.id.navigation_map, R.id.navigation_card,R.id.navigation_deals)
.build();
NavigationUI.setupActionBarWithNavController(this, mNavController, appBarConfiguration);
NavigationUI.setupWithNavController(mBottomNavigationView, mNavController);
mNavController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
Toast.makeText(getApplicationContext(),"hi",Toast.LENGTH_SHORT).show();
mDestination = mNavController.getCurrentDestination();
tab = mDestination.toString();
}
});
}
#Override
public void onBackPressed() {
//Toast.makeText(getApplicationContext(), mDestination.toString(),Toast.LENGTH_SHORT).show();
if (doubleBackToExitPressedOnce) {
getSupportFragmentManager().popBackStackImmediate();
mNavController.navigate(mDestination.getId());
mBottomNavigationView.setVisibility(View.VISIBLE);
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
UnityMapFragment
public class MapFragment extends Fragment{
protected UnityPlayer mUnityPlayer;
FrameLayout frameLayoutForUnity;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mUnityPlayer = new UnityPlayer(getActivity());
View view = inflater.inflate(R.layout.fragment_map, container, false);
this.frameLayoutForUnity = (FrameLayout) view.findViewById(R.id.frameLayoutForUnity);
this.frameLayoutForUnity.addView(mUnityPlayer.getView(),
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
mUnityPlayer.requestFocus();
mUnityPlayer.windowFocusChanged(true);
return view;
}
#Override
public void onPause() {
super.onPause();
mUnityPlayer.pause();
}
#Override
public void onResume() {
super.onResume();
mUnityPlayer.resume();
}
// Quit Unity
#Override
public void onDestroy ()
{
mUnityPlayer.quit();
super.onDestroy();
}
So I managed to make a solution for this problem don't know if its good to make it this way or not but what i did was I instantiate the UnityPlayer in my MainActivity and in my fragment i call upon the UnityPlayer that was instatiated in my Main Activity.
MainActivity.java
public class MainActivity extends AppCompatActivity {
public BottomNavigationView mBottomNavigationView;
public NavController mNavController;
public NavDestination mDestination;
AppBarConfiguration appBarConfiguration;
String tab;
int onBackTimes = 0;
public UnityPlayer mUnityPlayer; <----Call unity player
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUnityPlayer = new UnityPlayer(this); <----UNITY PLAYER HERE
boolean b = this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_main);
ActionBar mActionBar = getSupportActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater li = LayoutInflater.from(this);
View customView = li.inflate(R.layout.top_menu_custom, null);
mActionBar.setCustomView(customView);
mActionBar.setDisplayShowCustomEnabled(true);
mBottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
ImageButton profileButton = (ImageButton) customView.findViewById(R.id.profile_button);
ImageButton notificationButton = (ImageButton) customView.findViewById(R.id.noti_button);
profileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment profileFragment = new ProfileFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,profileFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
notificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NotificationFragment notificationFragment = new NotificationFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,notificationFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
mBottomNavigationView.setItemIconTintList(null);
mBottomNavigationView.setItemTextColor(ColorStateList.valueOf(getColor(R.color.black)));
mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard,R.id.navigation_map, R.id.navigation_card,R.id.navigation_deals)
.build();
NavigationUI.setupActionBarWithNavController(this, mNavController, appBarConfiguration);
NavigationUI.setupWithNavController(mBottomNavigationView, mNavController);
mNavController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
mDestination = mNavController.getCurrentDestination();
tab = mDestination.toString();
}
});
}
#Override
public void onBackPressed() {
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
onBackTimes +=1;
if(onBackTimes>1){
LoginActivity.close.finish();
finish();
}
else{
getSupportFragmentManager().popBackStackImmediate();
mBottomNavigationView.setVisibility(View.VISIBLE);
super.onBackPressed();
mNavController.navigate(mDestination.getId());
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
onBackTimes=0;
}
}, 2000);
}
#Override
protected void onStop() {
super.onStop();
}
//UNITY STUFF OVER HERE
#Override
protected void onPause() {
super.onPause();
mUnityPlayer.pause();
}
#Override protected void onResume()
{
super.onResume();
mUnityPlayer.resume();
}
#Override
protected void onDestroy(){
super.onDestroy();
}
}
UnityMapFragment
public class MapFragment extends Fragment{
private MainActivity mUnityMainActivity;
private UnityPlayer mUnityPlayer;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//this code calls the UNITYPLAYER from MainActivity and return it here
mUnityMainActivity = (MainActivity) getActivity();
View unityPlayViewer = mUnityMainActivity.mUnityPlayer.getView();
mUnityMainActivity.mUnityPlayer.requestFocus();
mUnityMainActivity.mUnityPlayer.windowFocusChanged(true);
return unityPlayViewer;
}
/** FOR UNITY **/
#Override
public void onPause() {
super.onPause();
mUnityMainActivity.mUnityPlayer.pause();
}
// Resume Unity
#Override public void onResume()
{
super.onResume();
mUnityMainActivity.mUnityPlayer.resume();
}
I don't know why i have to include the OnPause, OnResume etc on both file but if one of them doesn't have it it'll crash.
The problem is, a new UnityPlayer is being created every-time we switch to the unity fragment and this crashes the app. So we need to create the UnityPlayer only for the first time or only when the player has been stopped. This works on my side.
In the UnityFragment class, my global variables :
protected UnityPlayer mUnityPlayer;
private View view;
private FrameLayout frameLayoutForUnity;
In onCreate a new UnityPlayer is created, which is called only for the first time :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUnityPlayer = new UnityPlayer(getActivity()); // create Unity Player
}
In onCreateView we refresh the view for UnityPlayer :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(mUnityPlayer.getParent() != null){
((ViewGroup)mUnityPlayer.getParent()).removeAllViews();
}
view = inflater.inflate(R.layout.fragment_unity, container, false);
this.frameLayoutForUnity = (FrameLayout) view.findViewById(R.id.unityFragmentLayout);
this.frameLayoutForUnity.addView(mUnityPlayer.getView(),
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
mUnityPlayer.requestFocus();
mUnityPlayer.windowFocusChanged(true);
return view;
}
Rest remains same. There could be better solutions than this. Cheers :)

Interaction between fragments in Tabbed activity

I am trying a simple interaction between two fragments in Tabbed activity.
I have a two layouts with TextView, EditText and Button. I am trying to achieve move text from EditText in FragmentOne to the EdidText (or TextView) in Fragment two when the Button from FragmentOne is pressed. But it doesnt works.
During debuging there isnt any problem. App doesnt stop working.
Is something problem in ViewPager or SectionsPagerAdapter?
I have this two fragments.
Fragments One:
public class FragmentOne extends Fragment {
TextView textView;
EditText editText;
Button button;
private OnFragmentOneInteractionListener mListener;
public FragmentOne()
{
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_one, container, false);
editText = (EditText) view.findViewById(R.id.fragOne_txb);
textView = (TextView) view.findViewById(R.id.fragTwo_header);
button = (Button) view.findViewById(R.id.fragOne_btn_to2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String text = editText.getText().toString();
mListener.onFragmentOneInteraction(text);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentOneInteractionListener) {
mListener = (OnFragmentOneInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentOneInteractionListener");
}
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnFragmentOneInteractionListener
{
void onFragmentOneInteraction(String string);
}
}
And fragments two:
public class FragmentTwo extends Fragment{
private OnFragmentTwoInteractionListener mListener;
public EditText editText;
public FragmentTwo()
{
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_two, container, false);
editText = (EditText) view.findViewById(R.id.fragTwo_txb);
return view;
}
public void onUpdateEditText(String string)
{
this.editText.setText(string);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentTwoInteractionListener) {
mListener = (OnFragmentTwoInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentTwoInteractionListener");
}
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnFragmentTwoInteractionListener
{
void onFragmentTwoInteraction(Uri uri);
}
}
And this is my main activity:
public class MainActivity extends AppCompatActivity
implements FragmentOne.OnFragmentOneInteractionListener,
FragmentTwo.OnFragmentTwoInteractionListener
{
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public void onFragmentOneInteraction(String string)
{
FragmentTwo fr2 = (FragmentTwo) getSupportFragmentManager().findFragmentById(R.id.fr2);
fr2.onUpdateEditText(string);
}
#Override
public void onFragmentTwoInteraction(Uri uri)
{
}
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position)
{
case 0:
FragmentOne fragmentOne = new FragmentOne();
return fragmentOne;
case 1:
FragmentTwo fragmentTwo = new FragmentTwo();
return fragmentTwo;
default:
return null;
}
}
#Override
public int getCount()
{
// Show 2 total pages.
return 2;
}
}
}
I just tried your code and this is the update i did to make it work. Please mark it correct if its what you are looking for
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
#Override
public void onFragmentOneInteraction(String string)
{
fragmentTwo.onUpdateEditText(string);
/*FragmentTwo fr2 = (FragmentTwo) getSupportFragmentManager().findFragmentById(R.id.fr2);
fr2.onUpdateEditText(string);*/
}
#Override
public void onFragmentTwoInteraction(Uri uri)
{
}
FragmentTwo fragmentTwo = new FragmentTwo();
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position)
{
case 0:
FragmentOne fragmentOne = new FragmentOne();
return fragmentOne;
case 1:
return fragmentTwo;
default:
return null;
}
}
#Override
public int getCount()
{
// Show 2 total pages.
return 2;
}
}
I suggest to use getActivity() instead
if (getActivity() instanceof OnFragmentOneInteractionListener) {
mListener = (OnFragmentOneInteractionListener) getActivity();
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentOneInteractionListener");
}

How to make FloatingActionButton take you to specific tab in Tab Layout

I have a FloatingActionButton in my android navigation drawer with tablayout which displays the following message :
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
homeFragment();
SnackBarMessage("Go To Inbox.");
}
});
using snackbar
public void SnackBarMessage(String message){
Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
let's say I have 3 tabs e.g (tab 0 ,tab 1 , tab 2)
how can I make the Floating action button take me to tab 2 once I click on it
This is the fragment containing the tabs
public class HomeFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager mViewPager;
private OnFragmentInteractionListener mListener;
private SectionsPagerAdapter mSectionsPagerAdapter;
ArrayList<String> tabName;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
mViewPager = (ViewPager)view.findViewById(R.id.container);
tabName=new ArrayList<String>();
int [] tabIcons = {
R.drawable.ic_home,
R.drawable.ic_move_to_inbox,
R.drawable.ic_notifications,
R.drawable.ic_swap_horiz,
R.drawable.ic_people,
};
String[] strings = { "Main Page Goes Here", "Messages Go Here", "Notifications Go Here", "Trade Page Goes Here", "People Online Page Goes Here"};
for(int i=0;i<5;i++){
tabLayout.addTab(tabLayout.newTab().setIcon(tabIcons[i]));
tabName.add((strings[i]));
}
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
getChildFragmentManager().beginTransaction().addToBackStack(null).commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Note that we are passing childFragmentManager, not FragmentManager
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#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;
}
#Override
public void onResume() {
super.onResume();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
To be able to do this from another Fragment you will need to send a something in a Bundle, such as the position of the page, then do something like this:
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putInt(YOUR_PAGE, youPage);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack("Name").commit();
Then in your HomeFragment:
Bundle bundle = this.getArguments();
if (bundle != null) { viewPager.setCurrentItem(bundle.getInt(YOUR_PAGE) }

Going back from a fragment to the previous which have viewpager

I am developing an app which have a single activity and several fragments.
The first fragment contains a viewpager which have 3-4 fragments extra. I can switch from one fragment to another easily and the viewpager works fine, but when i am going back from one fragment to the first(not in viewpager), the viewpager is not loading all fragments. Below is the code:
mainactivity.java
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private String[] mOptionMenu;
private DrawerLayout mDrawerLayout;
private DrawerLayout loginlayout;
private RelativeLayout mDrawerRelativeLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitleSection;
private CharSequence mTitleApp;
private Fragment mFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1= (Button) findViewById(R.id.button1);
Button btn2= (Button) findViewById(R.id.button2);
Button login= (Button) findViewById(R.id.login);
Button about= (Button) findViewById(R.id.about);
about.setOnClickListener(this);
login.setOnClickListener(this);
btn2.setOnClickListener(this);
btn1.setOnClickListener(this);
FontChangeCrawler fontChanger = new FontChangeCrawler(getAssets(), "fonts/font.ttf");
fontChanger.replaceFonts((ViewGroup)this.findViewById(android.R.id.content));
if (findViewById(R.id.content_frame) != null) {
if (savedInstanceState != null) {
return;
}
FirstFragment firstFragment = new FirstFragment();
firstFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().addToBackStack(null)
.add(R.id.content_frame, firstFragment).commit();
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerRelativeLayout = (RelativeLayout) findViewById(R.id.left_drawer);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setCustomView(R.layout.actionbar_image);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#662e91")));
mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
}
#Override
public void onDrawerStateChanged(int newState) {
}
});
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
FirstFragment firstFragment = new FirstFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new FirstFragment()).commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
break;
case R.id.login:
callLoginDialog();
break;
case R.id.about:
about abt = new about();
abt.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame, abt).commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
break;
}
}
public class FontChangeCrawler
{
private Typeface typeface;
public FontChangeCrawler(Typeface typeface)
{
this.typeface = typeface;
}
public FontChangeCrawler(AssetManager assets, String assetsFontFileName)
{
typeface = Typeface.createFromAsset(assets, "fonts/font.ttf");
}
public void replaceFonts(ViewGroup viewTree)
{
View child;
for(int i = 0; i < viewTree.getChildCount(); ++i)
{
child = viewTree.getChildAt(i);
if(child instanceof ViewGroup)
{
// recursive call
replaceFonts((ViewGroup)child);
}
else if(child instanceof TextView)
{
// base case
((TextView) child).setTypeface(typeface);
}
}
}
}
public void callLoginDialog()
{
Dialog myDialog = new Dialog(this);
myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
myDialog.setContentView(R.layout.loginwindow);
myDialog.setCancelable(false);
TextView reg= (TextView) myDialog.findViewById(R.id.register);
Button login = (Button) myDialog.findViewById(R.id.login);
EditText emailaddr = (EditText) myDialog.findViewById(R.id.editText2);
EditText password = (EditText) myDialog.findViewById(R.id.editText3);
myDialog.show();
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Register",
Toast.LENGTH_LONG).show();
}
});
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//your login calculation goes here
}
});
myDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialog.cancel();
return true;
}
return false;
}
});
}
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
}
else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.user:
mDrawerLayout.closeDrawer(Gravity.LEFT);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
firstfragment.java
public class FirstFragment extends Fragment {
public ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first,
container, false);
viewPager = (ViewPager) rootView.findViewById(pager);
viewPager.setAdapter(new ViewPagerAdapter(getFragmentManager()));
viewPager.setCurrentItem(0);
PagerTitleStrip pagerTitleStrip= (PagerTitleStrip) rootView.findViewById(R.id.titlestrip);
pagerTitleStrip.setNonPrimaryAlpha(Float.parseFloat("0.3"));
viewPager.setPageTransformer(true, new ViewPager.PageTransformer() {
#Override
public void transformPage(View view, float position) {
final float normalizedposition = Math.abs(Math.abs(position) - 1);
view.setAlpha(normalizedposition);
}
});
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/font.ttf");
for (int counter = 0 ; counter<pagerTitleStrip.getChildCount(); counter++) {
if (pagerTitleStrip.getChildAt(counter) instanceof TextView) {
((TextView)pagerTitleStrip.getChildAt(counter)).setTypeface(font);
}
}
return rootView;
}
}
viewpageadapter.java
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 4;
// Tab Titles
private String tabtitles[] = new String[] { "Home", "Men", "Women", "Children" };
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
SecondFragment fragmenttab1 = new SecondFragment();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
ThirdFragment fragmenttab2 = new ThirdFragment();
return fragmenttab2;
case 2:
Fourthfragment fragmenttab3 = new Fourthfragment();
return fragmenttab3;
case 3:
FifthFragment fragmenttab4 = new FifthFragment();
return fragmenttab4;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
Try changing viewPager.setAdapter(new ViewPagerAdapter(getFragmentManager())); with viewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager()));

Categories