Настройка макета предпочтений и изменение в нем атрибута - PullRequest
7 голосов
/ 16 ноября 2011

возможно ли программно получить доступ к макету, для которого задано предпочтение?

Вот что у меня есть, очень простой проект - подтверждение концепции

Упражнение по предпочтениям:

package com.example;

import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.View;

public class PreferenceExampleActivity extends PreferenceActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

        ImageView v = (ImageView) findViewById(R.id.iconka);

    }
}

Ресурс XML:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:key="settings">
    <PreferenceCategory 
        android:title="Category Setting Name" 
        android:order="1" 
        android:key="Main">
        <Preference 
            android:order="1" 
            android:title="Setting" 
            android:summary="Setting1" 
            android:layout="@layout/profile_preference_row"
            android:key="profile" />
    </PreferenceCategory>
</PreferenceScreen>

Настраиваемый макет для Предпочтения:

<?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="match_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="15dip"
        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:textColor="?android:attr/textColorSecondary"
            android:maxLines="4" />

    </RelativeLayout>
    <ImageView
        android:id="@+id/iconka"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        />
</LinearLayout>

То, что я хочу, - это возможность получить доступ к «иконке» ImageView.от деятельности и изменить изображение оттуда.Я использую API 8 (Android 2.2)

В настоящее время буква "v" равна нулю, и я понятия не имею, почему это так.

Намек будет очень полезен!

Обновление - решение: На самом деле, мне нужно было настраиваемое предпочтение, которое я могу изменить для своих нужд.Это практическое руководство по созданию собственных пользовательских настроек в вашем проекте: Android & Amir - настройки Android См. Часть, когда автор создает пользовательский класс предпочтений.

Ответы [ 3 ]

9 голосов
/ 22 августа 2013

После 20 минут стягивания волос я нашел элегантное решение этой проблемы. Сначала расширьте предпочтение, затем переопределите метод getView (View convertView, ViewGroup parent). Мой случай был такой: у меня был макет предпочтений со значком приложения и двумя текстовыми представлениями (имя и версия приложения). Я хочу изменить версию приложения программно. Как мне это сделать? просто посмотрите ниже:

public class AboutUsPreference extends Preference {

    public AboutUsPreference(Context context) {
        super(context);
    }

    public AboutUsPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AboutUsPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public View getView(View convertView, ViewGroup parent) {
        View v = super.getView(convertView, parent);
        ((TextView)v.findViewById(R.id.textView2)).setText(getAppVersion());        
        return v;
    }

    private String getAppVersion(){
        PackageInfo pInfo = null;
        try {
            pInfo = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0);
        } catch (NameNotFoundException e) {
            Log.e(getClass().getName(), e.getMessage(), e);
            return "";
        }

        String version = pInfo.versionName;
        return getContext().getString(R.string.version, version);
    }


}

Решение заключается в следующем: View v = super.getView(convertView, parent); при переопределении метода getView. Вызов super.getview вернет ваш макет.

А мои предпочтения xml выглядят так:

<com.audioRec.android.settings.aboutUs.AboutUsPreference
        android:layout="@layout/about_preference_layout"/>
1 голос
/ 16 ноября 2011

Попробуйте взглянуть на следующие обсуждения вьювью. Может помочь вам с вашей проблемой.

Android: findViewById ImageView (пользовательский адаптер)

Android: получение исключения NullPointerException для ImageView imag = (ImageView) findViewById (R.id.image)

1 голос
/ 16 ноября 2011

попробуйте getLayoutResource , чтобы получить View предпочтения, а затем получите ImageView

...