Phụ đề ưu tiên

Đối với hầu hết các trường hợp, việc thêm bản tóm tắt lựa chọn ưu tiên tương đối đơn giản vì bạn chỉ cần thêm thuộc tính android:summary vào lựa chọn ưu tiên tương ứng bằng tài nguyên chuỗi thích hợp. Tuy nhiên, nếu phụ đề cần cập nhật linh động, thì bạn có thể cần một trình điều khiển tuỳ chỉnh cho lựa chọn ưu tiên.

Phụ đề tĩnh

Cách thêm phụ đề tĩnh vào một tuỳ chọn ưu tiên:

  1. Thêm thuộc tính android:summary vào tuỳ chọn. Ví dụ: để thêm một bản tóm tắt vào tuỳ chọn cài đặt màn hình L0, hãy thêm nội dung như sau vào các thuộc tính tuỳ chọn:
    android:summary="@string/display_settings_summary"
    

    Ví dụ: hãy xem xét mã mẫu đầy đủ về lựa chọn ưu tiên sau:

    <Preference
            android:fragment="com.android.car.settings.display.DisplaySettingsFragment"
            android:icon="@drawable/ic_settings_display"
            android:key="@string/pk_display_settings_entry"
            android:title="@string/display_settings"
            android:summary="@string/display_settings_summary"
            settings:controller="com.android.car.settings.common.DefaultRestrictionsPreferenceController"/>
    

Phụ đề động

Phụ đề được chỉ định bằng thuộc tính android:summary là tĩnh nên không thể cập nhật dựa trên một số điều kiện nhất định. Đối với phụ đề động, bạn cần sửa đổi trình điều khiển lựa chọn ưu tiên cho lựa chọn ưu tiên đó. Ví dụ sau đây sửa đổi tuỳ chọn vị trí L0 để có phụ đề chỉ định liệu vị trí đang bật hay tắt và nếu đang bật, hãy cho biết số lượng ứng dụng hiện có quyền truy cập thông tin vị trí.

  1. Xác định các chuỗi mới:
    <!-- Summary for Location settings when location is off [CHAR LIMIT=NONE] -->
        <string name="location_settings_summary_location_off">Off</string>
        <!-- Summary for Location settings when location is on, explaining how many apps have location permission [CHAR LIMIT=NONE]-->
        <plurals name="location_settings_summary_location_on">
            <item quantity="one">On - <xliff:g id="count">%1$d</xliff:g> app has access to location</item>
            <item quantity="other">On - <xliff:g id="count">%1$d</xliff:g> apps have access to location</item>
        </plurals>
        <!-- Location settings, loading the number of apps which have location permission [CHAR LIMIT=30] -->
        <string name="location_settings_loading_app_permission_stats">Loading\u2026</string>
    
  2. Tạo một PreferenceController mới, LocationEntryPreferenceController, để thiết lập và thay đổi văn bản tóm tắt về lựa chọn ưu tiên về vị trí một cách linh động:
    public class LocationEntryPreferenceController extends PreferenceController<Preference> {
    
        private static final Logger LOG = new Logger(LocationEntryPreferenceController.class);
        private static final IntentFilter INTENT_FILTER_LOCATION_MODE_CHANGED =
                new IntentFilter(LocationManager.MODE_CHANGED_ACTION);
    
        private final Context mContext;
        private final LocationManager mLocationManager;
        /** Total number of apps that have location permissions. */
        private int mNumTotal = -1;
        private int mNumTotalLoading = 0;
        private AtomicInteger mLoadingInProgress = new AtomicInteger(0);
    
        private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                refreshUi();
            }
        };
    
        public LocationEntryPreferenceController(Context context, String preferenceKey,
                FragmentController fragmentController, CarUxRestrictions uxRestrictions) {
            super(context, preferenceKey, fragmentController, uxRestrictions);
            mContext = context;
            mLocationManager = (LocationManager) getContext().getSystemService(
                    Service.LOCATION_SERVICE);
        }
    
        @Override
        protected Class<Preference> getPreferenceType() {
            return Preference.class;
        }
    
        @Override
        protected void onStartInternal() {
            getContext().registerReceiver(mReceiver, INTENT_FILTER_LOCATION_MODE_CHANGED);
        }
    
        @Override
        protected void onStopInternal() {
            getContext().unregisterReceiver(mReceiver);
        }
    
        @Override
        protected void updateState(Preference preference) {
            super.updateState(preference);
            updateSummary(preference);
            if (!mLocationManager.isLocationEnabled() || mLoadingInProgress.get() != 0) {
                return;
            }
            mNumTotalLoading = 0;
            // Retrieve a list of users inside the current user profile group.
            List<UserHandle> users = mContext.getSystemService(
                    UserManager.class).getUserProfiles();
            mLoadingInProgress.set(users.size());
            for (UserHandle user : users) {
                Context userContext = createPackageContextAsUser(mContext, user.getIdentifier());
                if (userContext == null) {
                    if (mLoadingInProgress.decrementAndGet() == 0) {
                        setLocationAppCount(preference, mNumTotalLoading);
                    }
                    continue;
                }
                PermissionControllerManager permController =
                        userContext.getSystemService(PermissionControllerManager.class);
                permController.countPermissionApps(
                        Arrays.asList(ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION),
                        PermissionControllerManager.COUNT_ONLY_WHEN_GRANTED,
                        (numApps) -> {
                            mNumTotalLoading += numApps;
                            if (mLoadingInProgress.decrementAndGet() == 0) {
                                setLocationAppCount(preference, mNumTotalLoading);
                            }
                        }, null);
            }
        }
    
        @VisibleForTesting
        void setLocationAppCount(Preference preference, int numApps) {
            mNumTotal = numApps;
            updateSummary(preference);
        }
    
        private void updateSummary(Preference preference) {
            String summary = "";
            if (mLocationManager.isLocationEnabled()) {
                if (mNumTotal == -1) {
                    summary = mContext.getString(R.string.location_settings_loading_app_permission_stats);
                } else {
                    summary = mContext.getResources().getQuantityString(
                            R.plurals.location_settings_summary_location_on,
                            mNumTotal, mNumTotal);
                }
            } else {
                summary = mContext.getString(R.string.location_settings_summary_location_off);
            }
            preference.setSummary(summary);
        }
    
        private Context createPackageContextAsUser(Context context, int userId) {
            try {
                return context.createPackageContextAsUser(
                        context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
            } catch (PackageManager.NameNotFoundException e) {
                LOG.e("Failed to create user context", e);
            }
            return null;
        }
    }
    

    Đối với trình điều khiển mẫu này:

    • Nếu vị trí bị tắt, văn bản tóm tắt sẽ được đặt thành chuỗi location_settings_summary_location_off.
    • Nếu bạn bật thông tin vị trí, số lượng ứng dụng có quyền truy cập thông tin vị trí sẽ được thêm vào. Trong khi tải, chuỗi location_settings_loading_app_permission_stats sẽ hiển thị. Khi dữ liệu được tải, trình điều khiển sẽ đặt bản tóm tắt thành chuỗi location_settings_summary_location_on với số lượng ứng dụng có quyền truy cập được chỉ định.
    • Khi trình điều khiển lựa chọn ưu tiên được khởi động, trình điều khiển sẽ đăng ký một trình thu và làm mới trạng thái lựa chọn ưu tiên khi trạng thái vị trí thay đổi.
  3. Sửa đổi tệp XML mảnh để đính kèm tay điều khiển mới vào tuỳ chọn liên quan:
    <Preference
            android:fragment="com.android.car.settings.location.LocationSettingsFragment"
            android:icon="@drawable/ic_settings_location"
            android:key="@string/pk_location_settings_entry"
            android:title="@string/location_settings_title"
            settings:controller="com.android.car.settings.location.LocationEntryPreferenceController"/>