在Preference裏動態加載layout androidPreference
程序员文章站
2022-07-12 19:36:28
...
在string.xml裏:
<com.android.deskclock.settings.AlarmVolumePreference android:key="volume_setting" android:layout="@layout/alarm_volume_preference" android:title="@string/alarm_volume_title" />
自定義了Prefernce,加載的默認layout爲alarm_volume_preference.xml
但是因爲需要適應其它平臺[因爲特殊設備的分辨率的原因],需要在AlarmVolumePreference裏根據不同情況加載layout.
查詢/frameworks/base/core/java/android/preference/Preference.java
/** * Sets the layout resource that is inflated as the {@link View} to be shown * for this Preference. In most cases, the default layout is sufficient for * custom Preference objects and only the widget layout needs to be changed. * <p> * This layout should contain a {@link ViewGroup} with ID * {@link android.R.id#widget_frame} to be the parent of the specific widget * for this Preference. It should similarly contain * {@link android.R.id#title} and {@link android.R.id#summary}. * * @param layoutResId The layout resource ID to be inflated and returned as * a {@link View}. * @see #setWidgetLayoutResource(int) */ public void setLayoutResource(@LayoutRes int layoutResId) { if (layoutResId != mLayoutResId) { // Layout changed mRecycleEnabled = false; } mLayoutResId = layoutResId; }
將新增的layout放置到overlay裏,然後在AlarmVolumePreference的構造方法裏調用setLayoutResource:
public AlarmVolumePreference(Context context, AttributeSet attrs) { super(context, attrs); if(滿足xx條件) { setLayoutResource(R.layout.alarm_volume_preference_xx); //不滿足該條件則加載默認layout. } }