Farid
Farid

Reputation: 168

How can I create a Setting activity

I created a Setting activity in my app, but it didn't work. This is my SettingFragment class:

public class SettingFragment extends PreferenceFragmentCompat
{
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey)
    {
        setPreferencesFromResource(R.xml.pref, rootKey);
    }
}

This is my SettingActivity:

public class SettingActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.content, new SettingFragment())
                .commit();
    }
}

This is MainActivity. Clicking the button will open SettingActivity.

btn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Intent intent = new Intent(MainActivity.this, SettingActivity.class);
                startActivity(intent);
            }
        });

And this is Preference.xml:

<PreferenceScreen 
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Preference
        app:key="feedback"
        app:title="Send feedback"
        app:summary="Report technical issues or suggest new features"/>

</PreferenceScreen>

What is the R.id.content? It was used in the developer.android site example. What is the problem? How can I solve this?

Upvotes: 0

Views: 188

Answers (2)

RonTLV
RonTLV

Reputation: 2556

What is the R.id.content?

Lets assume that this is the SettingActivity layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SettingsActivity">

    <LinearLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp" >
    </LinearLayout>

</LinearLayout>

The call to replace will swap your fragment with R.id.content. You can also call replace with android.R.id.content, read more here.

Upvotes: 1

sanoJ
sanoJ

Reputation: 3128

You need to use android.R.id.content. This will replace the root content with the Fragment's content. you can find more information about android.R.id.content from this

// Display the fragment as the main content.
getSupportFragmentManager()
                .beginTransaction()
                .replace(android.R.id.content, new SettingFragment())
                .commit();

Upvotes: 1

Related Questions