The buttons don't work when I change into landscape mode and back to portrait. Anyways, here is my code:
public class fragmentone extends Fragment {
Button biological;
Button natural;
View myView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.firstlay, container, false);
biological = (Button) myView.findViewById(R.id.biological);
biological.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BiologicalHazards fragment = new BiologicalHazards();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().addToBackStack("hi")
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container1, fragment)
.commit();
}
});
natural = (Button) myView.findViewById(R.id.natural);
natural.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NaturalHazards fragment = new NaturalHazards();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().addToBackStack("hi")
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container1, fragment)
.commit();
}
});
return myView;
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
getActivity().setContentView(R.layout.firstlay);
}else{
getActivity().setContentView(R.layout.firstlay);
}
}
}
Does anyone know how to solve this? Any help is appreciated and thanks in advance.
you need to add setRetainInstance(true); //to your fragment onCreateView()
Also needn't be doing this getActivity().setContentView(R.layout.firstlay); in your onConfigurationChanged() method.
Hope this help :)
I think You to have re initilize when change orientation
try your modified code
private LayoutInflater inflater;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myView = inflater.inflate(R.layout.firstlay, container, false);
reInitilize(myView);
return myView;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
myView = inflater.inflate(R.layout.firstlay, null);
reInitilize(myView);
}else{
myView = inflater.inflate(R.layout.firstlay, null);
reInitilize(myView);
}
}
private void reInitilize(View myView) {
// TODO Auto-generated method stub
biological = (Button) myView.findViewById(R.id.biological);
biological.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BiologicalHazards fragment = new BiologicalHazards();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().addToBackStack("hi")
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container1, fragment)
.commit();
}
});
natural = (Button) myView.findViewById(R.id.natural);
natural.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NaturalHazards fragment = new NaturalHazards();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().addToBackStack("hi")
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
.replace(R.id.container1, fragment)
.commit();
}
});
}
You don't need to do handle orientation your self just to change your layout. Create 2 files with this same name R.layout.fistlay. One in res/layout, one in res/layout-land. Android will automatically pick the right one base on the orientation.
you could implement the method
#Override
protected void onSaveInstanceState(Bundle bundle){
// store some variable like boolean, ints, String to the bundle
bundle.putBoolean('currentFragment', isInFragmentA);
// call the default method
super.onSaveInstanceState(bundle);
}
After this, you could check if you are on a configuration change as following:
void onCreate(Bundle bundle){
if (bundle == null){
//start the activity as the use is opening the app as normal
} else {
// bundle is not null
//get back the variable you have store and act accordingly
// e.g do some FragmentTransition
}
}
Hope this help
Related
On click of Button I am trying to open second fragment(YourResultFragment.java),
I had a lots but don't know why it is not working , here is my code which I am using
public class KnowYourBodyFragment extends Fragment {
public KnowYourBodyFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_know_your_body, container, false);
Button button = (Button)rootView.findViewById(R.id.button2);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Fragment mFragment = new YourResultFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.know_your_body_container, mFragment ).commit();
}
});
// Inflate the layout for this fragment
return rootView;
}
Use this Try to replace it with Default Container android.R.id.content.
Button button = (Button)rootView.findViewById(R.id.button2);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Fragment newFragment = new YourResultFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
// Replace whatever is in the fragment_container view with this
// fragment,
// and add the transaction to the back stack
transaction.replace(android.R.id.content, newFragment);
transaction.addToBackStack("tag");
// Commit the transaction
transaction.commitAllowingStateLoss();
}
});
What is transaction.addToBackStack("tag") ?
Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.
Iam new to android .I need to go back to the FragmentActivity from fragment page.
My work flow is:
MainActivity->ProfileActivity->ProfilePhotoEditFragment
I need to go back to
ProfilePhotoEditFragment -> ProfileActivity
manifest
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
ProfilePhotoEditFragment.java
public class ProfilePhotoEditFragment extends Fragment implements OnClickListener {
ViewUtils mViewUtils;
Bundle mSavedInstanceState;
private OnNavigateProfileListener mOnNavigateProfileListener;
private Button mCancelButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context mContext = getActivity().getApplicationContext();
mViewUtils = new ViewUtils(mContext);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mSavedInstanceState = savedInstanceState;
View view = inflater.inflate(R.layout.fragment_edit_profile_pic, container, false);
mCancelButton = (Button) view.findViewById(R.id.cancel);
mCancelButton.setOnClickListener(this);
return view;
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onClick(View view) {
if (view.getId() == mCancelButton.getId()){
onBackPressed();
}
}
public void onBackPressed() {
// do something on back.
return;
}
}
remove current fragment ProfilePhotoEditFragment in onBackPressed()
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
//( "stackzeo");
} else {
getSupportFragmentManager().popBackStack();
removeCurrentFragment();
//("stacknotzeo");
}
..
public void removeCurrentFragment() {
Fragment currentFrag = (Fragment) getFragmentManager()
.findFragmentById(R.id.content_frame);
if (currentFrag != null)
getFragmentManager().beginTransaction().remove(currentFrag);
getFragmentManager().beginTransaction().commit();
}
Call findFragmentById() on FragmentManager and determine which fragment is in your R.id.content_frame container.
Thank you All. this my working code
....
#Override
public void onClick(View view) {
if (view.getId() == mCancelButton.getId()){
getActivity().getSupportFragmentManager().popBackStack();
removeCurrentFragment();
}
}
public void removeCurrentFragment()
{
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
Fragment currentFrag = getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_common_profile_layout);
String fragName = "NONE";
if (currentFrag!=null)
fragName = currentFrag.getClass().getSimpleName();
if (currentFrag != null)
transaction.remove(currentFrag);
transaction.commit();
}
getActivity().onBackPressed();
You should be able to call this code from every fragment.
Please check, if getActivity() returns null.
Hope this helps.
just write down
public void onBackPressed(){
super.onBackPressed();
}
i created an activity that contains 5 fragments and one of the fragments contains a profile page and i created another activity to edit the profile page but when i click the save button to return to the Edit (fragment) . The app crashes..
i need help or suggestions
this is my Fragment code below :
public class MeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.me, container, false);
Button bt = (Button) view.findViewById(R.id.btedit);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getActivity(), Editme.class);
startActivity(i);
}
});
return view;
}
and this is the Editme Class:
Button btnLoad = (Button) findViewById(R.id.btsave);
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
MeFragment save = new MeFragment();
fragmentTransaction.add(R.id.fragment_content, save);
fragmentTransaction.commit();
}
};
btnLoad.setOnClickListener(listener);
If you opened another activity and after making some changes you'd like to go back to previous activity(with 5 fragments) simply call finish method instead of doing fragment transaction.
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
}
Could you anyone advice me how to implement saveFragmentInstanceState() or some other methods to retrieving fragment instance when back button is pressed. I use own stack for fragment, viz code bellow:
public class stackA extends ActivityInTab {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackA", "onCreate");
if(savedInstanceState == null){
navigateTo(new fragmentA());
}
}
}
Next there is implementation of ActivityInTab class. I think for this class must be implemented methods for saving and retrieving fragment state but still I can't find the way how to do this.
abstract class ActivityInTab extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_tab);
Log.i("ActivityInTab", "onCreate");
}
protected void navigateTo(Fragment newFragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content, newFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
#Override
public void onBackPressed() {
Log.i("ActivityInTab", "onBackPressed");
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 1) {
super.onBackPressed();
} else {
// Otherwise, ask user if he wants to leave :)
//showExitDialog();
super.onBackPressed();
}
}
}
And finally, this is imlementation of Fragments:
public class fragmentA extends Fragment {
private LinearLayout ll;
private FragmentActivity fa;
private String textViewText;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("Fragment A", "onCreateView");
fa = super.getActivity();
ll = (LinearLayout) inflater.inflate(R.layout.fragmenta, container,
false);
Button next = (Button) ll.findViewById(R.id.button1);
Button randomBtn = (Button) ll.findViewById(R.id.random_button);
final TextView randomText = (TextView) ll
.findViewById(R.id.random_textview);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
((ActivityInTab) getActivity()).navigateTo(new
fragmentB());
}
});
randomBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
randomText.setText(String.valueOf(Math.random()));
textViewText = randomText.getText().toString();
}
});
if (savedInstanceState != null) {
randomText.setText(savedInstanceState.getString("TextView"));
}
return ll;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// setRetainInstance(true);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("TextView", textViewText);
}
}
I'm able to save instance state only for orientation changes using onSaveInstanceState(Bundle outState), but no for back button.
I would be very grateful for any advice, thanks.
In the onBackPressed Method you have access to the FragmentManager which can retrieve any fragment for you using the FragmentManager methods "findFragmentById" or "findFragmentByTag".
You can get direct access to any fragment whos state you want to save using either of those two methods depending on how you added the fragments.
I'm starting with fragments and I'm facing a problem. I wan't to restore my fragment after a screen rotation.
My app looks like this: on landscape I have a button on the left area, which updates the a label on the right area. If on portrait mode, I'm navigating to a new activity. However, I wan't to maintain the fragment state after rotating.
Code looks like this:
Left area fragment:
public class ListFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
Button button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
updateDetail();
break;
}
}
public void updateDetail() {
String newTime = String.valueOf(System.currentTimeMillis());
DetailFragment fragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detailFragment);
if (fragment != null && fragment.isInLayout()) {
fragment.setText(newTime);
} else {
Intent intent = new Intent(getActivity().getApplicationContext(),
DetailActivity.class);
intent.putExtra("value", newTime);
startActivity(intent);
}
}
}
Right area activity:
public class DetailActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
if (savedInstanceState == null) {
setContentView(R.layout.activity_detail);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String s = extras.getString("value");
TextView view = (TextView) findViewById(R.id.detailsText);
view.setText(s);
}
}
}
}
Right area fragment:
public class DetailFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragment_detail, container, false);
return view;
}
public void setText(String item) {
TextView view = (TextView) getView().findViewById(R.id.detailsText);
view.setText(item);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getFragmentManager();
DetailFragment fragment = (DetailFragment)fm.findFragmentById(R.id.detailFragment);
if (fragment == null) {
fragment = new DetailFragment();
fragment.setTargetFragment(this, 0);
fm.beginTransaction().add(R.id.detailFragment, fragment).commit();
}
}
}
What can I possibly be doing wrong?
You have a few options you can use the Bundle in a couple of methods to save and restore the state of the fragments.
Or you can possibly use the setRetainInstance method:
onCreate(Bundle save)
{
super.onCreate(save);
setRetainInstance(true);
}
Keep in mind that the setRetainInstance method doesn't work for fragments in the backstack.
#Override
public void onConfigurationChanged(Configuration newConfig) {
int orientation = getResources().getConfiguration().orientation;
switch (orientation) {
case Configuration.ORIENTATION_LANDSCAPE:
getSupportFragmentManager().beginTransaction().replace(R.id.detailFragment, new DetailFragment()).commitAllowingStateLoss();
getSupportFragmentManager().beginTransaction().remove(new DetailFragment()).commitAllowingStateLoss();
break;
case Configuration.ORIENTATION_PORTRAIT:
getSupportFragmentManager().beginTransaction().replace(R.id.detailFragment, new DetailFragment()).commitAllowingStateLoss();
getSupportFragmentManager().beginTransaction().remove(new DetailFragment()).commitAllowingStateLoss();
break;
}
super.onConfigurationChanged(newConfig);
}
You can check on the onConfigurationChange and ensure that your fragment state is not lost by doing a commitAllowingStateLoss