Android 설정의 Preference 이해 및 사용

      Preference는 Android App에서 중요한 컨트롤 중 하나이며 대부분의 Settings 모듈은 Preference를 통해 구현됩니다.

이점:

        Preference는 이전에 설정한 데이터를 자동으로 표시할 수 있습니다.Android는 이러한 상황을 처리하기 위해 키-값 쌍의 기본 설정을 제공하고 이러한 데이터를 자동으로 저장하며 즉시 적용됩니다.사용자가 작업을 직접 저장할 필요가 없으며, xml 컨트롤에서 해당 Preference만 정의하면 됩니다.

PreferenceActivity 및 PreferenceFragment:

        PreferenceActivity는 매우 유용한 기반 클래스로 Android 프로젝트를 개발할 때 옵션 설정을 피할 수 없으며 이러한 설정은 Preference로 저장하는 데 사용됩니다. Android는 이러한 종류의 활동을 위해 특별히 편리한 기본 PreferenceActivity를 제공합니다. Preference에서 상속하는 경우 Preference의 읽기 및 쓰기를 직접 제어할 필요가 없으며 PreferenceActivity가 모든 것을 처리합니다.

        PreferenceActivity는 일반 Activity와 달리 인터페이스 레이아웃 파일을 사용하지 않고 옵션 설정을 사용하는 레이아웃 파일을 사용합니다. 옵션 설정 레이아웃 파일은 PreferenceScreen을 루트 요소로 사용하여 매개변수 설정 인터페이스 레이아웃을 정의합니다.

       Android 3.0부터는 더 이상 공식적으로 PreferenceActivity에서 레이아웃 파일을 설정하는 옵션을 직접 로드하는 것이 권장되지 않으며 대신 PreferenceFragment를 사용하는 것이 좋습니다. 어댑터 어댑터를 통해 항목을 표시합니다.

Preference 소개 및 사용

 1. 일반적으로 사용되는 컨트롤 기본
             설정 컨트롤 패밀리 컨트롤 패밀리 보기 컨트롤 의미                   

               기본 설정 TextView 텍스트 상자                      

              CheckPreference CheckBox 라디오 버튼                  

              EditTextPreference EditText 입력 텍스트 상자            

              ListPreference ListView 목록 상자             

              RingtonePreference - 벨소리

              PreferenceCategory는 LinearLayout 및 RelativeLayout과 유사하며 기본 설정 세트를 결합하여 레이아웃을 더 계층화하는 데 사용됩니다.

              PreferenceScreen 모든 Preference 요소의 루트 노드
 2. 의존성을 추가하려면 사용 필요

 implementation ("androidx.preference:preference:1.2.0-alpha01")

(1) res 파일 아래에 xml 폴더를 정의하고 test.xml을 다음과 같이 정의합니다.

(2) 기본 설정 컨트롤은 xml 파일에 정의되어 있습니다.

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

    <PreferenceCategory
        android:key="test2"
        android:title="第二组设置">

        <CheckBoxPreference
            android:defaultValue="false"
            android:key="g2_checkbox_key"
            android:summaryOff="关"
            android:summaryOn="开"
            android:title="第二组设置勾选" />

        <ListPreference
            android:dialogIcon="@android:drawable/stat_sys_warning"
            android:dialogTitle="第二组列表设置"
            android:key="g2_list_key"
            android:summary="选择"
            android:title="第一组列表设置" />

    </PreferenceCategory>

    <SwitchPreference
        android:defaultValue="false"
        android:key="show_advanced_setting"
        android:summary="高级设置"
        android:title="显示高级设置" />

    <PreferenceCategory android:key="yh">
        <com.android.test3.prefence.RestrictedSwitchPreference
            android:defaultValue="true"
            android:icon="@drawable/ic_settings_wireless"
            android:key="login_dji_account"

            android:title="蓝牙" />

        <com.android.test3.prefence.RestrictedSwitchPreference
            android:defaultValue="true"
            android:icon="@drawable/ic_launcher_background"
            android:key="login_dji_account1"
           app:allowDividerAbove="true"
            android:title="网络" />

        <com.android.test3.prefence.RestrictedPreference
            android:icon="@drawable/ic_launcher_background"
            android:key="internet_settings"
            android:order="20"
            android:summary=" SAA"
            android:title="互联网"
            app:allowDividerAbove="true"

            settings:keywords="@string/keywords_internet"
            settings:useAdminDisabledSummary="true" />

        <com.android.test3.prefence.LuxPreference
            android:icon="@drawable/ic_settings_wireless"
            android:summary="ww"
            app:allowDividerAbove="true"
            android:title="测试自动" />

        <com.android.test3.prefence.LuxArrowPreference
            android:icon="@drawable/ic_settings_wireless"
            android:summary="ww"
            android:title="开始" />

    </PreferenceCategory>

</PreferenceScreen>

 (3) 새 클래스 PrefFragment.java를 만들고 PreferenceFragment를 상속하고 옵션 설정을 위한 레이아웃 파일을 로드합니다. (핵심 코드는 6행과 13행입니다.)

package com.android.test3.fragment;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.preference.PreferenceFragmentCompat;

import com.android.test3.R;

/**
 * @author hudebo
 * @desc
 * @date 2022/11/11
 */
public class PowerFragment extends PreferenceFragmentCompat {
    @Override
    public void onCreatePreferences(@Nullable Bundle savedInstanceState, @Nullable String rootKey) {
        //从xml文件加载选项 
        setPreferencesFromResource(R.xml.pref_two, rootKey);
    }
}

(4) 그런 다음 MainActivity.java에서 위의 Fragment를 로드합니다 .

package com.android.test3;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.android.test3.fragment.PowerFragment;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportFragmentManager().beginTransaction().replace(
                R.id.content,new PowerFragment() ).commitAllowingStateLoss();
    }

}

사용자 지정 기본 설정

예를 들어 배경 추가, 다른 컨트롤 추가 등과 같이 원래 기본 설정이 우리의 요구 사항을 충족하지 못하는 경우가 있습니다. 이 때 문제를 해결하려면 컨트롤을 사용자 지정해야 합니다.

 예: (1) 레이아웃의 배경을 설정합니다. Preference를 상속합니다. onBindViewHolder 메서드에서 홀더를 통해 얻은 컨트롤을 설정합니다.

package com.android.test3.prefence;

import android.content.Context;
import android.util.AttributeSet;

import androidx.core.content.res.TypedArrayUtils;
import androidx.preference.Preference;
import androidx.preference.PreferenceViewHolder;

import com.android.test3.PrefenceFeatureManager;
import com.android.test3.R;

/**
 * @author hudebo
 * @desc 自定义子Preference 支持圆角; 去除summary  支持icon title
 * @date 2022/11/24
 */
public class LuxPreference extends Preference {
    public LuxPreference(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public LuxPreference(Context context, AttributeSet attrs) {
        this(context, attrs, TypedArrayUtils.getAttr(context, R.attr.luxPreferenceStyle,
                android.R.attr.preferenceStyle));
    }

    public LuxPreference(Context context) {
        this(context, null);
    }

    public LuxPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void onBindViewHolder(PreferenceViewHolder holder) {
        super.onBindViewHolder(holder);
        if (holder != null) {
            PrefenceFeatureManager.setPrefenceBackground(this, holder.itemView);
        }
    }
}

(2) 레이아웃 컨트롤 수정 a. 먼저 레이아웃에서 레이아웃 스타일을 정의하고 그립니다.

 b. 사용자 지정 컨트롤에 레이아웃을 소개합니다.

선언: setLayoutResource 메서드는 원래 기본 설정을 포함하는 기본 레이아웃이고 setWidgetLayoutResource 메서드는 원래 레이아웃을 포함하는 WidgetLayout 컨트롤이며 다음 그림은 기본 설정의 소스 코드 레이아웃입니다.

 setLayoutResource는 "@android:id/widget_frame"을 제외한 컨트롤의 일부를 교체하는 것입니다. setWidgetLayoutResource는 "@android:id/widget_frame"의 일부를 교체할 뿐입니다. 오른쪽에 레이아웃이 없습니다.

<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2015 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:gravity="center_vertical"
    android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingRight="?android:attr/listPreferredItemPaddingRight"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:background="?android:attr/selectableItemBackground"
    android:clipToPadding="false"
    android:baselineAligned="false">

    <include layout="@layout/image_frame"/>

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingTop="16dp"
        android:paddingBottom="16dp">

        <TextView
            android:id="@android:id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceListItem"
            android:ellipsize="marquee"/>

        <TextView
            android:id="@android:id/summary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@android:id/title"
            android:layout_alignLeft="@android:id/title"
            android:layout_alignStart="@android:id/title"
            android:layout_gravity="start"
            android:textAlignment="viewStart"
            android:textColor="?android:attr/textColorSecondary"
            android:maxLines="10"
            style="@style/PreferenceSummaryTextStyle"/>

    </RelativeLayout>

    <!-- Preference should place its actual preference widget here. -->
    <LinearLayout
        android:id="@android:id/widget_frame"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="end|center_vertical"
        android:paddingLeft="16dp"
        android:paddingStart="16dp"
        android:paddingRight="0dp"
        android:paddingEnd="0dp"
        android:orientation="vertical"/>

</LinearLayout>

위는 일반적인 선호도 속성과 같은 개인적인 이해이며 클릭과 같은 관련 방법의 후속 소개입니다. ! !

추천

출처blog.csdn.net/hhbstudy/article/details/128304762