I have tabbed activity and I want to have youtube video on third tab.
here's my java :
public class FragmentTutorial extends YouTubePlayerFragment {
YouTubePlayerView youTubePlayerView;
YouTubePlayer.OnInitializedListener onInitializedListener;
public FragmentTutorial() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
youTubePlayerView = (YouTubePlayerView) youTubePlayerView.findViewById(R.id.tutorial_youtube_player);
onInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("3LiubyYpEUk");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
youTubePlayerView.initialize(PlayerConfig.API_KEY, onInitializedListener);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_tutorial, container, false);
}
}
and here's my XML :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.FragmentTutorial">
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tutorial_youtube_player" />
</FrameLayout>
and here's my MainActivity :
class FragmentAdapter extends FragmentPagerAdapter {
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentHome();
case 1:
return new FragmentCatalog();
case 2:
return new FragmentTutorial();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
//
//Your tab titles
//
case 0: return "Home";
case 1: return "Catalog";
case 2: return "Tutorial";
default: return null;
}
}
}
when I tried to run this code, I got this following error :
Error:(80, 28) error: incompatible types: FragmentTutorial cannot be converted to Fragment
what did I missed here? thank you...
Probably it is caused by the wrong Fragment class, YouTubePlayerFragment extends android.app.Fragment, FragmentPagerAdapter requires android.support.v4.app.Fragment and this cannot be converted
Edit:
try to use android.support.v13.app.FragmentPagerAdapter instead android.support.v4.app.FragmentPagerAdapter (other fragments should extends android.app.Fragment)
Related
I have this situation:
Fragment1 uses viewPager, then when click some component inside the viewPager's child fragment, it open Fragment2, which also uses viewPager.
So far so good. But then, on click the back button, doesn't come back to Fragment1, coming back for my main activity instead. The app uses single activity and Android Navigation.
I already tried use viewPager2, it happens the same thing.
Thanks if anyone can help me.
public class Fragment1 extends AbstractNavFragment {
private Fragment1 binder;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binder = Fragment1Binding.inflate(inflater, container, false);
return binder.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
binder.viewPager.setAdapter(new PageAdapterInternal(getChildFragmentManager()));
binder.viewPager.setOffscreenPageLimit(2);
binder.tabLayout.getTab().setupWithViewPager(binder.viewPager);
}
public void navigateToFragment2() {
navigate(R.id.action_Fragment1_to_Fragment2);
}
private class PageAdapterInternal extends FragmentStatePagerAdapter {
public PageAdapterInternal(#NonNull FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new IrcSupplyPositionsFragment(IrcSupplyPositionsFragment.FragmentType.PENDING);
case 1:
return new IrcSupplyPositionsFragment(IrcSupplyPositionsFragment.FragmentType.COMPLETED);
default:
throw new IllegalStateException("Unexpected value: " + position);
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return translate("rotativeInventory.supply.pendingPositions");
case 1:
return translate("rotativeInventory.supply.positionsCompleted");
default:
return "";
}
}
#Override
public int getCount() {
return 2;
}
}
}
public class Fragment2 extends AbstractNavFragment {
private Fragment2 binder;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
binder = Fragment2Binding.inflate(inflater, container, false);
return binder.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
binder.viewPager.setAdapter(new RotativeInventorySupplyUDFragment.PageAdapterInternal(getChildFragmentManager()));
binder.viewPager.setOffscreenPageLimit(2);
binder.tabLayout.getTab().setupWithViewPager(binder.viewPager);
}
#Override
protected void doOnViewCreate() {}
private class PageAdapterInternal extends FragmentStatePagerAdapter {
public PageAdapterInternal(#NonNull FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new IrcSupplyUDFragment(IrcSupplyUDFragment.FragmentType.PENDING);
case 1:
return new IrcSupplyUDFragment(IrcSupplyUDFragment.FragmentType.COMPLETED);
default:
throw new IllegalStateException("Unexpected value: " + position);
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return translate("rotativeInventory.supply.pendingPositions");
case 1:
return translate("rotativeInventory.supply.positionsCompleted");
default:
return "";
}
}
#Override
public int getCount() {
return 2;
}
}
}
You have to override your onBackPressed method of your Activity, to controll all this stuff or register your fragment for a OnBackPressedDispatcher and when user click on back button of your device, take a decision, like ==> findNavController().popBackStack()
Today was the first day I used ViewPager to swipe across screens in my activity. However, after adding the ViewPager, none of my buttons in any activities seem to work. I can only swipe between my activities. I don't understand as to why this happens so any help would be greatly appreciated. Thank you!
Here is the PageAdapter class code:
PageAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentOne();
break;
case 1:
return new FragmentTwo();
break;
case 2:
return new FragmentThree();
break;
default:
break;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
Here is the Fragments code:
FragmentOne.java
public class FragmentOne extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_log,container,false);
}
}
FragmentTwo.java
public class FragmentTwo extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_remote_lock,container,false);
}
}
FragmentThree.java
public class FragmentThree extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_my_keys,container,false);
}
}
FragmentActivity.java
public class FragmentActivity extends android.support.v4.app.FragmentActivity {
ViewPager viewPager;
#Override
protected void onResume() {
super.onResume();
viewPager.setCurrentItem(1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
viewPager = (ViewPager) findViewById(R.id.damsara);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
}
FragmentActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/damsara"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.v4.view.ViewPager>
The xml files i added to the fragment classes contain buttons with animations. however none of them work.
I'm pretty new in android development and I have some questions about communication between fragments and main activity.
I didn't success to solve my problem in my particular case. What I want to do is to modify the alpha of a view inside a fragment (something like a card) when scrolling from one fragment to the one with this view. I tried different things but I failed (null pointer exception), you can see some experiments in a comment. Here is my code and my architecture:
Fragment with the view:
public class VideoviewFragment extends BaseFragment {
/* public View card;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_videoview, container, false);
card = (View) rootview.findViewById(R.id.card_video);
return rootview;
}
public void setalphacard(float value){
card.setAlpha(value);
}*/
public static VideoviewFragment create() {
return new VideoviewFragment();
}
#Override
public int getLayoutResId() {
return R.layout.fragment_videoview;
}
#Override
public void inOnCreateView(View root, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
}
}
Base fragment:
public abstract class BaseFragment extends Fragment {
private View mRoot;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mRoot = inflater.inflate(getLayoutResId(), container, false);
inOnCreateView(mRoot, container, savedInstanceState);
return mRoot;
}
#LayoutRes
public abstract int getLayoutResId();
public abstract void inOnCreateView(View root, #Nullable ViewGroup container,#Nullable Bundle savedInstanceState);
}
Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Viewpager
final ViewPager viewPager = (ViewPager) findViewById(R.id.am_view_pager);
final MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
// tabview et viewpager
viewPager.setCurrentItem(1);
// Changement couleurs swipe
viewPager.setBackgroundColor(Color.rgb(135,206,250));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(position == 1) {
viewPager.setBackgroundColor((Integer) new ArgbEvaluator().evaluate(positionOffset, Color.rgb(135,206,250),Color.rgb(240,15,45)));
//videoviewFragment.setalphacard(positionOffset);
}
if(position == 0) {
viewPager.setBackgroundColor((Integer) new ArgbEvaluator().evaluate(positionOffset, Color.TRANSPARENT,Color.rgb(135,206,250)));
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
Adapter:
public class MainPagerAdapter extends FragmentPagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return CameraFragment.create();
case 1:
return OptionFragment.create();
case 2:
return VideoviewFragment.create();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
XML VideoviewFragment
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout0"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="#+id/card_video"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="70dp"
android:background="#drawable/card_background_video"/>
</RelativeLayout>
(I know there is no instance of my fragment in this activity...)
I found few similar topics on StackOverflow like this one Use view from fragment xml file, but I'm doing something wrong...
Thanks for your help!
I have a App with a Slidingmenu where i can pick different Fragment, which displays different kind of ListFragments.
The ListFragments will be filled by JSON from my Database Server.
If you Click on one of the Listitems, a new Fragment is shown which contains more Details about the selected Listitem.
public void updateList(final Activity a, final ListFragment L) {
adapter = new SimpleAdapter(a, mCommentList,
R.layout.single_comment, new String[] {TAG_PIC_ID,TAG_CATEGORY, TAG_ACTIVITY, TAG_DATUM, TAG_AKTUSR, TAG_MAXUSR, TAG_GENDER, /*TAG_POST_ID,*/ TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME }, new int[] { R.id.imgrow, R.id.category, R.id.activity/*R.id.id*/ , R.id.datum, R.id.aktusr, R.id.maxusr, R.id.gender, /*R.id.category,*/ R.id.title, R.id.message,
R.id.username });
L.setListAdapter(adapter);
ListView lv = L.getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int intid = (int)id;
Details nextFrag= new Details();
L.getFragmentManager().beginTransaction()
.replace(R.id.frame_container, nextFrag, "Test")
.addToBackStack(null)
.commit();
}
});
}
When i call the function from a "single" fragment its no problem and the DetailPage is shown.
The Problem is when i call the function from a TabbedActivity with a SectionsPagerAdapter.
The TabbedActivity
package info.androidhive.slidingmenu;
public class TabbedActivity extends Fragment {
SectionsPagerAdapter mSectionsPagerAdapter;
public static final String TAG = TabbedActivity.class.getSimpleName();
ViewPager mViewPager;
public static TabbedActivity newInstance() {
return new TabbedActivity();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_item_one, container, false);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getChildFragmentManager());
mViewPager = (ViewPager) v.findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
return v;
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new newEntrys();
switch (position) {
case 0:
fragment = new newEntrys();
break;
case 1:
fragment = new oldEntrys();
break;
default:
break;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Aktuelle Einträge";
case 1:
return "Vergangene Einträge";
}
return null;
}
}}
The TabbedActivity contains the 2 Fragments newEntry and oldEntry which are nearly equal.
package info.androidhive.slidingmenu.fragments;
public class RegisterdEvents_new extends ListFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.read, container, false);
return rootView;
}
public void startTask(){
Read SO = new Read();
Load LEvt = SO.new Load(getActivity(), this, "NEW");
LEvt.execute();
}
public void onResume() {
startTask();
super.onResume();
}
}
So the function updateList above is called in
Load LEvt = SO.new Load(getActivity(), this, "NEW");
But the problem is that i always get the Error
No view found for id 0x7f0a000f (package:id/frame_container) for fragment Details{e3992e2 #0 id=0x7f0a000f Test}
Someone of you can help me to solve this problem?
I am trying to display a fragment in a ViewPager and I would like to have a button to replace the fragment in the ViewPager. I have managed to set up using examplesIi found on stackoverflow. However, how can I toggle between the 2 fragmentA and FragmentB.
Thank you so much.
My code is as follows :
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private final FragmentManager mFragmentManager;
private Fragment mFragmentAtPos0;
private Fragment mFragmentAtPos1;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
mFragmentManager=fm;
}
#Override
public int getItemPosition(Object object)
{
if (object instanceof FragmentA && mFragmentAtPos0 instanceof FragmentB)
return POSITION_NONE;
if (object instanceof FragmentB && mFragmentAtPos1 instanceof FragmentA)
return POSITION_NONE;
return POSITION_UNCHANGED;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch (position){
case 1:
if (mFragmentAtPos1 == null)
{
mFragmentAtPos1 = FragmentB.newInstance(new FirstPageFragmentListener()
{
public void onSwitchToNextFragment()
{
mFragmentManager.beginTransaction().remove(mFragmentAtPos1).commit();
mFragmentAtPos1 = new FragmentA();
notifyDataSetChanged();
showToast("in switchtoNextFragmentA ------------1");
}
});
}
return mFragmentAtPos1;
case 0:
if (mFragmentAtPos0 == null)
{
mFragmentAtPos0 = FragmentA.newInstance(new FirstPageFragmentListener()
{
public void onSwitchToNextFragment()
{
mFragmentManager.beginTransaction().remove(mFragmentAtPos0).commit();
mFragmentAtPos0 = new FragmentB();
notifyDataSetChanged();
showToast("in switchtoNextFragment");
}
});
}
return mFragmentAtPos0;
default: return null;
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public class FragmentB extends Fragment {
Button button;
static FragmentB b;
static FirstPageFragmentListener fpl1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved)
{
return inflater.inflate(R.layout.frag_b, group, false);
}
public static Fragment newInstance(FirstPageFragmentListener firstPageFragmentListener) {
// TODO Auto-generated method stub
fpl1 = firstPageFragmentListener;
if (b == null)
b = new FragmentB();
return b;
}
public static FragmentB newInstance() {
if (b == null)
b = new FragmentB();
return b;
}
#Override
public void onActivityCreated (Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
button = (Button) getActivity().findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fpl1.onSwitchToNextFragment();
}
});
}
}
UPDATE : layout file
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/lbltime"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:id="#+id/framelayout">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFCC" >
</android.support.v4.view.ViewPager>
</FrameLayout>
Its simple just do this
inside your button onClick method
Fragment f;
f = new FragmentTwo();
FragmentTransaction ft = getFragmentSupportManager().beginTransaction();
ft.replace(R.id.main_details_fragment_container, f);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();