Reputation: 153
I created a preference_headers.xml as follow. My activity is able to generate it without any problem. I'm wondering how to pass an argument (i.e. IP address string) from activity to fragment class. I am thinking to use findfragmentbyid() to access the specific fragment, however, I don't know how to add an ID at the header tag in preference_headers.xml.
Here is my sample code. Thanks
===== SetupActivity.java =======
public class SetupActivity extends SherlockPreferenceActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.preference_headers, target);
}
}
===== preference_headers.xml =======
<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
<header android:title="Network" />
<header
android:id="@+id/setting_wifi"
android:fragment="com.example.setup.WIFIFragment"
android:title="@string/setting_wifi" >
</header>
</preference-headers>
===== WIFIFragment .java =======
public static class WIFIFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference_wifi);
}
}
Upvotes: 1
Views: 6515
Reputation: 1157
I use getPreferenceManager().findPreference(PREF_KEY).getExtras();
to get the extras bundle, and put whatever I want in it.
Upvotes: 0
Reputation:
In your SherlockPreferenceActivity
override this method
@Override
public void onHeaderClick(Header header, int position) {
// Here's an example
if(header.fragmentArguments == null)
{
header.fragmentArguments = new Bundle();
}
header.fragmentArguments.putString("IP", "Hi there! My IP is 127.0.0.1");
super.onHeaderClick(header, position);
}
And you can obtain the argument in your Fragment
public static class WIFIFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference_wifi);
Bundle b = getArguments();
if(b != null)
Toast.makeText(getActivity() , b.getString("IP") , 1).show();
}
}
I have tried this in Jelly bean not in Actionbar Sherlock library, but you can try it. Hope it helps
Upvotes: 4
Reputation: 12672
You can use findFragmentByTag()
to get the fragment. The tag name will need to be set when you're adding the fragment to the Activity.
Upvotes: 0