2015-01-22 2 views
1

Я работаю над проектом Android. У меня есть код prefs.xml, что-то вроде этогоAndroid Set Custom Preference Layout

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 

     <Preference 
      android:key="pref_name_color_picker" 
      android:title="Colour" 
      android:summary="Colour of the name" 
      android:defaultValue="#FFFFFF" 
      android:layout="@layout/custom_name_setting_layout" /> 
    </PreferenceCategory> 


</PreferenceScreen> 

И мне нужна индивидуальная схема предпочтений. И я создал;

custom_name_setting_layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:minHeight="?android:attr/listPreferredItemHeight" 
    android:gravity="center_vertical" 
    android:paddingRight="?android:attr/scrollbarSize"> 

    <RelativeLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="15dip" 
     android:layout_marginRight="6dip" 
     android:layout_marginTop="6dip" 
     android:layout_marginBottom="6dip" 
     android:layout_weight="1"> 

     <TextView 
      android:id="@+android:id/title" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:singleLine="true" 
      android:textAppearance="?android:attr/textAppearanceLarge" 
      android:ellipsize="marquee" 
      android:fadingEdge="horizontal" /> 

     <TextView 
      android:id="@+android:id/summary" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_below="@android:id/title" 
      android:layout_alignLeft="@android:id/title" 
      android:textAppearance="?android:attr/textAppearanceSmall" 
      android:maxLines="2" /> 

     <ImageView 
      android:id="@+id/ivNameTextColor" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:minHeight="32dp" 
      android:minWidth="32dp" 
      android:layout_alignParentRight="true" /> 

    </RelativeLayout> 

</LinearLayout> 

И написать SettingActivity.java

public class SettingActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { 
    int color = 0xffffff00; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     addPreferencesFromResource(R.xml.prefs); 


     LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View row = inflater.inflate(R.layout.custom_name_setting_layout, null); 

     ImageView ivNameTextColor = (ImageView) row.findViewById(R.id.ivNameTextColor); 
     ivNameTextColor.setBackgroundColor(Color.RED); 
    } 
} 

Моя проблема; Я пишу метод setBackgroundColor, но не работает. Не работает meanin, эта программа работает без ошибок (например, NullReferenceException, ошибки нет). Но цвет фона по-прежнему не меняется.

Я не знаю почему. Как я могу решить эту проблему? Благодаря

+0

Да, но идентификатор цвета будет меняться динамически. Этот образец, для образца, я пишу Color.RED –

+0

Вам нужно работать с ListView. Вы можете вспомнить его с помощью 'findViewById (android.R.id.list)' – natario

+0

Пожалуйста, дайте мне пример использования. Спасибо, что я новичок в кодировании Android. –

ответ

0

Очевидно, что если вы закодировав цвет, то вы можете просто сделать его в XML:

android:background="@android:color/red" 

Если вы хотите сделать это в коде, тогда, к сожалению, это сложнее, чем это может показаться. Вы не можете просто установить цвет представления предпочтений в onCreate(), потому что представления предпочтений хранятся в списке и создаются и перерабатываются динамически при прокрутке списка.

Вам необходимо установить цвет фона при создании представления. Для этого вам необходимо реализовать класс пользовательских предпочтений и переопределить getView():

public class CustomColorPreference extends Preference 
{ 
    int backgroundColor = Color.BLACK; 

    public CustomColorPreference(Context context) { 
     super(context); 
    } 

    public CustomColorPreference(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public void setCustomBackgroundColor(int color) 
    { 
     backgroundColor = color; 
    } 

    @Override 
    public View getView(View convertView, ViewGroup parent) 
    { 
     View v = super.getView(convertView, parent); 

     // v.setBackgroundColor(backgroundColor); // set background color of whole view 
     ImageView ivNameTextColor = (ImageView)v.findViewById(R.id.ivNameTextColor); 
     ivNameTextColor.setBackgroundColor(backgroundColor); 

     return v; 
    } 
} 

Изменение XML использовать CustomColorPreference класс:

<com.example.yourapp.CustomColorPreference 
     android:key="pref_name_color_picker" 
     android:title="Colour" 
     android:summary="Colour of the name" 
     android:defaultValue="#FFFFFF" 
     android:layout="@layout/custom_name_setting_layout" /> 

Тогда в вашем onCreate вы можете получить CustomColorPreference и установите цвет на него с использованием общедоступного метода setCustomBackgroundColor():

CustomColorPreference picker = (CustomColorPreference)findPreference("pref_name_color_picker"); 
picker.setCustomBackgroundColor(Color.RED);