2016-08-27 3 views
1

Я пытаюсь отобразить ListView с цветным фоном. Каждая строка должна иметь разные градиентные фоны. Я искал какое-то время, но не смог исправить свою проблему. Каждая строка имеет тот же фон - последний сохраненный профиль. Более того, мне не удалось установить градиент в качестве фона TextView, который использует rounded.xml в качестве фона. Спасибо за любую помощь.CustomAdapter другой элемент списка градиента

Screenshot of my list

Вот мой CustomAdapter:

public class CustomAdapterProfiles extends ArrayAdapter<Profile> { 

    private static final String TAG = "MyActivity"; 
    ArrayList<Profile> myArrayList = null; 
    PaintDrawable paint; 

    int[] arrColors; 
    int numColors; 
    float[] result; 

    Profile i; 

    CustomAdapterProfiles(Context context, ArrayList<Profile> menuAdapter){ 
     super(context, R.layout.customrow , menuAdapter); 
     this.myArrayList = menuAdapter; 
    } 


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

     LayoutInflater listInflater = LayoutInflater.from(getContext()); 
     View customView = listInflater.inflate(R.layout.customrow, parent, false); 

     i = myArrayList.get(position); 
     String singleItem = i.getObjectName(); 
     TextView mobileText = (TextView) customView.findViewById(R.id.listID); 
     mobileText.setText(singleItem); 

     numColors = i.getArrayList().size(); 
     arrColors = new int[i.getArrayList().size()]; 

     if (numColors>1) { 

      //positions of colors defined by user 
      result = new float[numColors]; 
      for (int a = 0; a < numColors; a++) { 
       result[a] = (float) i.getGradients().get(a); 
      } 

      //make sure user didnt write error values (not fixed yet) 
      result[0]=0; 
      result[numColors - 1] = 1; 

      //colors 
      for (int j = 0; j < numColors; j++) { 
       arrColors[j] = Integer.parseInt(i.getArrayList().get(j).toString(), 16) + 0xFF000000; 
      } 

      ShapeDrawable.ShaderFactory shaderFactory = new ShapeDrawable.ShaderFactory() { 
       @Override 
       public Shader resize(int width, int height) { 
        LinearGradient linearGradient = new LinearGradient(0, 0, width, height, 
          arrColors, //pouzity array farieb 
          result, 
          Shader.TileMode.REPEAT); 
        return linearGradient; 
       } 
      }; 
      paint = new PaintDrawable(); 
      paint.setShape(new RectShape()); 
      paint.setShaderFactory(shaderFactory); 

      mobileText.setBackgroundDrawable((Drawable) paint); 
     } 
     else { 
      //cant set shaderFactory becouse it needs 2 or more colors 
      mobileText.getBackground().setColorFilter(Color.parseColor("#" + i.getArrayList().get(0).toString()), PorterDuff.Mode.SRC_ATOP); 
     } 

     return customView; 
    } 
} 

ответ

0

Самая большая проблема (я предполагаю, что это было) использовала ArrayAdapter вместо BaseAdapter. Я пробовал (как программист noob android) много вещей и учебных пособий, но после того, как я пробовал это: enter link description here это сработало. Кроме того, как вы можете видеть, я нашел решение для округленного текстового просмотра (помечено в коде ниже «---»). Имя элементов строки равно «", чтобы вы не могли видеть имена.

enter image description here

public class CustomListAdapter extends BaseAdapter { 
private Context context; //context 
private ArrayList<Profile> items; //data source of the list adapter 

//public constructor 
public CustomListAdapter(Context context, ArrayList<Profile> items) { 
    this.context = context; 
    this.items = items; 
} 

@Override 
public int getCount() { 
    return items.size(); //returns total of items in the list 
} 

@Override 
public Object getItem(int position) { 
    return items.get(position); //returns list item at the specified position 
} 

@Override 
public long getItemId(int position) { 
    return position; 
} 

public void updateResults(ArrayList<Profile> results) { 
    items = results; 
    //Triggers the list update 
    notifyDataSetChanged(); 
} 

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

    if (convertView == null) { 
     convertView = LayoutInflater.from(context).inflate(R.layout.customrow, parent, false); 
     viewHolder = new ViewHolder(convertView); 
     convertView.setTag(viewHolder); 
    } else { 
     viewHolder = (ViewHolder) convertView.getTag(); 
    } 

    // get current item to be displayed 
    Profile currentItem = (Profile) getItem(position); 
    viewHolder.itemName.setText(currentItem.getObjectName()); 


    int numColors = currentItem.getArrayList().size(); 


    if (numColors > 1) { 

     int[] arrColors = new int[numColors]; 

     //positions of colors defined by user 
     final float[] result = new float[numColors]; 
     for (int a = 0; a < numColors; a++) { 
      result[a] = (float) currentItem.getGradients().get(a); 
     } 

     //make sure user didnt write error values (not fixed yet) 
     result[0] = 0; 
     result[numColors - 1] = 1; 

     //colors 
     for (int j = 0; j < numColors; j++) { 
      arrColors[j] = Integer.parseInt(currentItem.getArrayList().get(j).toString(), 16) + 0xFF000000; 
     } 

     final int[] finalArrColors = arrColors; 

     ShapeDrawable.ShaderFactory shaderFactory = new ShapeDrawable.ShaderFactory() { 
      @Override 
      public Shader resize(int width, int height) { 
       LinearGradient linearGradient = new LinearGradient(0, 0, width, height, 
         finalArrColors, //pouzity array farieb 
         result, 
         Shader.TileMode.REPEAT); 
       return linearGradient; 
      } 
     }; 

     // --- rounded textView ! 
     PaintDrawable paint = new PaintDrawable(); 
     paint.setShape(new RectShape()); 
     paint.setShaderFactory(shaderFactory); 

     paint.setCornerRadius(100); 
     // --- end of rounded textView code 

     viewHolder.itemName.setBackgroundDrawable(paint); 
    } 
    else if (numColors == 1) { 
     //not important 
    } 
    else { 
     viewHolder.itemName.setText("empty object"); 
    } 

    return convertView; 
} 

private class ViewHolder { 
    TextView itemName; 

    public ViewHolder(View view) { 
     itemName = (TextView) view.findViewById(R.id.listID); 
    } 
} 

}

Вызов BaseAdapter:

CustomListAdapter adapter = new CustomListAdapter(this, profiles); ListView menuListView = (ListView) findViewById(R.id.listViewHS); menuListView.setAdapter(adapter); adapter.updateResults(profiles);

Профиль Класс:

public class Profile implements Serializable { 

private String objectName; 
private ArrayList<String> arrayColorList; 
private ArrayList<Float> gradients; 

public Profile(String objectName, ArrayList<String> arrayList, ArrayList<Float> gradients){ 
    this.objectName=objectName; 
    this.arrayColorList=arrayList; 
    this.gradients=gradients; 
} 

public String getObjectName() { 
    return objectName; 
} 

public ArrayList<String> getArrayList() { 
    return arrayColorList; 
} 

public ArrayList<Float> getGradients() { 
    return gradients; 
} 

}

0

Удалить фон набор из макета вашего списка пункта. Из вашего кода я вижу, что макет, который вы используете для каждого элемента списка, - customrow.xml. У вас может быть фон rounded.xml. Удалите эту строку.

Теперь о показе правильного цвета для каждого элемента списка ...

Как на картинке я вижу вы устанавливаете некоторый градиент, так что я предполагаю, что вы можете создать градиент правильно.

Теперь, как я вижу из вашего кода, вы устанавливаете один и тот же цвет для каждого элемента вашего ListView. Поэтому, я думаю, вы неправильно поняли поведение функции getView(). Поэтому я проясняю эту идею.

getView() вызывается для каждого элемента ListView, как только он отображается на экране. Предположим, у вас есть 20 элементов в вашем списке. Теперь, когда список загружается в первый раз, предположим, что на экране отображены первые 7 элементов, и вам нужно прокрутить, чтобы увидеть другие элементы.

Теперь вот как ListView работает для повторного цикла созданных представлений. ListView не заполняет все 20 предметов одновременно. Вместо этого он заполняет первые 7, которые отображаются на экране. Поэтому в первый раз функция getView() называется 7 раз, чтобы заполнить каждый элемент, видимый на экране. При прокрутке списка функция getView() вызывается снова для каждого из новых видимых элементов в списке.

Надеюсь, у вас есть идея из объяснения. Теперь, вот как вы можете решить свою проблему.

Возьмем массив цветов, которые определяются пользователем.

int[] arrColors = {/* ..get the user input and populate the colour array outside of the adapter. */}; 
int numColors = 10; // I've just set a default value 

Теперь вот псевдо код вашей getView функции.

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

    LayoutInflater listInflater = LayoutInflater.from(getContext()); 
    View customView = listInflater.inflate(R.layout.customrow, parent, false); 

    // ... Set the text 
    // position of colors defined by user 
    // ... Get the user defined colour here. 
    Color color = arrColors[position]; 

    // Now modify the colour as you wish 
    Paint paint = prepareTheBackground(); 

    // Now set the colour as background 
    mobileText.setBackgroundDrawable((Drawable) paint); 

    return customView; 
} 
+0

Спасибо за ответ! :) Точка использования rounded.xml в качестве фона customrow.xml - я хотел, чтобы конечный результат был округленным текстовым видом с градиентом цвета фона. Но это не большая проблема. Псевдокод, который вы опубликовали, это в основном код, который у меня есть. Он устанавливает градиентные фоны для каждого элемента. Я хотел, чтобы он был уникальным:/Каждый элемент имеет объект, содержащий цвета для градиента. После добавления нового элемента все элементы имеют фон из последнего добавленного. –

+0

Главное, чтобы установить фон для каждого элемента списка правильно? Из вашего кода я вижу, что вы устанавливаете одинаковый цвет фона для всех элементов. Моя идея состоит в том, чтобы сначала заполнить массив желаемыми цветами, а затем получить «позицию» в виде списка в функции getView() и получить точный цвет из этого массива. Проверьте код еще раз. –

Смежные вопросы