【问题标题】:Get view of preference with custom layout使用自定义布局获取偏好视图
【发布时间】:2015-01-29 12:52:56
【问题描述】:

我有一个偏好 android:layout gft. 我已经在 xml 文件中首选项的 android:layout 属性中设置了布局。

现在我需要初始化布局中的一个按钮(它是一个 +1 按钮)。 我需要在 onCreate 方法中获取该按钮(这是一个 +1 按钮),但是当我使用 findViewById(button_id) 时,它返回 null。

有什么方法可以了解这种偏好吗?

更新:似乎在我添加首选项 xml 后没有创建首选项,所以我得到了 null。我可以在哪里调用 findViewById 以便按钮已经创建?

谢谢。

首选项 xml:

<Preference android:title="Rate this app"
    android:key="rate"
    android:widgetLayout="@layout/plusone_pref"/>

</PreferenceScreen>

偏好布局xml:

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.plus.PlusOneButton xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:plus="http://schemas.android.com/apk/lib/com.google.android.gms.plus"
android:id="@+id/plus_one_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:focusable="false"
plus:size="standard" />

【问题讨论】:

    标签: android android-preferences


    【解决方案1】:

    您需要创建一个扩展Preference 的类,然后覆盖onBindView,您就可以访问该视图。

    public class MyPreference extends Preference {
    
        ...
    
        @Override
        protected void onBindView(View view) {
            super.onBindView(view);
            View myView = (View) view.findViewById(R.id.my_id);
            // ... do stuff
        }
    
    }
    

    您可能需要覆盖更多方法,请阅读 PreferenceActivity 中的自定义首选项 - http://developer.android.com/guide/topics/ui/settings.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多