0

I am new to fragment concept. In my app I have to save user preferences. I have gone through this doc. Prepared my preferences xml file and PreferenceFragment file. Everything is fine up to now. My problem is, I have to add the following code in my onCreate() method of my MainActivity

getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new SettingsFragment())
            .commit();

It is showing on Main screen. But I want to launch this on a button click method

 onSettingsClicked(){
         // launch preferces screen
    }

And I want to display it as a separate screen. How can I do that?

Pradip
  • 3,189
  • 3
  • 22
  • 27
saa
  • 1,538
  • 2
  • 17
  • 35

2 Answers2

1

You need to implement the concept of fragmentTransaction. You need to do the following things-

  1. Create a new Fragment.xml to display the button.
  2. Invoke the new fragment from the onCreate();
  3. Get the Button on the Fragment view.
  4. On Button onclick listener replace the the fragment with the SettingFragment().
    Done!

Check out this FragmentTransaction Tutorial, it will guide you-

Do the following changes like -

// Code not accurate, may be some syntax error  
@Override
public void onCreate()
{
// super and other stuff

getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new NewFragment())
            .commit();

Button btn = (Button)findViewById(R.id.button01);
btn.setOnClickListener(new OnClickListener(){

 @override
 public void onClick(View v)
 {
 FragmentTransaction ft = getFragmentManager().beginTransaction();

            ft.replace(android.R.id.content, new new SettingsFragment())
            .commit();
 }

});


}
Pradip
  • 3,189
  • 3
  • 22
  • 27
  • looking good. This fragment is adding to current Activity. But i want to display this preference as SubActivity – saa Jan 08 '14 at 06:54
  • Fragment is always added to the Current activity. Fragment is designed for this purpose. You can do what you are looking for by defining you main layout properly. add `` tag in your main layout. to display sub view. have you got my point. – Pradip Jan 08 '14 at 07:01
  • Yeah got it.. So Intially i will hide this fragment. Then on button click i ll show it to the user. Am i correct? – saa Jan 08 '14 at 07:20
0

Instead of using fragementTransaction you can use preferenceFragement : How do you create Preference Activity and Preference Fragment on Android? by WannaGetHigh

Community
  • 1
  • 1
Sabin
  • 61
  • 3