I am trying to implement ViewPager2 in my application and this is not the first time I am doing it but now it is not working.
I've been trying to find a solution for a couple of hours and trying different options but still - the fragments don't show up.
ViewPager2 is displaying correctly - I checked this by changing its background color.
I'm using the OneUI 2.4.0 library - but I've tested this library before and everything worked, and now it won't.
ViewPager2 Adapter
public class MainViewPagerAdapter extends FragmentStateAdapter {
private ArrayList<Fragment> arrayList = new ArrayList<>();
public MainViewPagerAdapter(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
return new MainFragment();
case 1:
return new NewsFragment();
case 2:
return new ProfileFragment();
}
return null;
}
#Override
public int getItemCount() {
return 3;
}
}
MainFragment.java (other fragments code looks the same)
public class MainFragment extends Fragment {
View mRootView;
#Nullable
#Override
public View onCreateView(
#NonNull LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_main, container, true);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("MainFragment", "Initialized"); // I don't see that in logcat
}
}
fragment_main.xml (Other fragments have similar layout)
<?xml version="1.0" encoding="utf-8"?>
<de.dlyt.yanndroid.oneui.widget.NestedScrollView 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">
<com.google.android.material.textview.MaterialTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/main_page"
android:textColor="#color/sesl_primary_text"
android:textSize="24sp"
android:textStyle="bold" />
</de.dlyt.yanndroid.oneui.widget.NestedScrollView>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ToolbarLayout mToolbarLayout;
private ViewPager2 mViewPager;
private TabLayout mTabLayout;
private MainViewPagerAdapter viewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
setup();
}
private void initialize() {
mToolbarLayout = (ToolbarLayout) findViewById(R.id.mToolbarLayout);
mViewPager = (ViewPager2) findViewById(R.id.mMainPager);
mTabLayout = (TabLayout) findViewById(R.id.mMainTabLayout);
}
private void setup() {
viewPagerAdapter = new MainViewPagerAdapter(getSupportFragmentManager(), getLifecycle());
mViewPager.setAdapter(viewPagerAdapter);
}
And the problem is just that i don't see my fragments in ViewPager2.
try to
return mRootView
instead of
return super.onCreateView(inflater, container, savedInstanceState);
The place where you went wrong was when you did not add the layout to the root. The problem is this:
return super.onCreateView(inflater, container, savedInstanceState);
but, you r not using your view right? You are using the default view which is just empty. So, to solve it, you need to pass it your view instead of that. So, return your view like this:
return mRootView;
Related
I'm making a tabbed activity with different fragments and one of them contains a recyclerview with just some names at the moment. I have no idea what I've done wrong, I get a warning every time on starting the app that says no adapter attached, skipping layout. I've created and set the adapter to the recyclerview in my fragment, created an adapter with viewholder, and created a class to set the name on the recyclerview.
Here is my fragment class:
public class fragment_main extends Fragment {
View view;
private RecyclerView mainrecyclerview;
private List<MainSchedule> listStr;
public fragment_main() {}
#NonNull
#Override
public View onCreateView(LayoutInflater inflater, #NonNull ViewGroup container, #NonNull Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_main, container, false);
mainrecyclerview = (RecyclerView) view.findViewById(R.id.todayRecyclerView);
MainRecyclerViewAdapter mainAdapter = new MainRecyclerViewAdapter(getActivity(), listStr);
mainrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
mainrecyclerview.setAdapter(mainAdapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listStr = new ArrayList<>();
listStr.add(new MainSchedule("one"));
listStr.add(new MainSchedule("two"));
listStr.add(new MainSchedule("three"));
}
}
fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragment_main">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/todayRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="32dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="32dp"
android:layout_marginBottom="250dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
recyclerviewadapter class:
public class MainRecyclerViewAdapter extends RecyclerView.Adapter<MainRecyclerViewAdapter.ViewHolder> {
Context mContext;
List<MainSchedule> mData;
public MainRecyclerViewAdapter(Context context, List<MainSchedule> data){
this.mContext = context;
this.mData = data;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.mainschedule_cards, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(mData.get(position).getName());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textViewClass);
}
}
}
I've tried many ways of creating the adapter and binding the layout manager to the recyclerview, but nothing seems to work and I get the same error each time.
Problem seems with onCreateView because you're supposed to return view
Replace your fragment_main with code below
public class fragment_main extends Fragment {
private RecyclerView mainrecyclerview;
private List<MainSchedule> listStr;
public fragment_main() {
}
#NonNull
#Override
public View onCreateView(LayoutInflater inflater, #NonNull ViewGroup container, #NonNull Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listStr = new ArrayList<>();
listStr.add(new MainSchedule("one"));
listStr.add(new MainSchedule("two"));
listStr.add(new MainSchedule("three"));
mainrecyclerview = (RecyclerView) view.findViewById(R.id.todayRecyclerView);
MainRecyclerViewAdapter mainAdapter = new MainRecyclerViewAdapter(getActivity(), listStr);
mainrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
mainrecyclerview.setAdapter(mainAdapter);
}
}
I'm making an app that displays the same menus for different users, each menu being a fragment, but depending on the user certain things are visible and others aren't.
However, when I try to set a component's visibility as GONE I get a null pointer exception error, I'm still testing so I'm only using a textView on the fragment xml.
I've already tried initializing both the TextView and the FragmentMenuEncomenda, the class of the fragment I'm using, objects, both inside the if clause before the onCreate() method, and after the setContentView(), like the tabLayout and viewPager.
The if clause was only to make sure the user type was correct and the code in question is as follows:
public class PaginaInicialCliente extends AppCompatActivity {
private SharedPreferences sharedpreferences;
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pagina_inicial_cliente);
tabLayout = findViewById(R.id.tabLayoutCliente);
viewPager = findViewById(R.id.viewPagerCliente);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
//fragments a adicionar
adapter.addFragment(new FragmentMenuEncomendas(), "Encomendas");
adapter.addFragment(new FragmentMenuOpcoes(), "Opções");
//inicializar o tab layout
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
sharedpreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
if (sharedpreferences.getInt("tipo",0)==3) {
Log.d("USER_DEBUG","Cliente");
FragmentMenuEncomendas fragmentMenuEncomendas = new FragmentMenuEncomendas();
//THE ERROR IS HERE
fragmentMenuEncomendas.getActivity().findViewById(R.id.textViewEncomendas).setVisibility(View.GONE);
}
}
}
The FragmentMenuEncomenda class:
public class FragmentMenuEncomendas extends Fragment {
View v;
public FragmentMenuEncomendas(){
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.encomendas_fragment, container, false);
return v;
}
}
The xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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">
<TextView
android:id="#+id/textViewEncomendas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
All the answers I've searched didn't work, I don't know if it's because I'm trying to change the visibility inside the on create method.
Because view is not created when you call the function.
public class FragmentMenuEmpresas extends Fragment {
View v;
View textView;
boolean isTextViewShow = false;
boolean isViewCreated = false;
public FragmentMenuEmpresas() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.empresas_fragment, container, false);
textView = v.findViewById(R.id.textViewEncomendas);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (isTextViewShow) {
textView.setVisibility(View.VISIBLE);
} else {
textView.setVisibility(View.GONE);
}
isViewCreated = true;
}
void setIsTextViewShow() {
if (isViewCreated) {
textView.setVisibility(View.VISIBLE);
} else {
isTextViewShow = true;
}
}
void setIsTextViewGone() {
if (isViewCreated) {
textView.setVisibility(View.GONE);
} else {
isTextViewShow = false;
}
}
}
then you can call the setIsTextViewShow or setIsTextViewGone anytime you want
FragmentMenuEncomendas fragmentMenuEncomendas = new FragmentMenuEncomendas();
fragmentMenuEncomendas.setIsTextViewShow();//show
fragmentMenuEncomendas.setIsTextViewGone();//gone
I have two fragments ListNav and SwipeNav in Navigation Drawer. ListNav shows list view of data from String array. SwipeNav shows data as swipe views of the same data from string array.
I am using single fragment for viewpager swipe views multiple tabs.
My problem is :
When I click on B in List View, it shows A in SwipeNav,
When I click on C in List View, it shows A in SwipeNav,
When I click on D in List View, it shows A in SwipeNav,
When I click on E in List View, it shows A in SwipeNav,
I want to get result:
If I click on B in List View, it will show B in SwipeNav,
If I click on C in List View, it will show C in SwipeNav,
If I click on D in List View, it will show D in SwipeNav
String Array:
<string-array name="tab_titles">
<item>A</item>
<item>B</item>
<item>C</item>
<item>D</item>
<item>E</item>
<item>F</item>
<item>G</item>
<item>H</item>
<item>I</item>
........
</string-array>
I ListNav I use below to replace to SwipeNav with OnItemClickListener:
ListNav:
public class ListNav extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
return inflater.inflate(R.layout.nav_lis_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.fragment12, new ListNavAdapter());
ft.commit();
ListNavAdapter:
public class ListNavAdapter extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.nav_list_layout, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tab_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String[] tabTitlesArray = getContext().getResources().getStringArray(R.array.tab_titles);
Bundle bundle = new Bundle();
bundle.putString("tab_titles", tabTitlesArray[i].toString());
SwipeNav fragobj = new SwipeNav();
fragobj.setArguments(bundle);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(((ViewGroup)(getView().getParent())).getId(), fragobj);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
});
}
In SwipeNav:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (getArguments() != null && !getArguments().isEmpty()) {
Bundle bundle = this.getArguments();
String myInt = bundle.getString("tab_titles");
}
return inflater.inflate(R.layout.nav_swipe, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myPagerAdapter = new MyPagerAdapter(getChildFragmentManager(),getContext());
viewPager = (ViewPager) view.findViewById(R.id.pager);
viewPager.setAdapter(myPagerAdapter);
}
This is MyPagerAdapter:
public class MyPagerAdapter extends FragmentStatePagerAdapter {
private Context context;
private String[] tabTitlesArray = null;
public MyPagerAdapter(FragmentManager fm, Context context) {
super(fm);
tabTitlesArray = context.getResources().getStringArray(R.array.tab_titles);
this.context= context;
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new AFragment();
Bundle args = new Bundle();
args.putString(AFragment.ARG_OBJECT, tabTitlesArray[i]);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return tabTitlesArray.length;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
Single fragment for tabbed activity AFragment:
public class AFragment extends Fragment {
public static final String ARG_OBJECT = "object";
public AFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(R.id.text1)).setText(args.getString(ARG_OBJECT));
return rootView;
}
nav_lis_layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment12"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
nav_list_layout:
<?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:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
I searched all answers in Stackoverflow. But fail to solve my problem why particular item click not showing same item to the next fragment.
I need your help plz.
you should not put into string commas
"tabTitlesArray[i]"
try with
""+tabTitlesArray[i]
When I click on B in List View, it shows A in SwipeNav,
The problem is because you are sending the same object but with different keys.
What you have to do is, in your onClick get the position of your adapter and put it to your bundle
bundle.putString("tab_titles", tabTitlesArray[i].toString());
Then you get the value using String myString = bundle.getString("tab_titles");
And then when you create the adapter, you can send the String via parameter and put the text in your adapter, anyways the code is a mess... It's very hard to understand.
In your SwipeNav, after you setup the ViewPager, you have not use viewPager.setCurrentItem() to change to your desired page. Since setCurrentItem() needs an integer argument, so the clicked position in the list needs to pass from ListNavAdapter to SwipeNav.
ListNavAdapter.java:
public class ListNavAdapter extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.nav_list_layout, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tab_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getActivity(), "Item: " + (i +1), Toast.LENGTH_SHORT).show();
String[] tabTitlesArray = getContext().getResources().getStringArray(R.array.tab_titles);
Bundle bundle = new Bundle();
bundle.putString("tab_titles", tabTitlesArray[i].toString());
bundle.putInt("tab_int", i); //Added
// set Fragmentclass Arguments
SwipeNav fragobj = new SwipeNav();
fragobj.setArguments(bundle);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(((ViewGroup)(getView().getParent())).getId(), fragobj);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
//Fragment f=getFragmentManager().findFragmentById(R.id.fragment12);
// if(f==null){
// getFragmentManager().beginTransaction().replace(((ViewGroup)(getView().getParent())).getId(), new SwipeNav()).commit();
// }
}
});
}
// Toast.makeText(getActivity(), "Item: " + (position +1), Toast.LENGTH_SHORT).show();
// Create new fragment and transaction
}
SwipeNav.java:
public class SwipeNav extends Fragment {
private MyPagerAdapter myPagerAdapter;
private ViewPager viewPager;
private int tab_int; //Added
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
//String passingString = getArguments().getString("TAG");
if (getArguments() != null && !getArguments().isEmpty()) {
Bundle bundle = this.getArguments();
String myInt = bundle.getString("tab_titles");
tab_int = bundle.getInt("tab_int"); //Added
return inflater.inflate(R.layout.nav_swipe, container, false);
} else {
return inflater.inflate(R.layout.nav_swipe, container, false);
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myPagerAdapter = new MyPagerAdapter(getChildFragmentManager(),getContext());
viewPager = (ViewPager) view.findViewById(R.id.pager);
//viewPager.setId( R.id.pager );
viewPager.setAdapter(myPagerAdapter);
viewPager.setCurrentItem(tab_int); //Added
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Satyanusaran Bengali");
}
}
Hope that helps!
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!