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);
Related
I have two fragment inside a LinearLayout.
When I click on a FAB button I would like to hide one but a
null object reference appears on FragmentTransaction hide method.
Why doesn't "f" have a view reference?
public class FragmentOne extends Fragment {
public FragmentOne() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View returnView = inflater.inflate(R.layout.fragment_one, container, false);
FloatingActionButton fabTemp = returnView.findViewById(R.id.fabTemp);
final Fragment f = getActivity().getSupportFragmentManager().getFragments().get(0).getChildFragmentManager().getFragments().get(1);
final FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
fabTemp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
transaction.setCustomAnimations(android.R.animator.fade_in,
android.R.animator.fade_out);
if (f.isHidden()) {
transaction.show(f);
} else {
transaction.hide(f);
}
transaction.commit();
}
});
return returnView;
}
I solved in another way despite not being as i wanted
final View frag = getView().findViewById(R.id.frgSettemp);
frag.setVisibility(View.GONE);
In onCreateView just inflate and return the view.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View returnView = inflater.inflate(R.layout.fragment_one, container, false);
return returnView;
}
Try the other processing in onViewCreated #override method. like this
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
FloatingActionButton fabTemp = getView().findViewById(R.id.fabTemp);
final Fragment f = getActivity().getSupportFragmentManager().getFragments().get(0);
final FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
fabTemp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
transaction.setCustomAnimations(android.R.animator.fade_in,
android.R.animator.fade_out);
if (f.isHidden()) {
transaction.show(f);
} else {
transaction.hide(f);
}
transaction.commit();
}
});
}
Hope this will help.
You should call only
final Fragment f = getActivity().getSupportFragmentManager().getFragments().get(0);
or
final Fragment f = getActivity().getSupportFragmentManager().getFragments().get(1);
What you have done will return null for sure.
Is it possible to pass data from an Activity using Bundle to a Fragment that has no OnCreate
Try this one
public class SampleActivity extends AppCompactActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
if (savedInstanceState == null) {
Fragment fragment = new SampleFragment();
Bundle args = new Bundle();
args.putInt("sample_int", 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction()
.add(R.id.container, fragment)
.commit();
}
}
}
public class SampleFragment extends Fragment {
#Override
public void onResume() {
Bundle args = getArguments();
if (args != null) {
int sampleInt = args.getInt("sample_int", -1);
}
}
}
From Activity, you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
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();
I wanna inflate some fragment from an activity (which is not main but is activity).
I do exactly like this instruction:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
YourFragment fragment = new YourFragment();
fragmentTransaction.replace(android.R.id.content, fragment);//here is the error
fragmentTransaction.commit();
but in the one before last line, editor shows error saying:
2nd argument wrong type.Found:max.mzf.max.fragment.Required:android.app.fragment
this is my own code:
Activity
public class QuizCard extends FragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_card);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
QcardFragment fragment = new QcardFragment();
fragmentTransaction.replace(R.id.your_placeholder, fragment );
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.card_menu, menu);
return true;
}
and this is QcardFragment:
public class QcardFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get data from Argument
}
public void onCardClick(View view) {
flipCard();
}
private void flipCard() {
View rootLayout = (View) getActivity().findViewById(R.id.main_activity_root);
View cardFace = (View) getActivity().findViewById(R.id.main_activity_card_face);
View cardBack = (View) getActivity().findViewById(R.id.main_activity_card_back);
FlipAnimation flipAnimation = new FlipAnimation(cardFace, cardBack);
if (cardFace.getVisibility() == View.GONE) {
flipAnimation.reverse();
}
rootLayout.startAnimation(flipAnimation);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.qcardfragment, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
What's wrong?
Make sure that your fragment class extends Fragment from android native library. If you are using external implementation try to change
FragmentManager fragmentManager = getFragmentManager();
to
FragmentManager fragmentManager = getSupportFragmentManager();
I am creating a five tabs that contains one fragment each.
I am using ListView in the first tab and in the ListView OnItemClickListener I want to replace from the first Tab Fragment to second tab Fragment.
How can I do that by using Fragment and TabHost?
I extends Fragment for main class and all fragment classes. I am not extends FragmentActivity. So how can I change the tab from one fragment to another fragment?
MainClass:
public class TabsFragment extends Fragment implements OnTabChangeListener {
private View mRoot;
public TabHost mTabHost;
private int mCurrentTab;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.tabs_fragment, null);
mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
setupTabs();
return mRoot;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(mCurrentTab);
// manually start loading stuff in the first tab
updateTab("1");
}
private void setupTabs() {
mTabHost.setup(); // important!
mTabHost.addTab(newTab("1", R.drawable.fragment1, R.id.fragment1));
mTabHost.addTab(newTab("2", R.drawable.fragment2, R.id.fragment2));
mTabHost.addTab(newTab("3", R.drawable.fragment3, R.id.fragment3));
mTabHost.addTab(newTab("4", R.drawable.fragment4, R.id.fragment4));
mTabHost.addTab(newTab("5", R.drawable.fragment5, R.id.fragment5));
}
private TabSpec newTab(String tag, int labelId, int tabContentId) {
Log.d(TAG, "buildTab(): tag=" + tag);
View indicator = LayoutInflater.from(getActivity()).inflate(
R.layout.tab,
(ViewGroup) mRoot.findViewById(android.R.id.tabs), false);
((ImageView) indicator.findViewById(R.id.imageView1)).setImageResource(labelId);
TabSpec tabSpec = mTabHost.newTabSpec(tag);
tabSpec.setIndicator(indicator);
tabSpec.setContent(tabContentId);
return tabSpec;
}
#Override
public void onTabChanged(String tabId) {
updateTab(tabId);
mCurrentTab = Integer.valueOf(tabId) - 1;
}
private void updateTab(String tabId) {
FragmentManager fm = getFragmentManager();
if (fm.findFragmentByTag(tabId) == null) {
if (tabId.equals("1"))
fm.beginTransaction().replace(R.id.fragment1, new Fragment1(), tabId).commit();
else if (tabId.equals("2"))
fm.beginTransaction().replace(R.id.fragment2, new Fragment2(), tabId).commit();
else if (tabId.equals("3"))
fm.beginTransaction().replace(R.id.fragment3, new Fragment3(), tabId).commit();
else if (tabId.equals("4"))
fm.beginTransaction().replace(R.id.fragment4, new Fragment4(), tabId).commit();
else if (tabId.equals("5"))
fm.beginTransaction().replace(R.id.fragment5, new Fragment5(), tabId).commit();
}
}
}
Fragment1:
public class Fragment1 extends Fragment implements OnItemClickListener {
ListView listView;
View theView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
theView = inflater.inflate(R.layout.fragment1, container, false);
listView = (ListView)theView.findViewById(R.id.list);
listView.setOnItemClickListener(this);
return theView;
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here I want to switch from 1st Tab(Fragment1) to 2nd Tab(Fragment2)
// How can I switch from 1st tab to 2nd tab here???
// Below code is not worked for me.
Fragment2 newFragment = new Fragment2();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.map, newFragment);
transaction.commit();
}
}
Fragment2:
public class Fragment2 extends SupportMapFragment {
private LatLng mPosFija = new LatLng(37.878901,-4.779396);
GoogleMap mapView;
public Fragment2() {
super();
}
public static Fragment2 newInstance(LatLng posicion) {
Fragment2 frag = new Fragment2();
frag.mPosFija = posicion;
return frag;
}
#Override
public void onResume() {
super.onResume();
initMap();
}
#Override
public void onCreate(Bundle arg0) {
super.onCreate(arg0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view = inflater.inflate(R.layout.fragment2, container, false);
view.setId(getId());
SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.mapview);
mapView = fm.getMap();
initMap();
return view;
}
private void initMap() {
UiSettings settings = mapView.getUiSettings();
settings.setAllGesturesEnabled(true);
settings.setMyLocationButtonEnabled(true);
mapView.addMarker(new MarkerOptions().position(mPosFija).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon)));
}
}
Check out my post. This contains all you need with basic.
Dynamically changing the fragments inside a fragment tab host?
NextFragment nextFrag = new NextFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.addToBackStack("next");
//container_framelayout: FrameLayout of Fragment to be replaced
transaction.replace(R.id.container_framelayout, nextFrag);
transaction.commit();