Multiple Fragment Instances - android

I have created a fragment I would like to add multiple instances of:
public class myFragment extends Fragment {
int id;
public static myFragment newInstance(int id) {
myFragment fragment = new myFragment();
int id = id;
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView idText = (TextView)
rootView.findViewById(R.id.idText);
idText.setText(id);
return rootView;
}
In my Main class,
private int currentID;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
currentId = 0;
FragmentManager manager = getFragmentManager();
FragmentTransaction fragmentTransaction =
manager.beginTransaction();
oneFragment = new myFragment();
oneFragment.newInstance(currentId);
currentId = 2;
fragmentTransaction
.replace(R.id.container, oneFragment)
.commit();
twoFragment = new myFragment();
twoFragment.newInstance(currentId);
currentId = 3;
The problem is, oneFragment is coming up with id 2. I am not entirely sure why this is the case. The container is a LinearLayout with a vertical orientation and the Fragment is a linear as well. I would like to use the code I wrote for myFragment repeatedly for all of the ID's.

Your MyFragment class needs to transfer the id like this:
public class MyFragment extends Fragment {
private final static String ID_KEY = "id_key";
public int id;
public static MyFragment newInstance(int id) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putInt(ID_KEY, id);
fragment.setArguments(args);
return fragment;
}
public MyFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getInt(ID_KEY);
}
}
}
I don't think that you need to create a fragment and then call newInstance() on it. I think you can just get away with calling newInstance(). Try this:
private int currentID;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
currentId = 0;
FragmentManager manager = getFragmentManager();
FragmentTransaction fragmentTransaction =
manager.beginTransaction();
MyFragment oneFragment = MyFragment.newInstance(currentId);
currentId = 2;
fragmentTransaction
.replace(R.id.container, oneFragment)
.commit();
MyFragment twoFragment = MyFragment.newInstance(currentId);
currentId = 3;

You should pass id for each Fragment using Constructor. So, every fragment instance hold their id in member variable
public class MyFragment extends Fragment {
private int id;
// constructor
public MyFragment() {
}
public MyFragment(int a) {
this.id = a;
}
// this method is not requreied if you use above Constuctor
public myFragment newInstance(int id) {
return new myFragment(id);
}
}
Main Class :
private int currentID = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
currentId = 0;
FragmentManager manager = getFragmentManager();
FragmentTransaction fragmentTransaction =
manager.beginTransaction();
oneFragment = new myFragment(currentID); // id = 0
currentId = 2;
fragmentTransaction
.replace(R.id.container, oneFragment)
.commit();
twoFragment = new myFragment(currentID); // id = 2
currentId = 3;
}

Related

After two different fragments have been replaced, first fragment is recreated when on pressed back button

I have three fragment and one activity. It works this way:
[activity]-> [MainFragment]->[MenuFragment]->[SignUpFragment]
When [SignUpFragment] is back pressed, the [MainFragment] is created twice.
I tried setRetaInInstance(true) and I checked savedInstanceState but I can not prevent [MainFragment] recreating.
This is my MainActivity:
public class MainActivity extends AppCompatActivity {
public Bundle mSavedInstanceState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedInstanceState = savedInstanceState;
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
callMainFragment();
}
private void callMainFragment() {
if (mSavedInstanceState == null) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container_category, new MainFragment(), MainFragment.class.getSimpleName());
transaction.addToBackStack(null);
transaction.commit();
}
}
public ActionBar getMainActionBar(){
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Action Bar Display settings
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
// Custom view inflater
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Custom layout view
View viewActionBar = inflater.inflate(R.layout.action_bar, null);
// Set custom view
actionBar.setCustomView(viewActionBar);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
}
return actionBar;
}
This is my MainFragment:
public class MainFragment extends BaseFragment implements AdapterView.OnItemClickListener, BuyersGuideCategoriesDelegate, View.OnClickListener {
private Bundle mSavedInstanceState;
private BuyersGuideCategoriesFragment mCategoriesFragment;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mSavedInstanceState = savedInstanceState;
if (mSavedInstanceState == null) {
mView = inflater.inflate(R.layout.fragment_main, container, false);
// Call Grid View Buyers Guide Fragment
mCategoriesFragment = new BuyersGuideCategoriesFragment();
mCategoriesFragment.mGridViewDelegate = this;
setIcons();
setTitles();
setTexts();
initListView();
}
return mView;
}
#Override
public void onResume() {
super.onResume();
ImageView menu = (ImageView) ((MainActivity) getActivity()).getMainActionBar().getCustomView().findViewById(R.id.action_bar_menu_icon);
menu.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mSavedInstanceState == null) {
MainActivity activity = (MainActivity) getActivity();
FragmentManager manager = activity.getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container_category, new MenuFragment(),MenuFragment.class.getSimpleName());
transaction.addToBackStack(null);
transaction.commit();
}
}
}
This is my MenuFragment:
public class MenuFragment extends BaseFragment implements AdapterView.OnItemClickListener, View.OnClickListener {
private Bundle mSavedInstanceState;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mSavedInstanceState = savedInstanceState;
if (savedInstanceState == null) {
mView = inflater.inflate(R.layout.fragment_menu, container, false);
setMenuItemsListViewAdapter();
}
return mView;
}
private void setMenuItemsListViewAdapter() {
ListView menuItems = (ListView) mView.findViewById(R.id.list_menu_items);
ListMenuItemsListViewAdapter adapter = new ListMenuItemsListViewAdapter(getContext(),getMenuItemNames());
menuItems.setAdapter(adapter);
menuItems.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch ((String) parent.getAdapter().getItem(position)){
case SIGN_UP:
replaceFragment(R.id.container_category,new SignUpFragment(),SignUpFragment.class.getSimpleName());
break;
}
}
private void replaceFragment(int containerId,Fragment fragment, String fragmentTag){
if (mSavedInstanceState == null){
MainActivity activity = (MainActivity) getActivity();
FragmentManager manager = activity.getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(containerId,fragment,fragmentTag);
transaction.addToBackStack(null);
transaction.commit();
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.menu_back_icon:
replaceFragment(R.id.container_category, new MainFragment(),MainFragment.class.getSimpleName());
break;
}
}
}
And this is my SignUpFragment:
public class SignUpFragment extends BaseFragment implements View.OnClickListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (savedInstanceState == null) {
mView = inflater.inflate(R.layout.fragment_sign_up, container, false);
}
return mView;
}
}
EDIT 1: The MainFragment is recreated only when I return from SignUpFragment to MenuFragment. I am doing wrong using so many fragments? Should I use activity?
When you are move between Fragments, call addToBackStack() :
FragmentTransaction ft = fragmentManager.beginTransation();
ft.replace( R.id.fragment, new MyFragment() ).addToBackStack( "ftransaction" ).commit();
Create first Fragment:
FragmentTransaction ft = fragmentManager.beginTransation();
ft.add(R.id.container, new FirstFragment()).addToBackStack(null).commit();
Second:
FragmentTransaction ft = fragmentManager.beginTransation();
ft.replace(R.id.container, new SecondFragment()).addToBackStack(null).commit();
and Third:
FragmentTransaction ft = fragmentManager.beginTransation();
ft.replace(R.id.container, new ThirdFragment()).commit();

Custom adapter for multiple fragments in one tab of ViewPager

I want to want to make ViewPager with each tab containing three fragments. FragmentPagerAdapter only works for one fragment, so I tried my best to make my own custom adapter extending PagerAdapter. Unfortunately, the code I wrote only displays these three Fragments in the first tab and after restarting the app all tabs are blank. I suspect that it has something to do with onSaveInstanceState, but I don't know how to make it properly. Also, I've read that I shouldn't add the fragments to FragmentTransaction in instantiateItem, but I don't know where else I could do it. Could you help me ?
TaskListPagerActivity:
public class TaskListPagerActivity extends AppCompatActivity implements BottomPanelFragment.OnBottomPanelSelectedListener {
private static final String TAG = "TaskListPagerActivity";
private ViewPager mViewPager;
FragmentStacker[] mStacker;
public static Intent newInstance(Context packageContext) {
Intent intent = new Intent(packageContext, TaskListPagerActivity.class);
return intent;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_list_pager);
mStacker = new FragmentStacker[7];
mViewPager = (ViewPager) findViewById(R.id.activity_task_list_pager);
mViewPager.setAdapter(new TaskListPagerAdapter(this));
}
// Interface methods
private class TaskListPagerAdapter extends PagerAdapter {
private FragmentActivity mContext;
public TaskListPagerAdapter(FragmentActivity context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment res;
FragmentManager fm = mContext.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (mStacker[position] == null) {
mStacker[position] = new FragmentStacker();
ft.add(container.getId(), mStacker[position]);
} else {
ft.attach(mStacker[position]);
}
res = mStacker[position];
ft.commit();
return res;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
}
#Override
public int getCount() {
return 7;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return ((Fragment) object).getView()==view;
}
}}
FragmentStacker:
public class FragmentStacker extends Fragment {
Fragment[] fragments = createFragments();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.task_list_activity_fragment, container, false);
FragmentManager fm = getFragmentManager();
Fragment customDateFragment = fm.findFragmentById(R.id.custom_date_fragment_container);
Fragment taskListFragment = fm.findFragmentById(R.id.task_list_fragment_container);
Fragment bottomPanelFragment = fm.findFragmentById(R.id.bottom_panel_container);
FragmentTransaction fragmentTransaction = fm.beginTransaction();
if (customDateFragment == null) {
customDateFragment = fragments[0];
taskListFragment = fragments[1];
bottomPanelFragment = fragments[2];
fragmentTransaction.add(R.id.custom_date_fragment_container, customDateFragment);
fragmentTransaction.add(R.id.task_list_fragment_container, taskListFragment);
fragmentTransaction.add(R.id.bottom_panel_container, bottomPanelFragment);
fragmentTransaction.commit();
} else {
fragmentTransaction.attach(customDateFragment);
fragmentTransaction.attach(taskListFragment);
fragmentTransaction.attach(bottomPanelFragment);
}
return v;
}
private Fragment[] createFragments() {
return new Fragment[]{new CustomDateFragment(), new TaskListFragment(), new BottomPanelFragment()};
}}

Bundle not working (getArguments() always null) [Android]

My code was working few hours ago but not anymore, I can't see what is the reason.
Here is my listener where I change fragment after a click :
CustomMarkRow.java
public void onClick(DialogInterface dialogInterface, int i){
Bundle bundle = new Bundle();
bundle.putInt("id", CustomMarkRow.this.mark.getId());
FragmentManager fragmentManager = CustomMarkRow.this.fragmentManager;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); activity.getActionBar().setSelectedNavigationItem(CustomMarkRow.this.positionTab);
EditMarkFragment fragment = new EditMarkFragment();
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.fragmentContainer, fragment,"2");
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
At this moment, fragment.getArguments() contains what I put inside :
{android.os.Bundle#3644} "Bundle[{id=1}]"
In my second file :
EditMarkFragment.java
public class EditMarkFragment extends Fragment {
public View view;
public EditMarkFragment(){
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
this.view = inflater.inflate(getResources().getIdentifier("edit_mark", "layout",container.getContext().getPackageName()), container, false);
if(this.getArguments()==null){ // always null
...
}
return this.view
}
getArguments() always return null here, What is bad in this sample ?
* edit *
Here is my launcher class :
public class Launcher extends Activity implements ActionBar.TabListener {
private HomeFragment frag1 = new HomeFragment();
private EditMarkFragment frag2 = new EditMarkFragment();
private MarkListFragment frag3 = new MarkListFragment();
private EditCategoryFragment frag4 = new EditCategoryFragment();
private CategoryListFragment frag5 = new CategoryListFragment();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.launcher);
//Configuration de la barre d'onglet
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = getActionBar().newTab().setTabListener(this).setTag("1").setText("Home"); //.setIcon(R.drawable.homew);
getActionBar().addTab(tab1);
ActionBar.Tab tab2 = getActionBar().newTab().setTabListener(this).setTag("2").setText("New Mark"); //.setIcon(R.drawable.addw);
getActionBar().addTab(tab2);
ActionBar.Tab tab3 = getActionBar().newTab().setTabListener(this).setTag("3").setText("My Marks"); //.setIcon(R.drawable.listw);
getActionBar().addTab(tab3);
ActionBar.Tab tab4 = getActionBar().newTab().setTabListener(this).setTag("4").setText("New Category"); //.setIcon(R.drawable.categoryw);
getActionBar().addTab(tab4);
ActionBar.Tab tab5 = getActionBar().newTab().setTabListener(this).setTag("5").setText("Categories"); //.setIcon(R.drawable.categoryw);
getActionBar().addTab(tab5);
}
#Override
public void onTabSelected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
if(tab.getTag().equals("1")){
ft.replace(R.id.fragmentContainer, frag1);
}
else if(tab.getTag().equals("2")){
ft.replace(R.id.fragmentContainer, frag2);
}
else if(tab.getTag().equals("3")){
ft.replace(R.id.fragmentContainer, frag3);
}
else if(tab.getTag().equals("4")){
ft.replace(R.id.fragmentContainer, frag4);
}
else if(tab.getTag().equals("5")){
ft.replace(R.id.fragmentContainer, frag5);
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
if(tab.getTag().equals("1")){
ft.remove(frag1);
}
else if(tab.getTag().equals("2")){
ft.remove(frag2);
}
else if(tab.getTag().equals("3")){
ft.remove(frag3);
} else if(tab.getTag().equals("4")){
ft.remove(frag4);
}
else if(tab.getTag().equals("5")){
ft.remove(frag5);
}
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
}
}
While your onClick() code is creating an arguments Bundle, your onCreate() is not. If that edition of your fragment calls getArguments(), the method will return null.
1-Update your EditMark fragment with as follows:-
public class EditMarkFragment extends Fragment {
public static View view;
public static EditMarkFragment newInstance(int id) {
EditMarkFragment fragment = new EditMarkFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
this.view = inflater.inflate(getResources().getIdentifier("edit_mark", "layout",container.getContext().getPackageName()), container, false);
int id=getArguments.getInt("id");
return this.view}
2- Inside CustomMarkRow update your code as :-
public void onClick(DialogInterface dialogInterface, int i){
FragmentManager fragmentManager = CustomMarkRow.this.fragmentManager;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); activity.getActionBar().setSelectedNavigationItem(CustomMarkRow.this.positionTab);
EditMarkFragment fragment = EditMarkFragment.newInstance(CustomMarkRow.this.mark.getId()) ;
fragmentTransaction.replace(R.id.fragmentContainer, fragment,"2");
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
Try this,hope this will hep you.

Fragment to Fragment communication with FragmentStatePagerAdapter

I'm trying to update the text of my TextView in my FragmentB through the Button in my FragmentA. But whenever I click the Button, nothing happens in my TextView. What could be the problem? Here's my code:
Communicator.java:
public interface Communicator {
public void respond(String data);
}
MainActivity.java:
public class MainActivity extends FragmentActivity implements Communicator{
ViewPager viewPager = null;
FragmentManager fragmentManager = getSupportFragmentManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MyAdapter(fragmentManager));
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentB fragB = new FragmentB();
fragmentTransaction.add(R.id.pager, fragB, "frag_tag");
fragmentTransaction.commit();
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter (FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if (i == 0)
{
fragment = new FragmentA();
}
if (i == 1)
{
fragment = new FragmentB();
}
if (i == 2)
{
fragment = new FragmentC();
}
if (i == 3)
{
fragment = new FragmentD();
}
if (i == 4)
{
fragment = new FragmentE();
}
if (i == 5)
{
fragment = new FragmentF();
}
return fragment;
}
#Override
public int getCount() {
return 6;
}
}
#Override
public void respond(String data) {
// TODO Auto-generated method stub
FragmentB f2 = (FragmentB) fragmentManager.findFragmentByTag("frag_tag");
f2.changeText(data);
}
}
FragmentA:
public class FragmentA extends Fragment implements OnClickListener {
int counter = 0;
Button button1;
Communicator comm;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragmenta, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
comm = (Communicator) getActivity();
button1 = (Button) getActivity().findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter++;
comm.respond("The button was clicked" + counter + "times");
}
}
FragmentB:
public class FragmentB extends Fragment {
TextView text1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragmentb, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
text1 = (TextView) getActivity().findViewById(R.id.textView1);
}
public void changeText(String data) {
// TODO Auto-generated method stub
text1.setText(data);
}
}
The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods.
public static class MainActivity extends Activity
implements HeadlinesFragment.OnHeadlineSelectedListener{
...
public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Do something here to display that article
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);
if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...
// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
} else {
// Otherwise, we're in the one-pane layout and must swap frags...
// Create fragment and give it an argument for the selected article
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
}
For more detail please follow this link http://developer.android.com/training/basics/fragments/communicating.html#Deliver

IllegalArgumentException: No view found for id 0x7f07003c for fragment

I am new to Fragments. I tried simple fragment example. But it throws the error. I don't know what is wrong.
public class NewActivity extends Activity {
int mStackLevel = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
Fragment newFragment = NewFragment
.newInstance(mStackLevel);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
} else {
mStackLevel = savedInstanceState.getInt("level");
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("level", mStackLevel);
}
public static class NewFragment extends Fragment {
int mNum;
Context context;
static NewFragment newInstance(int num) {
NewFragment f = new NewFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
context = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.example_fragment, container,
false);
return v;
}
}
}
My logcat shows:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.FragmentExample/com.example.FragmentExample.NewActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f07003c for fragment NewFragment{40ff0850 #0 id=0x7f07003c}
ft.add(R.id.simple_fragment, newFragment).commit();
you missed setContentView for your Activity. Your Fragment can not be added without a View hierarchy.
Note : Your Fragment is hosted by an activity. So you need to set the content to the activity first.
Just replace this method with your method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(Your_layout_file);
if (savedInstanceState == null) {
Fragment newFragment = NewFragment
.newInstance(mStackLevel);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.simple_fragment, newFragment).commit();
} else {
mStackLevel = savedInstanceState.getInt("level");
}
}
you missed this line setContentView(Your_layout_file);
This answer highlights a silly mistake that may occur, that arises when nesting fragments or you are converting activities to fragments.
If you are trying to replace a fragment within a fragment with the fragmentManager but you are not inflating the parent fragment that can cause an issue.
In BaseFragment.java OnCreateView:
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.container, new DifferentFragment())
.commit();
}
return super.onCreateView(inflater, container, savedInstanceState);
Replace super.onCreateView(inflater, container, savedInstanceState);
with inflating the correct layout for the fragment:
return inflater.inflate(R.layout.base_fragment, container, false);

Categories

Resources