2012-01-30 47 views
1

所以我有一對夫婦的我的應用程序的部分這一問題,但我會堅持一個:如何更改當前不活動的視圖的佈局?

我有一個偏好屏幕,跨應用程序更新字體大小/字體。除了我的聯繫人選擇器之外,它的功能非常好。這是因爲我創造它的方式:

private void populateContactList() { 

    Cursor cursor = getContacts(); 
    fields = new String[] { ContactsContract.CommonDataKinds.Email.DATA }; 
    adapter = new SimpleCursorAdapter(this, R.layout.entry, cursor, fields, 
      new int[] { R.id.contactEntryText }); 
    mContactList.setAdapter(adapter); 
} 

凡R.id.contactEntryText是在不同的.XML比當前充氣一個(它只是適應該佈局)。

當然,我不能強加一個setTextColor();它,因爲當我嘗試做一個findViewById,我得到一個空指針異常。

我該如何去改變該佈局上的字體樣式,以便我的列表視圖獲取它?

回答

2

而不是隻使用SimpleCursorAdapter,擴展它。然後在getView中,您可以更改UI(文本顏色,字體大小或其他)。您可以通過適配器中的偏好管理器或活動中的某個位置(onCreate ...)查找偏好設置,從而在設置活動中設置顏色或大小。

您不能使用處理程序在活動之間進行通信。

更新,抱歉,由於缺乏清晰度,您需要覆蓋您的適配器,而不是(或不只是)ListActivity。這裏是一些代碼:

在你的活動:

private void populateContactList() { 

    Cursor cursor = getContacts(); 
    fields = new String[] { ContactsContract.CommonDataKinds.Email.DATA }; 
    adapter = new MyAdapter(this, R.layout.entry, cursor, fields, 
     new int[] { R.id.contactEntryText }); 
    mContactList.setAdapter(adapter); 
} 

MyAdapter是一個擴展簡單的遊標適配器自己的自定義適配器。如果您只需要在每行中查找文本視圖並更改某些屬性(這是我的理解),請調用super.getView以獲取每行的ViewGroup,然後可以在該ViewGroup上調用findViewById以獲取TextView。一旦你有了,你可以隨意更改屬性。以下僅爲最基本的實施大綱:

private static class MyAdapter extends SimpleCursorAdapter{ 

    public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { 
     super(context, layout, c, from, to); 
     //you could use context to get PreferenceManager and find the 
     //colors/sizes set in your settings activity here 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     final ViewGroup rowView = (ViewGroup) super.getView(position, convertView, parent);  

     final TextView yourText = (TextView) rowView.findViewById(R.id.yourTextViewId); 
     yourText.setTextColor(...); 
     yourText.setTextSize(...); 
    } 
}