I am learning about Fragments in Android and I have a problem with Logcat.
I have 2 Activities and 2 Fragments, with their Layouts:
PlayerActivity - PlayerFragment / activity_player - fragment_player
LibraryActivity - LibraryFragment / activity_library - fragment_library
I have a button in PlayerFragment to LibraryActivity, where I inflate LibraryFragment. The problem is when I am in LibraryFragment Logcat doesn't show anything.
This is the Intent that I use to call to LibraryActivity (This button is in PlayerFragment in the method onActivityCreated)
final Button to_library = (Button) getView().findViewById(R.id.library);
to_library.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newIntent = new Intent(getActivity(), LibraryActivity.class);
startActivity(newIntent);
}
});
LibraryActivity:
public class LibraryActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_library);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.library, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_library,
container, false);
return rootView;
}
}
}
LibraryFragment
public class LibraryFragment extends Fragment {
private final String LOG_TAG = "test";
public LibraryFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.v(LOG_TAG, "onAttach");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(LOG_TAG, "onCreate");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_library, container,
false);
Log.v(LOG_TAG, "onCreateViewLibraryFragment");
/*
* AquĆ podemos seleccionar las Views contenidas en el Layout para
* trabajar con ellas, por ejemplo con: TipoView miView = (TipoView)
* rootView.findViewById(R.id.miViewXML);
*/
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v(LOG_TAG, "onActivityCreatedLibraryFragment");
}
#Override
public void onStart() {
super.onStart();
Log.v(LOG_TAG, "onStart");
}
#Override
public void onResume() {
super.onResume();
Log.v(LOG_TAG, "onResume");
}
#Override
public void onPause() {
super.onPause();
Log.v(LOG_TAG, "onPause");
}
#Override
public void onStop() {
super.onStop();
Log.v(LOG_TAG, "onStop");
}
#Override
public void onDestroyView() {
super.onDestroyView();
Log.v(LOG_TAG, "onDestroyView");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.v(LOG_TAG, "onDestroy");
}
#Override
public void onDetach() {
super.onDetach();
Log.v(LOG_TAG, "onDetach");
}
}
Here is where I have the problem.
Logcat doesn't show the message "onActivityCreatedLibraryFragment". I have the methods onStart(), onResume(), onStop(), etc., with their "Log.v" and I have the same problem.
Thank you in advance for your help.
activity_library.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.jgutierrezgil.bmusic.LibraryActivity"
tools:ignore="MergeRootFrame" />
fragment_library.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.jgutierrezgil.bmusic.LibraryActivity$PlaceholderFragment" >
</RelativeLayout>
EDIT 1: I have completed the code of LibraryFragment and I have added activity_library.xml and fragment_library.xml
It looks like you never actually add LibraryFragment to your code. You are only adding PlaceholderFragment, which is leftover from the tutorial you did.
In the onCreate() of your LibraryActivity, make the following changes:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_library);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
//.add(R.id.container, new PlaceholderFragment()).commit();
.add(R.id.container, new LibraryFragment()).commit();
}
}
The PlaceholderFragment is defined at the bottom of LibraryActivity and is meant as a dummy. The reason the proper layout is showing up is because you changed the inputted layout file to R.layout.fragment_library for the PlaceholderFragment, giving the appearance that it inflated the proper Fragment.
Related
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 :)
Could guys hep me integrate Startapp network in this activity, this is my code it has not the oncreate method i tried to integrate it but i failed. Please help me. You can find below the code and it does not contain the oncreate method.Im new to coding and i tried lot of time to solve this problem it's easy for me if the oncreate method is there i can integrate the ad network easy. Pleas guys any idea to deal with will help me. Thank you
public class MainFragment extends Fragment {
public MainFragment() {
// Required empty public constructor
}
private final String TAG = "MainFragment";
Activity activity;
AdView bannerAdView;
boolean isAdLoaded;
CardView cardVideoToGIF, cardImagesToGIF, cardCaptureImage, cardVideoToAudio, cardVideoCutter, cardGallery;
LinearLayout linearRow2;
private String SELECTED_TYPE = Constants.TYPE_GIF;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onResume() {
super.onResume();
if (bannerAdView != null) {
bannerAdView.resume();
}
((MainActivity) activity).setTitle("");
((MainActivity) activity).setDrawerState(true);
if (!MyApplication.isFFmpegSupports) {
linearRow2.setVisibility(View.GONE);
}
}
#Override
public void onPause() {
if (bannerAdView != null) {
bannerAdView.pause();
}
super.onPause();
}
#Override
public void onDestroy() {
if (bannerAdView != null) {
bannerAdView.destroy();
}
super.onDestroy();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
cardVideoToGIF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopupMenu(cardVideoToGIF);
SELECTED_TYPE = Constants.TYPE_GIF;
}
});
Replace your code with the following
public class MainFragment extends Fragment {
// Add these lines of code which is the onCreate method of your Fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// put your integration code here
Log.i("MainFragment", "onCreate()");
}
public MainFragment() {
// Required empty public constructor
}
private final String TAG = "MainFragment";
Activity activity;
AdView bannerAdView;
boolean isAdLoaded;
CardView cardVideoToGIF, cardImagesToGIF, cardCaptureImage, cardVideoToAudio, cardVideoCutter, cardGallery;
LinearLayout linearRow2;
private String SELECTED_TYPE = Constants.TYPE_GIF;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onResume() {
super.onResume();
if (bannerAdView != null) {
bannerAdView.resume();
}
((MainActivity) activity).setTitle("");
((MainActivity) activity).setDrawerState(true);
if (!MyApplication.isFFmpegSupports) {
linearRow2.setVisibility(View.GONE);
}
}
#Override
public void onPause() {
if (bannerAdView != null) {
bannerAdView.pause();
}
super.onPause();
}
#Override
public void onDestroy() {
if (bannerAdView != null) {
bannerAdView.destroy();
}
super.onDestroy();
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
cardVideoToGIF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPopupMenu(cardVideoToGIF);
SELECTED_TYPE = Constants.TYPE_GIF;
}
});
How to add action bar in YouTube player?
I'm trying to add action bar in this activity, but because it's not extended to AppCompatActivity that's why I'm getting an error in getSupportActionBar();. I'm also getting error if I replace the YouTubeBaseActivity with AppCompatActivity. Can anyone help me with this?
public class ActivityPlayer extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public String DEVELOPER_KEY = "key";
public String YOUTUBE_VIDEO_CODE = "5z-Roo_NpI4";
private static final int RECOVERY_DIALOG_REQUEST = 1;
YouTubePlayerView youTubeView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
setContentView(R.layout.activity_main);
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubeView.initialize(DEVELOPER_KEY, this);
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return true;
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
Snackbar.make(youTubeView, "There was an error initializing the video player.", Snackbar.LENGTH_LONG).setDuration(5000).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.loadVideo(YOUTUBE_VIDEO_CODE);
player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
#Override
public void onBackPressed() {
finish();
}
private YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_player);
}
}
I had the same Problem with you, I'm posting an answer in case you or others still need a work around. Forget about YoutubeBaseActivity and focus on YoutubePlayerSupportFragment because Fragment let you setup your Activity as you wish. There is YoutubePlayerFragment also but the Support version of it work better with android support libraries.
Here's is the Steps I used :
Make your activity Extends AppCompatActivity
public class ActivityPlayer extends AppCompatActivity {
Add a FrameLayout in xml layout of the Current Activity that extends AppCompatActivity (activity_main.xml)
<FrameLayout
android:id="#+id/flYoutube"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:visibility="visible" />
Create a YoutubeFragment extends Fragment, with fragment_youtube.xml layout and a FrameLayout inside of it. And in onCreateView, create a YoutubePlayerSupportFragment instance and replace the FrameLayout within the fragment_youtube.xml with that instance of YoutubePlayerSupportFragment.
public class YoutubeFragment extends Fragment {
private static final String YOUTUBE_API_KEY = "8S7K4hEVhgOQ87501j-FAKE-KEY";
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String VIDEO_ID = "VIDEO_ID";
// TODO: Rename and change types of parameters
private String videoId;
public YoutubeFragment() {
// Required empty public constructor
}
public static YoutubeFragment newInstance(String videoId) {
YoutubeFragment fragment = new YoutubeFragment();
Bundle args = new Bundle();
args.putString(VIDEO_ID, videoId);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
videoId = getArguments().getString(VIDEO_ID);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_youtube, container, false);
YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.flYoutubePlayer, youTubePlayerFragment).commit();
youTubePlayerFragment.initialize(YOUTUBE_API_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider arg0, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
//youTubePlayer.setFullscreen(true);
youTubePlayer.loadVideo(videoId);
//yoTubePlayer.play();
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
// TODO Auto-generated method stub
}
});
return rootView;
}
}
Create a 2nd FrameLayout in fragment_youtube.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="jfsl.ayibopost.fragments.YoutubeFragment">
<FrameLayout
android:id="#+id/flYoutubePlayer"
android:layout_width="match_parent"
android:layout_height="200dp"></FrameLayout>
</RelativeLayout>
Last thing to do in PlayerActivity onCreate(), is to create an instance of your own created YoutubeFragment and replace the Frame Layouts within the activity_main.xml with that YoutubeFragment instance via Fragment Transaction:
// Create Youtube Fragment instance by passing a Youtube Video ID
YoutubeFragment youtubeFragment = YoutubeFragment.newInstance("2zNSgSzhBfM");
getSupportFragmentManager().beginTransaction()
.replace(R.id.flYoutube, youtubeFragment).commit();
And you are done.
You should implement an AppCompatCallback interface.
Please, see my answer.
I have a fragment which displays a mapview.
I have to inflate a menu layout from the fragment and I have added setHasOptionsMenu(true) in the code so that menu bar can inflated from the fragment.
But the interesting thing is that it doesn't show up when the fragment loads the first time. But if I switch over to some other fragment and comes back to this fragment the menu bar show up again. I have no idea why doesn't it show up in the first place.
What needs to be done ? Can some one help ?
The following is the content of the fragment layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
This is the java class.
public class SearchFragment extends Fragment implements GoogleMap.InfoWindowAdapter,
GoogleMap.OnInfoWindowClickListener, LocationListener, OnMapReadyCallback {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i(TAG, "onCreateView()");
rootView = inflater.inflate(R.layout.fragment_search, container, false);
setHasOptionsMenu(true);
MapsInitializer.initialize(this.getActivity());
mMapView = (MapView) rootView.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
this.markers = new HashMap<>();
this.activity = (MainActivity) this.getActivity();
return rootView;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
Log.i(TAG, "onCreateOptionsMenu()");
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
this.activity.getMenuInflater().inflate(R.menu.menu_search, menu);
}
#Override
public void onMapReady(GoogleMap map) {
Log.i(TAG, "onMapReady");
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
try {
if (checkScanPermissions()) {
map.setMyLocationEnabled(true);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(getLocation(), 18));
}
} catch (SecurityException e) {
Log.e(TAG, "Permission to location not granted");
}
map.setBuildingsEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
map.setInfoWindowAdapter(this);
map.setOnInfoWindowClickListener(this);
this.mMap = map;
setUpMap(false);
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate()");
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.i(TAG, "onSaveInstanceState()");
super.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
Log.i(TAG, "onLowMemory()");
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void onResume() {
Log.i(TAG, "onResume()");
super.onResume();
setHasOptionsMenu(true);
mMapView.onResume();
}
}
Have You tried to remove menu.clear(); from onCreateOptionsMenu?
This line:
setHasOptionsMenu(true);
is in the wrong method. Should be in onCreate instead.
add this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
I want to build an android application with a Fragment which contains a List of Option and if I click on one of this option, I can see, another fragment with other option.
So I build this:
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:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.MainActivity"
tools:ignore="MergeRootFrame" >
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="480dp"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation_drawer" >
<ListView
android:id="#+id/left_list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:background="#6dc659"
android:foreground="#color/white">
</ListView>
<fragment
android:id="#+id/navigation_drawer"
android:name="it.eresult.decipher.fragment.NavigationDrawerFragment"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation_drawer" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
This is the MainActivity.java
public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks{
private DrawerLayout drawer;
private ListView leftList;
private String[] leftListStrings;
private String[] rightListStrings;
private NavigationDrawerFragment mNavigationDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
leftList = (ListView) findViewById(R.id.left_list);
leftListStrings = getResources().getStringArray(R.array.principal_menu);
leftList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,leftListStrings));
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
leftList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
arg1.setBackgroundColor(getResources().getColor(R.color.selected_menu_option));
if(arg2 == 0){
}
}
});
drawer.setDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDrawerSlide(View arg0, float arg1) {
// TODO Auto-generated method stub
}
#Override
public void onDrawerOpened(View arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDrawerClosed(View arg0) {
// TODO Auto-generated method stub
//rightList.setVisibility(View.INVISIBLE);
}
});
}
#Override
public void onNavigationDrawerItemSelected(int position) {
//TODO
}
class MayAdapter extends ArrayAdapter<String>{
List<String> myList = null;
public MayAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
myList = objects;
}
public List<String> getMyList() {
return myList;
}
public void setMyList(List<String> myList) {
this.myList = myList;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle("omnia");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
This is NavigationDrawerFragment.java
public class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
Toolbar toolBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
}
// Select the default item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// the fragment has menu items to contribute
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.social_history),
getString(R.string.encounter),
getString(R.string.problems),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
private ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(),
mDrawerLayout,
null,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu();
}
};
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(true);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}
}
With this code, if I try to run my application, I can see the complete menu like this
Instead, I want to see only the left menu, and if I click on one items, see the right menu