在完整视图中显示首选项片段

Display preference fragments in a full view

我正在使用首选项片段并替换主 xml 文件根布局的 id 中的片段。所以我的问题是偏好与主要 activity xml 元素一起显示。

我在 Android 应用程序中看到首选项是单独打开的 我不确定它们是单独打开还是只占据整个屏幕。为了打开偏好片段,我正在做一个正常的片段事务(注意:我没有使用支持库不确定这是否与我的问题有关但仍然提到它)。

这就是问题所在,

这是我的代码

sampleprefs.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <CheckBoxPreference
        android:defaultValue="false"
        android:title="Check box preference"
        android:key="check_box_preference_1" />
    <EditTextPreference
        android:defaultValue="Default value"
        android:selectAllOnFocus="true"
        android:singleLine="true"
        android:title="Edit text preference"
        android:key="edit_text_preference_1" />

</PreferenceScreen>

这里是主要布局,

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="com.random.preferenceexample.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView" />

    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"


        android:id="@+id/button" />
</LinearLayout>

这是我的主要 Activity 代码,点击按钮即可显示片段,

public class MainActivity extends Activity implements View.OnClickListener {
    boolean result;
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(this);
 }

    @Override
    public void onClick(View v) {

        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        SettingsFragment sf = new SettingsFragment();
        ft.add(R.id.activity_main,sf);
        ft.commit();
    }

这是片段class

public class SettingsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.sampleprefs);
    }
}

看起来问题似乎与 Fragment 的背景透明度有关。 Fragments 默认情况下是透明背景,因为它们只能用于绘制屏幕的一小部分,但如果您希望 Fragment 覆盖全屏,则只需为其添加一些背景即可。

此外,对于 FragmentTransactions.

,最好使用支持将视图一个放在另一个上方的根布局(例如 FrameLayout)

将这些添加到您的片段中:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        view.setBackgroundColor(getResources().getColor(android.R.color.white));
        return view;
    }

这是工作示例