I am writing an app using tabbed activity (created with a wizard, Android Studio 1.4.1). I am having troubles trying to put my own fragment for second tab. For the code below, the line (as suggested in [1])
fragment = new ExplanationFragment();
causes following error: Incompatible types. Required: android.support.v4.app.Fragment. Found: ...ExplanationFragment. I tried as well
fragment = ExplanationFragment.newInstance;
with the same result.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
// return PlaceholderFragment.newInstance(position);
Fragment fragment = null;
switch (position) {
case 1:
fragment = new ExplanationFragment();
break;
default:
fragment = PlaceholderFragment.newInstance(position);
break;
}
return fragment;
}
The fragment itself is just created with the wizard:
package ...;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ExplanationFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private OnFragmentInteractionListener mListener;
public static ExplanationFragment newInstance(String param1, String param2) {
ExplanationFragment fragment = new ExplanationFragment();
Bundle args = new Bundle();
return fragment;
}
public ExplanationFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_explanation_fragment, container, false);
}
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;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
I actually expect the solution to lie somewhere completely else (some xml maybe, or particular Fragment class), but can't track it down precisely. Is it at all possible to use several different classes of fragments with a FragmentPagerAdapter?
[1] Android Tabbed Activity: Action Bar Tabs with ViewPager: different layout for each tab