Подтвердить что ты не робот

Как изменить цвет и шрифт в ListView

Я пытаюсь изменить свой шрифт (цвет и размер) и задний план в моем ListView. Я хочу изменить его с помощью строк кода, а не на xml. мой список выглядит следующим образом:  xml:

 <?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="18sp" android:text="@string/hello">
</TextView>

и мой код

public class NewsActivity  extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

 // ArrayAdapter listItemAdapter = new ArrayAdapter( this,android.R.layout.simple_list_item_1, v_itemList );

      setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,ynetList));

      View v=getListView() ;

      ListView lv = getListView();

что дальше? пожалуйста, дайте мне пример базы в моем коде

4b9b3361

Ответ 1

Вам нужно создать CustomListAdapter.

public class CustomListAdapter extends ArrayAdapter <String> {

    private Context mContext;
    private int id;
    private List <String>items ;

    public CustomListAdapter(Context context, int textViewResourceId , List<String> list ) 
    {
        super(context, textViewResourceId, list);           
        mContext = context;
        id = textViewResourceId;
        items = list ;
    }

    @Override
    public View getView(int position, View v, ViewGroup parent)
    {
        View mView = v ;
        if(mView == null){
            LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mView = vi.inflate(id, null);
        }

        TextView text = (TextView) mView.findViewById(R.id.textView);

        if(items.get(position) != null )
        {
            text.setTextColor(Color.WHITE);
            text.setText(items.get(position));
            text.setBackgroundColor(Color.RED); 
            int color = Color.argb( 200, 255, 64, 64 );
                text.setBackgroundColor( color );

        }

        return mView;
    }

}

Элемент списка выглядит следующим образом (custom_list.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/textView"
    android:textSize="20px" android:paddingTop="10dip" android:paddingBottom="10dip"/>
</LinearLayout>

Используйте TextView api, чтобы украсить текст по своему вкусу.

и вы будете использовать его как это

listAdapter = new CustomListAdapter(YourActivity.this , R.layout.custom_list , mList);
mListView.setAdapter(listAdapter);

Ответ 2

Создайте CustomAdapter и у вас есть getView(), чтобы там, если вы хотите изменить цвет фона списка, используйте это:

v.setBackgroundColor(Color.CYAN);

Если вы хотите изменить textColor, сделайте следующее:

tv.setTextColor(Color.RED);

и для textSize:

tv.setTextSize(20);

где 'v' - это список, а 'tv' - текстовое окно

Ответ 3

Еще лучше, вам не нужно создавать отдельный макет XML-x для просмотра списка ячеек. Вы можете просто использовать "android.R.layout.simple_list_item_1", если список содержит только текстовое представление.

private class ExampleAdapter extends ArrayAdapter<String>{

    public ExampleAdapter(Context context, int textViewResourceId, String[] objects) {
        super(context, textViewResourceId, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        View view =  super.getView(position, convertView, parent);

        TextView tv = (TextView) view.findViewById(android.R.id.text1);
        tv.setTextColor(0);

        return view;
    }

Ответ 4

Если u хочет установить фон списка, поместите изображение перед символом <TextView>

< ImageView
android:background="@drawable/image_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>

и если u хочет изменить цвет, тогда поставьте цветовой код над текстовым полем таким образом

 android:textColor="#ffffff"

Ответ 5

Если вам просто нужно изменить некоторые параметры представления и поведения по умолчанию для ArrayAdapter, то для вас это будет ОК:

 import android.content.Context;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ArrayAdapter;

 public class CustomArrayAdapter<T> extends ArrayAdapter<T> {

    public CustomArrayAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

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

            // Here all your customization on the View
            view.setBackgroundColor(.......);
            ...

        return view;
    }


 }

Ответ 6

Если вы хотите использовать цвет из colors.xml, поэкспериментируйте

   public View getView(int position, View convertView, ViewGroup parent) {
        ... 
        View rowView = inflater.inflate(this.rowLayoutID, parent, false);
        rowView.setBackgroundColor(rowView.getResources().getColor(R.color.my_bg_color));
        TextView title = (TextView) rowView.findViewById(R.id.txtRowTitle);
        title.setTextColor(
            rowView.getResources().getColor(R.color.my_title_color));
        ...
     }

Вы также можете использовать:

private static final int bgColor = 0xAAAAFFFF;
public View getView(int position, View convertView, ViewGroup parent) {
        ... 
        View rowView = inflater.inflate(this.rowLayoutID, parent, false);
            rowView.setBackgroundColor(bgColor);
...
}

Ответ 7

Вы можете выбрать такого ребенка, как

TextView tv = (TextView)lv.getChildAt(0);
tv.setTextColor(Color.RED);
tv.setTextSize(12);    

Ответ 8

используйте их в Java-коде, например:

 color = getResources().getColor(R.color.mycolor);

Метод getResources() возвращает класс ResourceManager для текущей активности, а getColor() запрашивает у менеджера поиск цвета с учетом идентификатора ресурса

Ответ 9

в android 6.0 вы можете изменить цвет текста, как показано ниже

holder._linear_text_active_release_pass.setBackgroundColor(ContextCompat.getColor(context, R.color.green));