menu not created when fragment is created but works on resume - java

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);
}

Related

What is the function that can be used instead of "this" in "Fragment"?

I'm implementing the autocomplete suggestion code in Google map place api.
We are using OnMapReadyCallback as an implement.
The MapView.getMapAsync(this) function was originally used in onCreateView. But now I'm going to use it in setupAutoCompleteFragment. However, in MapView.getMapAsync(this), it is not compiled due to this. What can be used?
public class googlemaptab extends Fragment implements OnMapReadyCallback {
MapView mapview;
Button kakaobutton;
public static googlemaptab newInstance(){
return new googlemaptab();
}
public googlemaptab() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_googlemaptab, container, false);
kakaobutton = (Button)view.findViewById(R.id.kakaobutton);
mapview = (MapView)view.findViewById(R.id.google_map_view);
setupAutoCompleteFragment();
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
kakaobutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//클릭하면 카카오maptab으로 이동하겠다.
((MainActivity)getActivity()).replaceFragment(kakaomaptab.newInstance());
}
});
}
#Override
public void onStart() {
super.onStart();
mapview.onStart();
}
#Override
public void onResume() {
super.onResume();
mapview.onResume();
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(mapview != null)
{
mapview.onCreate(savedInstanceState);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng SEOUL = new LatLng(37.56, 126.97);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(SEOUL);
markerOptions.title("서울");
markerOptions.snippet("수도");
googleMap.addMarker(markerOptions);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(SEOUL));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(13));
}
private void setupAutoCompleteFragment() {
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)getActivity().
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
mapview.getMapAsync(this);
}
#Override
public void onError(Status status) {
Log.e("Error", status.getStatusMessage());
}
});
}
}
You could do it better this way
private void setupAutoCompleteFragment(OnMapReadyCallback instance) {
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)getActivity().
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
mapview.getMapAsync(instance);
}
#Override
public void onError(Status status) {
Log.e("Error", status.getStatusMessage());
}
});
}
And don't forget to update your onCreateView with the new function signature as the following:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_googlemaptab, container, false);
kakaobutton = (Button)view.findViewById(R.id.kakaobutton);
mapview = (MapView)view.findViewById(R.id.google_map_view);
setupAutoCompleteFragment(this);
return view;
}
You can use Classname.this in this case.
For example: if your fragment name is HomeFragment then,
HomeFragment.this
If this still doesn't work then you can override onViewCreated() function and call mapView.getMapAsync(this) inside onViewCreated()
If needed check this link
have you tried with mapview.getMapAsync(getActivity()); instead of mapview.getMapAsync(this);

startapp ads not working

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 app bar in YouTube player activity?

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.

Android ListView with detail page null object

I am creating a listview from the contents of my api, if I click on a listview item I want to show a new view with more details for that clicked item, currently the listview gets shown properly but if I click on an item the app crashed and I get this error message:
> java.lang.RuntimeException: Unable to start activity
> ComponentInfo{de.dev.app/de.dev.app.ui.quote.ArticleDetailActivity}:
> java.lang.NullPointerException: Attempt to invoke virtual method
> 'java.lang.String de.dev.app.jokeapp.entities.Joke.getTitle()' on a null
> object reference ... Caused by: java.lang.NullPointerException:
> Attempt to invoke virtual method 'java.lang.String
> de.dev.app.entities.Joke.getTitle()' on a null object reference
> at
> de.dev.app.ui.quote.ArticleDetailFragment.onCreateView(ArticleDetailFragment.java:100)
The error points to this lines in my ArticleDetailFragment.java:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflateAndBind(inflater, container, R.layout.fragment_article_detail);
if (!((BaseActivity) getActivity()).providesActivityToolbar()) {
((BaseActivity) getActivity()).setToolbar((Toolbar) rootView.findViewById(R.id.toolbar));
}
collapsingToolbar.setTitle(jokeItem.getTitle()); // points here
author.setText(jokeItem.getTitle());
quote.setText(jokeItem.getTitle());
jokeHeader.setText(jokeItem.getTitle());
jokeContent.setText(jokeItem.getContent());
return rootView;
}
This is my onAttach method:
#Override
public void onAttach(Context context) {
super.onAttach(context);
Bundle bundle = getArguments();
if(bundle == null) {
getActivity().finish();
return;
}
jokeItem = (Joke)bundle.getSerializable("joke");
}
This is my ArticleDetailFragment looks like:
public class ArticleDetailFragment extends BaseFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// load dummy item by using the passed item ID.
dummyItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
}
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
tokenManager = TokenManager.getInstance(preferences);
service = RetrofitBuilder.createServiceWithAuth(ApiService.class, tokenManager);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflateAndBind(inflater, container, R.layout.fragment_article_detail);
if (!((BaseActivity) getActivity()).providesActivityToolbar()) {
// No Toolbar present. Set include_toolbar:
((BaseActivity) getActivity()).setToolbar((Toolbar) rootView.findViewById(R.id.toolbar));
}
collapsingToolbar.setTitle(jokeItem.getTitle());
author.setText(jokeItem.getTitle());
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.sample_actions, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// your logic
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Bundle bundle = getArguments();
if(bundle == null) {
getActivity().finish();
return;
}
jokeItem = (Joke)bundle.getSerializable("joke");
}
}
My ArticleDetailActivity
public class ArticleDetailActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
ArticleDetailFragment fragment = ArticleDetailFragment.newInstance(getIntent().getStringExtra(ArticleDetailFragment.ARG_ITEM_ID));
getFragmentManager().beginTransaction().replace(R.id.article_detail_container, fragment).commit();
}
#Override
public boolean providesActivityToolbar() {
return false;
}
}
Calling the ArticleDetailActivity in my ListActivit like this:
public class ListActivity extends BaseActivity implements ArticleListFragment.Callback {
...
#Override
public void onItemSelected(Joke joke) {
Intent detailIntent = new Intent(this, ArticleDetailActivity.class);
// detailIntent.putExtra(ArticleDetailFragment.ARG_ITEM_ID, id);
startActivity(detailIntent);
}
...
Call DetailActivity like this from your ListActvity,
Intent detailIntent = new Intent(this, ArticleDetailActivity.class);
// detailIntent.putExtra(ArticleDetailFragment.ARG_ITEM_ID, id);
Bundle bundle = new Bundle();
bundle.putSerializable("joke", joke);
detailIntent.putExtras(bundle);
startActivity(detailIntent);
and change your ArticleDetailActivity change like this, we need to send data to fragment
public class ArticleDetailActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
// Show the Up button in the action bar.
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
ArticleDetailFragment fragment = new ArticleDetailFragment();
fragment.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().replace(R.id.article_detail_container, fragment).commit();
}
#Override
public boolean providesActivityToolbar() {
return false;
}
}
Add this line of code to your ArticleDetailFragment class
#BindView(R.id.title)
TextView title;

Logcat doesn't show anything of a fragment

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.

Categories