2016-11-17 62 views
0
訪問按鈕

我在首以這種方式創建按鈕:如何PreferenceActivity

<PreferenceScreen> 
    <Preference 
    android:key="resetBD" 
    android:title="@string/ajustes_almacenamiento" 
    android:summary="@string/ajustes_almacenamiento_desc" 
    android:widgetLayout="@layout/pref_reset_bd_button" > 
    </Preference> 
</PreferenceScreen> 

佈局/ pref_reset_bd_button.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/submit_layout_button" 
    android:layout_height="wrap_content" 
    android:layout_width="fill_parent" 
    android:weightSum="10"> 
<Button 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/resetButton" 
    android:text="Reset" 
    android:layout_width="wrap_content" 
    android:onClick="submitWifiToDevice" 
    android:layout_height="wrap_content"> 
</Button> 
</LinearLayout> 

在PreferenceFragment我successfuly訪問/獲取按鈕這樣做:

 View footerView = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.pref_reset_bd_button, null, false); 
     resetButton= (Button) footerView.findViewById(R.id.resetButton); 

但是當我嘗試更改按鈕文字

resetButton.setText("NEW ONE"); 

(或禁用)什麼也沒有發生。我究竟做錯了什麼?

+0

您必須在屏幕可見之前刷新屏幕。抱歉從頭我不知道目前如何。 – greenapps

+1

你是否把setText放在任何條件下? – garima

+0

我看到在android-studio debuger該按鈕獲取新文本,但它不在模擬器中更新 –

回答

0

試試這個。創建一個自定義的偏好:

public class PreferenceWidget extends Preference { 
    private View mView; 

    @Override 
    protected void onBindView(View view) { 
     super.onBindView(view); 
     mView = view.findViewById(R.id.resetButton); 
    } 

    public View getView() { 
     return mView; 
    } 
} 

然後改變自己的喜好XML

<PreferenceScreen> 
    <package.PreferenceWidget 
    android:key="resetBD" 
    android:title="@string/ajustes_almacenamiento" 
    android:summary="@string/ajustes_almacenamiento_desc" 
    android:widgetLayout="@layout/pref_reset_bd_button" > 
    </package.PreferenceWidget > 
</PreferenceScreen> 

然後獲取視圖

PreferenceWidget p = (PreferenceWidget)findPreference("resetBD"); 
Button b = (Button)p.getView(); 
b.setText("Hello"); 

原來的答覆:

你不應該有自己膨脹視圖。這應該發生在您對addPreferencesFromResource的調用中。

然後,您可以獲取首選項,獲取首選項的視圖,找到按鈕視圖,然後設置文本。

Preference p = findPreference("resetBD"); 
View v = p.getView(null, null); 
Button b = (Button)v.findViewById(R.id.resetButton); 
v.setText("Hello"); 

雖然,因爲no one seems to know如何使用Preference.getView功能,您可能需要創建一個自定義的優先對象。

+0

這是一樣的......在android-studio debuger我獲得按鈕併成功設置新文本,但在模擬器按鈕文本不會改變。 –

+0

您是否嘗試過在設備上進行測試? – Mike

+0

是的,它不會改變。例如,我可以更改首選項標題,但不能包含widgetLayout的內容 –