2013-06-21 158 views
8

我有一個偏好android:layout gft。 我已經在xml文件的首選項的android:layout屬性中設置了佈局。獲取視圖的自定義佈局

現在我需要對佈局中的按鈕進行初始化(這是一個+1按鈕)。 我需要在onCreate方法中獲取該按鈕(這是一個+1按鈕),但是當我使用findViewById(button_id)時,它將返回null。

有什麼方法可以獲得此偏好的視圖嗎?

更新:似乎喜好是不添加偏好xml後創建的,所以我得到空。我可以在哪裏調用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" /> 

回答

9

你需要創建一個擴展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