I want to create navigation drawer sub category like TOI app. So far I have done this(some part of the code):
main_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1">
</FrameLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
android:name="com.medical.medicaldialogue.Activity.FragmentDrawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener{
private static String TAG = MainActivity.class.getSimpleName();
public static int SELECTED_POSITION = 0;
private SearchView searchView;
private Toolbar toolbar;
private ImageView imageViewToolbar;
private FragmentDrawer drawerFragment;
private ArrayList<HomeSummary> summaryItemArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
summaryItemArrayList = (ArrayList<HomeSummary>)getIntent().getSerializableExtra("summaryList");
Log.d("arrayLength -", ""+summaryItemArrayList.size());
toolbar =(Toolbar)findViewById(R.id.app_bar);
imageViewToolbar = (ImageView)findViewById(R.id.app_bar_img);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position){
Bundle bundle = new Bundle();
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position){
case 0:
fragment = new EditorPicsFragment();
title = getString(R.string.title_home);
imageViewToolbar.setVisibility(View.VISIBLE);
break;
}
if(fragment != null){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
bundle.putString("myFragment",title);
if(title.equalsIgnoreCase("Title")){
bundle.putParcelableArrayList("summaryList", summaryItemArrayList);
} else if(title.equalsIgnoreCase("Editor's Pick")){
bundle.putString("cat_id", "56");
}
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the app_bar title
getSupportActionBar().setTitle(title);
PrefStore.setStoryBarTitle(MainActivity.this, title);
}
}
#Override
protected void onResume() {
super.onResume();
// displayView(0);
}
}
FragmentDrawer.java
public class FragmentDrawer extends Fragment {
private String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles= null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
// Required empty public constructor
Log.d(TAG, "Drawer fragment created 1111");
}
public void setDrawerListener(FragmentDrawerListener listener){
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData(){
List<NavDrawerItem> data = new ArrayList<>();
// Preparing navigation drawer items
for(int i=0; i<titles.length; i++){
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
/**
* Modified Date on 9/2/2016
* Resizing the Drawer width when
*/
if(position ==21) {
ViewGroup.LayoutParams params = containerView.getLayoutParams();
params.width = 250;
containerView.setLayoutParams(params);
}else {
// ViewGroup.LayoutParams params = containerView.getLayoutParams();
// params.width = 400;
// containerView.setLayoutParams(params);
mDrawerLayout.closeDrawer(containerView);
}
Log.d(TAG, "Postion clicked: "+position);
}
#Override
public void onLongClick(View view, int position) {
Log.d(TAG, "Long press");
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
Log.d("Drawer opened","");
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
// drawerListener.onDrawerItemSelected(drawerView, 4);
// toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
Log.d("syncState", "Drawer");
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener{
public void onDrawerItemSelected(View view, int position);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "Drawer fragment created onStart() 222222");
}
}
so far I am able to create navigation drawer. But I want to achieve like this
How to add sub category drawer in above code. Any help would be appreciated.
Related
I am trying to display news of different categories under different tabs using TabLayout. The corresponding fragments do not load at all, only the tabs are displayed. The app freezes when I try to scroll or select a tab such that even the tabIndicator barely moves to the corresponding tab and Android displays "Not responding" message.
MainActivity.java
public class MainActivity extends AppCompatActivity{
Toolbar toolbar;
TabLayout tabLayout;
ViewPager2 viewPager2;
NewsPagerAdapter newsPagerAdapter;
TabLayoutMediator tabLayoutMediator;
String[] tabTitles = new String[]{"HOME","BUSINESS","HEALTH","TECHNOLOGY","SPORTS"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.tbCustom);
tabLayout = findViewById(R.id.tlCategories); setSupportActionBar(toolbar);
viewPager2 = findViewById(R.id.vpNews);
newsPagerAdapter = new NewsPagerAdapter(getSupportFragmentManager(),getLifecycle());
viewPager2.setAdapter(newsPagerAdapter);
tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> tab.setText(tabTitles[position]));
tabLayoutMediator.attach();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager2.setCurrentItem(tab.getPosition());
newsPagerAdapter.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
tabLayout.selectTab(tabLayout.getTabAt(position));
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
tabLayoutMediator.detach();
viewPager2.setAdapter(null);
}
}
NewsPagerAdapter.java
public class NewsPagerAdapter extends FragmentStateAdapter {
public NewsPagerAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position)
{
case 0: return new HomeFragment();
case 1: return new BusinessFragment();
case 2: return new HealthFragment();
case 3: return new TechnologyFragment();
case 4: return new SportsFragment();
default: return null;
}
}
#Override
public int getItemCount() {
return 5;
}
}
Home Fragment.java - Other fragments have the same structure
public class HomeFragment extends Fragment {
#Override
public void onDestroyView() {
super.onDestroyView();
recyclerView.setAdapter(null);
}
#Override
public void onDetach() {
super.onDetach();
}
private List<NewsModelClass> homeNews = new ArrayList<>();
String country = "in";
String category = "general";
int pageSize = 50;
private RecyclerView recyclerView;
NewsAdapter newsAdapter;
final String API_KEY = "ba88d060a3e049ca9fa46f2bea0d52c4";
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = v.findViewById(R.id.rvHome);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
newsAdapter = new NewsAdapter(getContext(),homeNews);
recyclerView.setAdapter(newsAdapter);
fetchNews();
}
private void fetchNews()
{
Call<NewsArticles> call = RetrofitClient.getInstance().getMyApi().getNews(country,pageSize,category,API_KEY);
call.enqueue(new Callback<NewsArticles>() {
#Override
public void onResponse(#NonNull Call<NewsArticles> call, #NonNull Response<NewsArticles> response) {
if(response.isSuccessful()) {
if (!homeNews.isEmpty()) {
homeNews.clear();
}
homeNews=response.body().getArticles();
newsAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(#NonNull Call<NewsArticles> call, Throwable t) {
Toast.makeText(getContext(),"Something is wrong",Toast.LENGTH_SHORT).show();
}
});
}
}
fragment_home.xml - Other fragments have the same layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.HomeFragment">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rvHome"
android:fitsSystemWindows="true"
android:padding="8dp"/>
</FrameLayout>
NewsAdapter.java
public class NewsAdapter extends
RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
Context context;
List<NewsModelClass> allNews;
public NewsAdapter(Context context,List<NewsModelClass>
allNews) {
this.context = context;
this.allNews = allNews;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View newsItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent, false);
return new NewsViewHolder(newsItem);
}
#Override
public void onBindViewHolder(#NonNull NewsViewHolder holder, int position) {
NewsModelClass currentNewsItem = allNews.get(position);
holder.title.setText(currentNewsItem.getTitle());
holder.author.setText(currentNewsItem.getAuthor());
if (currentNewsItem.getUrlToImage() != null)
Glide.with(holder.itemView.getContext()).load(Uri.parse(currentNewsItem.getUrlToImage())).into(holder.articleImage);
holder.cardView.setOnClickListener(v -> {
String newsUrl = currentNewsItem.getUrl();
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
int colorInt = Color.parseColor("#F1ECC3");
CustomTabColorSchemeParams defaultColors = new CustomTabColorSchemeParams.Builder()
.setToolbarColor(colorInt)
.build();
builder.setDefaultColorSchemeParams(defaultColors);
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(context, Uri.parse(newsUrl));
});
}
#Override
public int getItemCount() {
return allNews.size();
}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
ImageView articleImage;
TextView title, author;
CardView cardView;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
articleImage = itemView.findViewById(R.id.ivArticleImage);
title = itemView.findViewById(R.id.tvHeadline);
author = itemView.findViewById(R.id.tvAuthor);
cardView = itemView.findViewById(R.id.cardView);
}
}
}
Unfortunately, I am finding the developer of this project doesn't reply at all. So I am posting here. I am trying to implement this UI on my project but developer has used image in sample code. I need to implement here a fragment from one to another. I have already tried this but this doesn't change my fragment. Below is the code how I implemented.
Note: Below codes are a lot. I posted it to make sure where the problem was. As the documentation and sample project I did all well.
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<io.codetail.widget.RevealLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:autofit="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/container1"
android:orientation="vertical"
android:weightSum="2"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/lightbrown"
android:orientation="horizontal"
android:weightSum="2">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.2">
<me.grantland.widget.AutofitTextView
android:id="#+id/textBoy"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="32dp"
android:maxLines="1"
android:singleLine="true"
android:typeface="monospace"
android:text="#string/boy"
android:gravity="center_vertical|center_horizontal"
android:textSize="180sp"
autofit:minTextSize="20sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.8">
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="#drawable/home_boy_one" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#color/lightGreen"
android:weightSum="2">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.2">
<me.grantland.widget.AutofitTextView
android:id="#+id/textGirl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:layout_margin="32dp"
android:maxLines="1"
android:singleLine="true"
android:typeface="monospace"
android:text="#string/girl"
android:textSize="180sp"
autofit:minTextSize="20sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.8">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="#drawable/home_girl_one" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</io.codetail.widget.RevealLinearLayout>
Home.java
public class Home extends Fragment implements ScreenShotable {
private View Fragmentone_view;
private Bitmap bitmap;
private AutofitTextView textBoy, textGirl;
private Typeface typeface;
#Nullable
public static Home newInstance() {
Home home = new Home();
return home;
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
textBoy = rootView.findViewById(R.id.textBoy);
textGirl = rootView.findViewById(R.id.textGirl);
typeface = Typeface.createFromAsset(getResources().getAssets(), "fonts/trench.otf");
textBoy.setTypeface(typeface);
textGirl.setTypeface(typeface);
Log.d("reachHera","reachhere");
return rootView;
}
#Override
public void takeScreenShot() {
Thread thread = new Thread() {
#Override
public void run() {
try {
Bitmap bitmap = Bitmap.createBitmap(Fragmentone_view.getWidth(),
Fragmentone_view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Fragmentone_view.draw(canvas);
Home.this.bitmap = bitmap;
} catch (Exception ex) {
}
}
};
thread.start();
}
#Override
public Bitmap getBitmap() {
return bitmap;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.Fragmentone_view = view.findViewById(R.id.container1);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
ContentFragment.java
public class ContentFragment extends Fragment implements ScreenShotable {
public static final String CLOSE = "Close";
public static final String BUILDING = "Building";
public static final String BOOK = "Book";
public static final String PAINT = "Paint";
public static final String CASE = "Case";
public static final String SHOP = "Shop";
public static final String PARTY = "Party";
public static final String MOVIE = "Movie";
private View containerView;
protected ImageView mImageView;
protected int res;
private Bitmap bitmap;
public static ContentFragment newInstance(int resId) {
ContentFragment contentFragment = new ContentFragment();
Bundle bundle = new Bundle();
bundle.putInt(Integer.class.getName(), resId);
contentFragment.setArguments(bundle);
return contentFragment;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.containerView = view.findViewById(R.id.container);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
res = getArguments().getInt(Integer.class.getName());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mImageView = (ImageView) rootView.findViewById(R.id.image_content);
mImageView.setClickable(true);
mImageView.setFocusable(true);
mImageView.setImageResource(res);
return rootView;
}
#Override
public void takeScreenShot() {
Thread thread = new Thread() {
#Override
public void run() {
Bitmap bitmap = Bitmap.createBitmap(containerView.getWidth(),
containerView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
containerView.draw(canvas);
ContentFragment.this.bitmap = bitmap;
}
};
thread.start();
}
#Override
public Bitmap getBitmap() {
return bitmap;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements ViewAnimator.ViewAnimatorListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private List<SlideMenuItem> list = new ArrayList<>();
private ContentFragment contentFragment;
private ViewAnimator viewAnimator;
private int res = R.drawable.content_music;
private LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contentFragment = ContentFragment.newInstance(R.drawable.content_music);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, contentFragment)
.commit();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.setScrimColor(Color.TRANSPARENT);
linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.closeDrawers();
}
});
setActionBar();
createMenuList();
viewAnimator = new ViewAnimator<>(this, list, contentFragment, drawerLayout, this);
}
private void createMenuList() {
SlideMenuItem menuItem0 = new SlideMenuItem(ContentFragment.CLOSE, R.drawable.icn_close);
list.add(menuItem0);
SlideMenuItem menuItem = new SlideMenuItem(ContentFragment.BUILDING, R.drawable.icn_1);
list.add(menuItem);
SlideMenuItem menuItem2 = new SlideMenuItem(ContentFragment.BOOK, R.drawable.icn_2);
list.add(menuItem2);
SlideMenuItem menuItem3 = new SlideMenuItem(ContentFragment.PAINT, R.drawable.icn_3);
list.add(menuItem3);
SlideMenuItem menuItem4 = new SlideMenuItem(ContentFragment.CASE, R.drawable.icn_4);
list.add(menuItem4);
SlideMenuItem menuItem5 = new SlideMenuItem(ContentFragment.SHOP, R.drawable.icn_5);
list.add(menuItem5);
SlideMenuItem menuItem6 = new SlideMenuItem(ContentFragment.PARTY, R.drawable.icn_6);
list.add(menuItem6);
SlideMenuItem menuItem7 = new SlideMenuItem(ContentFragment.MOVIE, R.drawable.icn_7);
list.add(menuItem7);
}
private void setActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
linearLayout.removeAllViews();
linearLayout.invalidate();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0.6 && linearLayout.getChildCount() == 0)
viewAnimator.showMenuContent();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private ScreenShotable replaceFragment(ScreenShotable screenShotable, int topPosition) {
View view = findViewById(R.id.content_frame);
int finalRadius = Math.max(view.getWidth(), view.getHeight());
SupportAnimator animator = ViewAnimationUtils.createCircularReveal(view, 0, topPosition, 0, finalRadius);
animator.setInterpolator(new AccelerateInterpolator());
animator.setDuration(ViewAnimator.CIRCULAR_REVEAL_ANIMATION_DURATION);
findViewById(R.id.content_overlay).setBackgroundDrawable(new BitmapDrawable(getResources(), screenShotable.getBitmap()));
animator.start();
// ContentFragment contentFragment = ContentFragment.newInstance(this.res);
// getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, contentFragment).commit();
return screenShotable;
}
#Override
public ScreenShotable onSwitch(Resourceble slideMenuItem, ScreenShotable screenShotable, int position) {
switch (slideMenuItem.getName()) {
case ContentFragment.CLOSE:
return screenShotable;
case ContentFragment.BOOK:
Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
Home home=Home.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,home);
return replaceFragment(home,position);
default:
return replaceFragment(screenShotable, position);
}
}
#Override
public void disableHomeButton() {
getSupportActionBar().setHomeButtonEnabled(false);
}
#Override
public void enableHomeButton() {
getSupportActionBar().setHomeButtonEnabled(true);
drawerLayout.closeDrawers();
}
#Override
public void addViewToContainer(View view) {
linearLayout.addView(view);
}
}
I am trying to pass a String "mMeetingKey" from View.class to PostListFragment.class, but the bundle is returning null. I checked the bundle in View.class, it is not null. When I check the bundle in PostListFragment.class, it keep returning null.
The code is mainly from "Firebase Quickstart for Database".
Thank you for your help.
View.class
public class View extends BaseActivity {
private FragmentPagerAdapter mPagerAdapter;
private ViewPager mViewPager;
private String mMeetingKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_posts);
mViewPager = findViewById(R.id.container);
mMeetingKey=getIntent().getStringExtra("meetingKey");
Bundle bundle = new Bundle();
bundle.putString("mMeetingKey", mMeetingKey);
PostListFragment postListFragment=new PostListFragment();
postListFragment.setArguments(bundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container,postListFragment).commit();
mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
private final Fragment[] mFragments = new Fragment[] {
new PostListFragment(),
// new MyPostsFragment(),
// new CompletedPostFragment(),
};
private final String[] mFragmentNames = new String[] {
getString(R.string.heading_recent),
//getString(R.string.heading_my_posts),
//getString(R.string.heading_completed_posts)
};
#Override
public Fragment getItem(int position) {
return mFragments[position];
}
#Override
public int getCount() {
return mFragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentNames[position];
}
};
mViewPager.setAdapter(mPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Toast.makeText(this,mMeetingKey,Toast.LENGTH_LONG).show();
// Button launches NewPostActivity
findViewById(R.id.fab_new_post).setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
Intent intent = new Intent(View.this, NewPostActivity.class);
intent.putExtra("mMeetingKey",mMeetingKey);
startActivity(intent);
}
});
}
}
PostListFragment.class
public class PostListFragment extends android.support.v4.app.Fragment {
private static final String TAG = "PostListFragment";
// [START define_database_reference]
private DatabaseReference mDatabase;
// [END define_database_reference]
private String mMeetingKey;
private FirebaseRecyclerAdapter<Post, PostViewHolder> mAdapter;
private RecyclerView mRecycler;
private String meetingKeyRef;
private LinearLayoutManager mManager;
public PostListFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_all_post, container, false);
Bundle bundle = this.getArguments();
if (bundle != null) {
meetingKeyRef = bundle.getString("mMeetingKey").toString();
}
if (bundle!= null) {
meetingKeyRef = this.getArguments().getString("mMeetingKey");
}
if (bundle == null) {
throw new IllegalArgumentException("Bundle is null");
}
// [START create_database_reference]
mDatabase = FirebaseDatabase.getInstance().getReference().child(meetingKeyRef);
// [END create_database_reference]
mRecycler = rootView.findViewById(R.id.messages_list);
mRecycler.setHasFixedSize(true);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Set up Layout Manager, reverse layout
mManager = new LinearLayoutManager(getActivity());
mManager.setReverseLayout(true);
mManager.setStackFromEnd(true);
mRecycler.setLayoutManager(mManager);
// Set up FirebaseRecyclerAdapter with the Query
Query postsQuery = getQuery(mDatabase);
mAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(Post.class, R.layout.item_post,
PostViewHolder.class, postsQuery) {
#Override
protected void populateViewHolder(final PostViewHolder viewHolder, final Post model, final int position) {
final DatabaseReference postRef = getRef(position);
mMeetingKey= postRef.getKey();
// Set click listener for the whole post view
final String postKey = postRef.child(mMeetingKey).getKey();
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Launch PostDetailActivity
Intent intent = new Intent(getActivity(), PostDetailActivity.class);
intent.putExtra(PostDetailActivity.EXTRA_POST_KEY, postKey);
intent.putExtra(PostDetailActivity.EXTRA_MEETING_KEY,mMeetingKey);
startActivity(intent);
}
});
// Determine if the current user has liked this post and set UI accordingly
if (model.boxCount==1) {
viewHolder.boxView.setImageResource(R.drawable.ic_toggle_check_box_checked);
} else {
viewHolder.boxView.setImageResource(R.drawable.ic_toggle_check_box_outline);
}
// Bind Post to ViewHolder, setting OnClickListener for the star button
viewHolder.bindToPost(model, new View.OnClickListener() {
#Override
public void onClick(View boxView) {
// Need to write to both places the post is stored
DatabaseReference globalPostRef = mDatabase.child("posts").child(postRef.getKey());
DatabaseReference userPostRef = mDatabase.child("user-posts").child(model.uid).child(postRef.getKey());
// Run two transactions
onBoxClicked(globalPostRef);
onBoxClicked(userPostRef);
}
});
}
};
mRecycler.setAdapter(mAdapter);
}
// [START post_stars_transaction]
private void onBoxClicked(DatabaseReference postRef) {
postRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Post p = mutableData.getValue(Post.class);
if (p == null) {
return Transaction.success(mutableData);
}
if (p.checkbox.containsKey(getUid())) {
// Unstar the post and remove self from stars
p.boxCount = 0;
p.checkbox.remove(getUid());
} else {
// Star the post and add self to stars
p.boxCount = 1;
p.checkbox.put(getUid(), true);
}
// Set value and report transaction success
mutableData.setValue(p);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "postTransaction:onComplete:" + databaseError);
}
});
}
// [END post_stars_transaction]
#Override
public void onDestroy() {
super.onDestroy();
if (mAdapter != null) {
mAdapter.cleanup();
}
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
public Query getQuery(DatabaseReference databaseReference){
Query recentPostsQuery = databaseReference.child("posts")
.limitToFirst(100);
// [END recent_posts_query]
return recentPostsQuery;
}
}
activity_view_posts.xml
<?xml version="1.0" encoding="utf-8"?>
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tabs"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_new_post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
android:src="#drawable/ic_create"
app:backgroundTint="#android:color/holo_orange_dark" />
fragment_all_post.xml
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".checklist.View">
<android.support.v7.widget.RecyclerView
android:id="#+id/messages_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:clipToPadding="false"
android:padding="5dp"
android:scrollbars="vertical"
tools:listitem="#layout/item_post" />
You are using ViewPager then why you are replacing container with your fragment. Remove that code and use below code for View
public class View extends BaseActivity {
private FragmentPagerAdapter mPagerAdapter;
private ViewPager mViewPager;
private String mMeetingKey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_posts);
mViewPager = findViewById(R.id.container);
mMeetingKey=getIntent().getStringExtra("meetingKey");
Bundle bundle = new Bundle();
bundle.putString("mMeetingKey", mMeetingKey);
PostListFragment postListFragment=new PostListFragment();
postListFragment.setArguments(bundle);
mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
private final Fragment[] mFragments = new Fragment[] {
postListFragment ,
// new MyPostsFragment(),
// new CompletedPostFragment(),
};
private final String[] mFragmentNames = new String[] {
getString(R.string.heading_recent),
//getString(R.string.heading_my_posts),
//getString(R.string.heading_completed_posts)
};
#Override
public Fragment getItem(int position) {
return mFragments[position];
}
#Override
public int getCount() {
return mFragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentNames[position];
}
};
mViewPager.setAdapter(mPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Toast.makeText(this,mMeetingKey,Toast.LENGTH_LONG).show();
// Button launches NewPostActivity
findViewById(R.id.fab_new_post).setOnClickListener(new android.view.View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
Intent intent = new Intent(View.this, NewPostActivity.class);
intent.putExtra("mMeetingKey",mMeetingKey);
startActivity(intent);
}
});
}
}
I have really browsed through stackoverflow for this solution.
Im trying to access a fragment from another fragment and an error is thrown that
java.lang.ClassCastException: com.noel.myapplication99.IncomeTax cannot be cast to com.noel.myapplication99.IncomeDialog
at com.noel.myapplication99.MainActivity.createOutput(MainActivity.java:119)
at com.noel.myapplication99.IncomeTax$1.onClick(IncomeTax.java:77)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19869)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
These are my codes
MainActivity.java
public class MainActivity extends AppCompatActivity
implements IncomeTax.OnFragmentInteractionListener, ResidentialIncomeTax.OnFragmentInteractionListener, NavigationDrawerFragment.NavigationDrawerCallbacks, IncomeTax.IncomeTaxListener {
public void onFragmentInteraction(Uri uri){
}
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment=null;
switch(position)
{
case 0:
fragment = new IncomeTax();
mTitle = getString(R.string.title_section1);
break;
case 1:
fragment = new ResidentialIncomeTax();
mTitle = getString(R.string.title_section2);
break;
}
if(fragment!=null)
{
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, fragment, "Tag").commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void createOutput(int i, int f) {
IncomeDialog incomeDialog = (IncomeDialog) getSupportFragmentManager().findFragmentByTag("Tag");
incomeDialog.setOutputText(i, f);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
IncomeTax.java
public class IncomeTax extends Fragment implements AdapterView.OnItemSelectedListener {
IncomeTaxListener activityCommander;
float selectedIncomeType;
public interface IncomeTaxListener{
public void createOutput(int i, int f);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activityCommander = (IncomeTaxListener) context;
}catch(Exception e){
throw new ClassCastException(toString());
}
}
private OnFragmentInteractionListener mListener;
public IncomeTax() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
Button btnIcCalc;
EditText salary, insuaranceRelief;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_income_tax, container, false);
salary = (EditText) view.findViewById(R.id.tvSalary);
insuaranceRelief = (EditText) view.findViewById(R.id.tvReliefCalc);
btnIcCalc = (Button)view.findViewById(R.id.btnIcCalc);
final int iSalary=0;
final int iInsuranceRelief=1;
btnIcCalc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Dialog box here
activityCommander.createOutput(iSalary, iInsuranceRelief);
FragmentManager manager = getActivity().getSupportFragmentManager();
IncomeDialog myDialog = new IncomeDialog();
myDialog.setTargetFragment(IncomeTax.this, 0);
myDialog.show(manager, "IncomeDialog");
}
});
setSpinnerContent(view);
return view;
}
private void setSpinnerContent( View view )
{
Spinner spinner = (Spinner) view.findViewById( R.id.incomeTypeSpinner );
ArrayAdapter incomeSpinnerArrayAdapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.income_type_array, android.R.layout.simple_spinner_item);
spinner.setAdapter(incomeSpinnerArrayAdapter );
spinner.setOnItemSelectedListener(this);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
selectedIncomeType = 1;
break;
case 1:
selectedIncomeType = 1;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
IncomeDialog.java
public class IncomeDialog extends DialogFragment {
public IncomeDialog() {
// Required empty public constructor
}
TextView netPay, insuranceRelief;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_income_dialog, null);
netPay = (TextView) view.findViewById(R.id.tvNetPay);
insuranceRelief = (TextView) view.findViewById(R.id.tvPersonalRelief);
return view;
}
public void setOutputText(int i, int f){
netPay.setText(i);
insuranceRelief.setText(f);
}
If you want to send data to DialogFragmet then try like this:
Bundle bundle = new Bundle();
bundle.putInt("key1", i);
bundle.putInt("key2", f);
IncomeDialog incomeDialog = new IncomeDialog();
incomeDialog.setArguments(bundle);
Now carry out FragmentTransaction to add this incomeDialog. That will show the dialog.
To receive the bundle data in IncomeDialog:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_income_dialog, null);
netPay = (TextView) view.findViewById(R.id.tvNetPay);
insuranceRelief = (TextView) view.findViewById(R.id.tvPersonalRelief);
Bundle bundle=getArguments();
int i = bundle.getInt("key1");
int f = bundle.getInt("key2");
return view;
}
EDIT cjohn caught the missing piece. I was forgetting to call init() on my YTPlayerFragment.
New to android dev. I am trying to put a youtube video inside a YouTubePlayerFragment which is nested inside another fragment. Logcat doesn't show any errors, but my player fragment only shows a black box. Placing log statements inside my OnInitializedListener, it seems it's not even being called.
The ContentFragment that contains the YouTubePlayerFragment is a tab inside a ViewPager. My code is below. MainActivity ContentFragment, ContentFragment contains the YouTubePlayerFragment.
MainActivity.java:
public class MainActivity extends FragmentActivity{
TabsPagerAdapter mAdapter;
ViewPager mViewPager;
Boolean mLoggedIn;
String[] mTabs = {"Library", "Content", "Quotes"};
#Override
protected void onCreate(Bundle savedInstanceState) {
final ActionBar actionBar = getActionBar();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.viewPager);
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
mViewPager.setAdapter(mAdapter);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
};
for (String tab : mTabs) {
actionBar.addTab(actionBar.newTab().setText(tab).setTabListener(tabListener));
}
}
}
TabsPagerAdapter.java:
public class TabsPagerAdapter extends FragmentPagerAdapter{
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return new LibraryFragment();
case 1:
return new ContentFragment();
case 2:
return new QuotesFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
ContentFragment.java:
public class ContentFragment extends Fragment {
public ContentFragment() {
// Required empty public constructor
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
View v = inflater.inflate(R.layout.fragment_content, container, false);
YTPlayerFragment video = YTPlayerFragment.newInstance("nCgQDjiotG0");
getFragmentManager().beginTransaction().replace(R.id.youtubeFragment, video).commit();
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
YTPlayerFragment.java:
public class YTPlayerFragment extends YouTubePlayerSupportFragment {
private YouTubePlayer activePlayer;
private final static String DEV_KEY = "KEY";
public static YTPlayerFragment newInstance(String url) {
YTPlayerFragment player = new YTPlayerFragment();
Bundle bundle = new Bundle();
bundle.putString("url", url);
player.setArguments(bundle);
return player;
}
private void init() {
initialize(DEV_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
activePlayer = youTubePlayer;
Log.d("YOUTUBE", "Successfully initialized");
activePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
if (!b) {
activePlayer.cueVideo(getArguments().getString("url"));
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.e("YOUTUBE", youTubeInitializationResult.toString());
}
});
}
}
fragment_content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp"
android:clipToPadding="false"
android:scrollbarStyle="outsideOverlay"
android:orientation="vertical" >
<FrameLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/youtubeFragment" />
</LinearLayout>
Inside your ContentFragment, you're trying to add another Fragment as a child. To do this, you require the child fragment manager, acquired by calling getChildFragmentManager():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setRetainInstance(true);
View v = inflater.inflate(R.layout.fragment_content, container, false);
YTPlayerFragment video = YTPlayerFragment.newInstance("nCgQDjiotG0");
getChildFragmentManager().beginTransaction().replace(R.id.youtubeFragment, video).commit();
return v;
}