I am trying to add a fragment programatically to my layout in the MainActivity, to be more specific in its onCreate method. I keep getting an error Cannot resolve method add(), and that really shouldnt happen because I've copied the code from the official site. Somebody please help. Here is the code:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FooterVertical fragment = new FooterVertical();
fragmentTransaction.add(R.id.activity_main, fragment);
fragmentTransaction.commit();
public class FooterVertical extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FooterVertical() {
// Required empty public constructor
}
public static FooterVertical newInstance(String param1, String param2) {
FooterVertical fragment = new FooterVertical();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_footer_vertical, container, false);
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
If you are importing android.app.Fragment; change it to android.support.v4.app.Fragment;
I use this:
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new HomeFragment()).commit();
Related
On click listener not working on edit text in android
<EditText
android:id="#+id/state_search_UPFET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15sp"
android:clickable="true"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_below="#id/textView1"
android:hint="#string/hintState"
android:inputType="none"
android:padding="12sp" />
public class DoctorSearchFragment extends BaseFragment implements AbstractView, View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
private EditText SEARCH_STATE, SEARCH_CITY, DEPARTMENT;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
public static DoctorSearchFragment doctorSearchFragment;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private Button getDoctorButton;
public DoctorSearchFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static DoctorSearchFragment newInstance(String param1, String param2) {
DoctorSearchFragment fragment = new DoctorSearchFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
doctorSearchFragment=this;
setHasOptionsMenu(false);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
AppController.getInstance().getMainActivity().getSupportActionBar().setTitle(getString(R.string.search_doctor_by));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_book_appointment, container, false);
initializeComponents(view);
return view;
}
private void initializeComponents(View view) {
SEARCH_CITY = (EditText) view.findViewById(R.id.city_search_UPFET);
SEARCH_STATE = (EditText) view.findViewById(R.id.state_search_UPFET);
DEPARTMENT = (EditText) view.findViewById(R.id.dept_search_UPFET);
getDoctorButton = (Button) view.findViewById(R.id.getDoctor) ;
SEARCH_STATE.setOnClickListener(this);
SEARCH_CITY.setOnClickListener(this);
DEPARTMENT.setOnClickListener(this);
getDoctorButton.setOnClickListener(this);
//progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.state_search_UPFET:
SEARCH_STATE.setError(null);
SEARCH_STATE.setText("");
StateListDialog stateListDialog = new StateListDialog();
stateListDialog.setAppCompatActivity((AppCompatActivity) getActivity());
stateListDialog.loadData();
break;
case R.id.city_search_UPFET:
SEARCH_CITY.setError(null);
SEARCH_CITY.setText("");
CityListDialog cityListDialog = new CityListDialog();
cityListDialog.setAppCompatActivity((AppCompatActivity) getActivity());
cityListDialog.loadData(SEARCH_STATE.getText().toString());
break;
case R.id.getDoctor:
AppController.getInstance().handleEvent(AppDefines.EVENT_ID_DOCTORSLIST);
break;
}
}
public void setState(String state) {
Log.d("TAG", "FRAGMENT STATE " + state + " IS STATE NULL " + (SEARCH_STATE == null));
if (SEARCH_STATE != null) SEARCH_STATE.setText(state);
if (SEARCH_CITY != null) SEARCH_CITY.setText("");
}
public void setCity(String city) {
Log.d("TAG", "FRAGMENT STATE " + city + " IS STATE NULL " + (SEARCH_CITY == null));
if (SEARCH_CITY != null) SEARCH_CITY.setText(city);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void update() {
}
#Override
public void onFragmentResume() {
AppController.getInstance().getMainActivity().getSupportActionBar().setTitle(getString(R.string.search_doctor_by));
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public static DoctorSearchFragment getInstance() {
return doctorSearchFragment;
}
}
I have Strange problem
I Use frame layout and inside it I use Some Fragment Like Below And Handle Fragment With Bottom Bar
Now in One Of These Fragment I Use ViewPager And TabLayout Like Below
My Problem Is when Change Fragment From for exmple first to Third
First time change correctly but for
second time it does not work correctly and some thing happened like below
This is code for third Fragment Load (Just Load ViewPager)
public class Social extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private TabLayout tabLayout;
private BestMonth b,b1;
private ViewPager viewPager;
private OnFragmentInteractionListener mListener;
public Social() {
// Required empty public constructor
b= new BestMonth();
b1= new BestMonth();
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Social.
*/
// TODO: Rename and change types and number of parameters
public static Social newInstance(String param1, String param2) {
Social fragment = new Social();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_social, container, false);
viewPager = (ViewPager)view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
private void setupTabIcons() {
TextView tabOne = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.custom_tab, null);
tabOne.setText("برترین های ماه");
tabLayout.getTabAt(0).setCustomView(tabOne);
TextView tabTwo = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.custom_tab, null);
tabTwo.setText("محمبوب ترین ها");
tabLayout.getTabAt(1).setCustomView(tabTwo);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(b, "بهترین ها");
adapter.addFragment(b1, "برترین ها");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
And This Fragment Load Content Of ViewPager Inside Third Fragment
public class BestMonth extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private FloatingActionButton floatingActionButton;
private List<SocialInsClass> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private PostAdapter mAdapter;
private OnFragmentInteractionListener mListener;
public BestMonth() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static BestMonth newInstance(String param1, String param2) {
BestMonth fragment = new BestMonth();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_best_month, container, false);
view = Init(view);
return view;
}
private void prepareMovieData() {
movieList.clear();
SocialInsClass movie = new SocialInsClass("آرش", "https://ig-s-b-a.akamaihd.net/hphotos-ak-xpa1/t51.2885-19/s150x150/17267780_1886609681623949_4740572605386326016_a.jpg", "گل من", "http://nargil.ir/plant/images/pic/978/Armeria%20Maritima712.jpg");
movieList.add(movie);
movie = new SocialInsClass("راضیه", "https://ig-s-c-a.akamaihd.net/hphotos-ak-xpa1/t51.2885-19/14134653_740842746053754_866503745_a.jpg", " قابل شما رو ندار", "http://nargil.ir/plant/images/pic/978/Armeria%20Maritima308.jpg");
movieList.add(movie);
movie = new SocialInsClass("یگانه", "https://ig-s-a-a.akamaihd.net/hphotos-ak-xpa1/t51.2885-19/s150x150/17663339_736255433209640_3627796035541139456_a.jpg", "گل دون منزل من", "http://nargil.ir/plant/images/pic/978/Armeria%20Maritima953.jpg");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
}
private View Init(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_views);
floatingActionButton= (FloatingActionButton) view.findViewById(R.id.post);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getActivity(), SendPost.class));
}
});
mAdapter = new PostAdapter(movieList, getActivity());
prepareMovieData();
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Thank You So Much For Your Guide
:)
1) First Fragment 2) Third Fragment I am Using ViePager In It(Load Correctly) 3)When Choose in second time and does not work corectly
I follow the instructions on the website : http://jakewharton.github.io/butterknife/
error : java.lang.RuntimeException: Unable to start activity ComponentInfo. java.lang.RuntimeException: Unable to bind views for com.project.myapp.OneFragment.
I try to remove #Bind(R.id.btnNext) Button btnNext; and run no error.
public class OneFragment extends Fragment {
#Bind(R.id.btnNext) Button btnNext;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public OneFragment() {
// Required empty public constructor
}
public static OneFragment newInstance(String param1, String param2) {
OneFragment fragment = new OneFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
ButterKnife.bind(this, view);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Replace this:
ButterKnife.bind(this, view);
with
ButterKnife.bind(getActivity(), view);
I am working on an app for my school project in android studio that works with a navigation drawer and multiple fragments, I have got all the fragments setup and working but now I am stuck. I have no clue how to make working buttons in fragments.
Fragments activity
public class CaloriesEaten extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private static EditText caleaten;
private static EditText calalready;
private static TextView caltotal;
private static Button btnadd;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public CaloriesEaten() {
// Required empty public constructor
}
public static CaloriesEaten newInstance(String param1, String param2) {
CaloriesEaten fragment = new CaloriesEaten();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_calories_eaten,
container, false);
caleaten = (EditText) view.findViewById(R.id.CalorieInput);
calalready = (EditText) view.findViewById(R.id.Cals);
caltotal = (TextView) view.findViewById(R.id.CalNumber);
btnadd = (Button) view.findViewById(R.id.addcalories);
// Inflate the layout for this fragment
btnadd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return inflater.inflate(R.layout.fragment_calories_eaten, container, false);
}
public void buttonClicked (View view) {
int x = Integer.parseInt(caleaten.getText().toString());
int y = Integer.parseInt(calalready.getText().toString());
int total = x + y;
caltotal.setText(Integer.toString(total));
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
This is my first time asking a question here so if i'm missing anything please let me know.
Thanks!
View override by inflating at end of onCreateView() method
Replace
return inflater.inflate(R.layout.fragment_calories_eaten, container, false);
to
return view;
in onCreateView() method
Funny reason: You are inflating a View, using it to get it's children and finally returning different inflated view instance. You should return the same instance you are inflating initially and using to get it's children.
Just change
return inflater.inflate(R.layout.fragment_calories_eaten, container, false);
to
return view;
in onCreateView() method
Replace
return inflater.inflate(R.layout.fragment_calories_eaten, container, false);
to
view = inflater.inflate(R.layout.fragment_calories_eaten, container, false);
return view;
Now using this view instance you can find you other views inflating on it as button.
btnClickMe = (Button)view.findViewById(R.id.btn);
use above code in onCreateView method before returning view.
I am running into an issue where I have a fragment, which contains a tab layout/view pager which handles 3 sub fragments, and when I open the main fragment the first time all the data in the sub fragments shows up properly, but when I re-open the main fragment again (clicking on a seperate listview item), the data does not get populated properly (even though it exists).
I also noticed that the only time the sub-fragment gets its data is when view paging over to the last tab, or when rotating the screen. Also, when I try to move the screen to the right using the view pager the tab indicator will get stuck mid way between the first and second tab.
What can I do to fix this issue?
Fragment Adapter
public class DetailFragmentPagerAdapter extends FragmentPagerAdapter {
Context context;
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[] { "Plot", "Trailers", "Reviews" };
private Movie movie;
public DetailFragmentPagerAdapter(FragmentManager fm, Context context, Movie movie) {
super(fm);
this.context = context;
this.movie = movie;
}
#Override
public Fragment getItem(int position) {
if(position == 0){
return PlotFragment.newInstance(movie);
} else if (position == 1){
return TrailerFragment.newInstance();
} else if (position == 2){
return ReviewFragment.newInstance();
} else {
Log.e("RETURNING NULL", "RETURNING NULL");
return null;
}
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
Main Fragment
public class MovieItemDetailFragment extends Fragment implements View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
public String TAG = MovieItemDetailFragment.class.getCanonicalName();
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private View view;
private TextView tvTitle, tvReleaseDate, tvRating;
private ImageView ivMoviePoster;
private Movie movie;
private Handler handler;
private Button btnFavorite;
private boolean isFavorited = false;
private View.OnClickListener mOnClickListener;
private ViewPager viewpager;
private TabLayout tablayout;
private DetailFragmentPagerAdapter adapter;
// TODO: Rename and change types and number of parameters
public static MovieItemDetailFragment newInstance(String param1, String param2) {
MovieItemDetailFragment fragment = new MovieItemDetailFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public MovieItemDetailFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_movie_item_detail, container, false);
init();
return view;
}
private void init() {
handler = new Handler();
this.movie = (Movie) getArguments().getSerializable("MOVIE");
tvTitle = (TextView) view.findViewById(R.id.tvTitle);
tvReleaseDate = (TextView) view.findViewById(R.id.tvReleaseDate);
tvRating = (TextView) view.findViewById(R.id.tvAvgRating);
ivMoviePoster = (ImageView) view.findViewById(R.id.ivMoviePoster);
btnFavorite = (Button) view.findViewById(R.id.btnFavorite);
btnFavorite.setOnClickListener(this);
viewpager = (ViewPager) view.findViewById(R.id.pager);
tablayout = (TabLayout) view.findViewById(R.id.sliding_tabs);
adapter = new DetailFragmentPagerAdapter(getActivity().getSupportFragmentManager(),
getActivity(), getMovie());
viewpager.setAdapter(adapter);
adapter.notifyDataSetChanged();
tablayout.post(new Runnable() {
#Override
public void run() {
tablayout.setupWithViewPager(viewpager);
}
});
mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
isFavorited = true;
btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_content_selector));
}
};
setElementValues();
}
private void setElementValues() {
handler.post(new Runnable() {
#Override
public void run() {
tvTitle.setText(getMovie().getTitle());
tvReleaseDate.setText(getMovie().getRelease_date());
tvRating.setText(String.valueOf(getMovie().getVote_average()));
Picasso.with(getActivity()).load(getMovie().getFull_poster_path()).into(ivMoviePoster);
if (isFavorited) {
btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_content_selector));
} else {
btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_blank_content_selector));
}
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#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 onClick(View v) {
switch (v.getId()) {
case R.id.btnFavorite:
if (isFavorited) {
isFavorited = false;
btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_blank_content_selector));
showSnackbar("I thought that was one of your favorites.");
} else {
isFavorited = true;
btnFavorite.setBackground(getActivity().getResources().getDrawable(R.drawable.favorite_content_selector));
}
break;
}
}
private void showSnackbar(String msg) {
Snackbar
.make(view, msg, Snackbar.LENGTH_LONG)
.setAction(R.string.snackbar_action, mOnClickListener)
.setActionTextColor(getActivity().getResources().getColor(R.color.material_yellow_400))
.show();
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
public Movie getMovie() {
return movie;
}
}
Instead of calling
adapter = new DetailFragmentPagerAdapter(getActivity().getSupportFragmentManager(), getActivity(), getMovie());
try:
adapter = new DetailFragmentPagerAdapter(getChildFragmentManager(), getActivity(), getMovie());
This is also working for me.
Basically, the difference is that Fragment's now have their own internal FragmentManager that can handle Fragments. The child FragmentManager is the one that handles Fragments contained within only the Fragment that it was added to. The other FragmentManager is contained within the entire Activity.
for further detail about getChildFragmentManager()
visit this question
[What is difference between getSupportFragmentManager() and getChildFragmentManager()?