Пользовательские настройки нарушены в Honeycomb / ICS - PullRequest
4 голосов
/ 06 января 2012

Я использую пользовательское предпочтение, в котором я использую заголовок, сводку и значок. Преф используется для выбора элемента (обложки, приложения и т. Д.), А затем будет суммировать текущий выбор. Вот настройки, работающие правильно (вверху) и моя проблема с Honeycomb / ICS:

http://imgur.com/vKPOu

http://imgur.com/EiMBr

Для предпочтения освобождается место, но даже заголовок / сводка по умолчанию не отображаются, и цель выбора элемента также не срабатывает. Вот предпочтительный макет:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+android:id/widget_frame"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:gravity="center_vertical"
    android:paddingRight="?android:attr/scrollbarSize">
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dip"
        android:layout_marginRight="6dip"
        android:layout_marginTop="6dip"
        android:layout_marginBottom="6dip"
        android:layout_weight="1">
        <TextView
            android:id="@+android:id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:ellipsize="marquee"
            android:fadingEdge="horizontal" />
        <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:textAppearance="?android:attr/textAppearanceSmall"
            android:maxLines="2" />
   </RelativeLayout>
   <ImageView
       android:id="@+id/icon"
       android:layout_width="48dp"
       android:layout_height="48dp"
       android:layout_gravity="center" />
</LinearLayout> 

И само пользовательское предпочтение:

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class SelectedAppPreference extends Preference {
    private Drawable mIcon;

    public SelectedAppPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        final PackageManager pm = context.getPackageManager();
        String packageName = context.getSharedPreferences("appPrefs", Context.MODE_PRIVATE).getString("selected_app_package", null);

        this.setLayoutResource(R.layout.icon_pref);
        try {
            this.mIcon = pm.getApplicationIcon(packageName);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    public SelectedAppPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        final PackageManager pm = context.getPackageManager();
        String packageName = context.getSharedPreferences("appPrefs", Context.MODE_PRIVATE).getString("selected_app_package", null);

        this.setLayoutResource(R.layout.icon_pref);
        try {
            this.mIcon = pm.getApplicationIcon(packageName);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onBindView(final View view) {
        super.onBindView(view);

        final ImageView imageView = (ImageView)view.findViewById(R.id.icon);
        if ((imageView != null) && (this.mIcon != null)) {
            imageView.setImageDrawable(this.mIcon);
        }
    }

    public void setIcon(final Drawable icon) {
        if (((icon == null) && (this.mIcon != null)) || ((icon != null) && (!icon.equals(this.mIcon)))) {
            this.mIcon = icon;
            this.notifyChanged();
        }
    }

    public Drawable getIcon() {
        return this.mIcon;
    }
}

Ничего особенного в самом предпочтении. У меня есть ощущение, что проблема заключается в макете предпочтений XML, но я не уверен, что именно не работает правильно. Я могу подтвердить, что настройки работают нормально на устройствах Android 2.1, 2.2 и 2.3, и у меня были проблемы с 3.2 и 4.0. Есть предложения?

Ответы [ 2 ]

6 голосов
/ 08 января 2012

У меня была похожая проблема со сторонними пользовательскими настройками, и я исправил ее, сделав видимую рамку виджета.Это было невидимым по умолчанию в ICS.Не знаю, как оно отображается в соответствии с вашими предпочтениями.

// This line was in the original code.
LinearLayout widgetFrameView = ((LinearLayout) mView
                    .findViewById(android.R.id.widget_frame));
...
// This line fixed the visibility issue
widgetFrameView.setVisibility(View.VISIBLE);

Также пришлось перестроить представление, чтобы оно соответствовало остальным элементам управления ICS.

2 голосов
/ 10 января 2012

Сторонние пользовательские настройки, которые я установил, взяты с этого сайта

https://github.com/attenzione/android-ColorPickerPreference/tree/master/src/net/margaritov/preference/colorpicker

Мой код (в ColorPickerPreference.setPreviewColor ()) выглядит как

widgetFrameView.setVisibility(View.VISIBLE);
final boolean preApi14 = android.os.Build.VERSION.SDK_INT < 14;
final int rightPaddingDip = preApi14 ? 8 : 5;

widgetFrameView.setPadding(
                      widgetFrameView.getPaddingLeft(),
                      widgetFrameView.getPaddingTop(),
                      (int)(mDensity * rightPaddingDip),
                      widgetFrameView.getPaddingBottom()
                );

где

float mDensity = getContext().getResources().getDisplayMetrics().density;

Это с minSdkVersion = 8 и без targetSdkVersion.Если вы установите targetSdkVersion равным 14 или более, вам может потребоваться изменить значение «5» на что-то другое, пока элемент пользовательского предпочтения справа не выровняется со стандартными (например, флажки).

...