2014-11-03 5 views
0

Я создал ListView, следуя учебному пособию в Интернете. Он отлично работает и точно так, как я хочу. Теперь я пытаюсь создать еще один ListView в другой активности, но на этот раз мне нужны два TextViews, а не один.Как добавить еще один TextView в свой список?

Вот мой адаптер:

public class CustomListTwo extends ArrayAdapter<String> { 

private final Activity context; 
private final String[] web; 
// private final String[] hex; <-- was trying to add this one but it gave me an error :(
private final Integer[] imageId; 

public CustomListTwo(Activity context, 
        String[] web, Integer[] imageId) { 
    super(context, R.layout.color_item_layout, web); 
    this.context = context; 
    this.web = web; 
    this.imageId = imageId; 
} 

@Override 
public View getView(int position, View view, ViewGroup parent) { 
    LayoutInflater inflater = context.getLayoutInflater(); 

    View rowView= inflater.inflate(R.layout.color_item_layout, null, true); 
    TextView txtTitle = (TextView) rowView.findViewById(R.id.item_value); 
    ImageView imageView = (ImageView) rowView.findViewById(R.id.item_color); 

    txtTitle.setText(web[position]); 
    imageView.setImageResource(imageId[position]); 

    return rowView; 

    } 
} 

Я пытаюсь добавить "String [] гекс;" но он дает мне ошибку, говоря, что «переменная не может быть инициализирована». Моя идея состояла в том, чтобы дублировать все, что было написано о веб-переменной, и заменить ее шестнадцатеричной переменной и изменить значения.

Вот моя активность:

public class ColorRed extends Activity { 

ListView list; 
String[] web; 
Integer[] imageId = { 
     R.color.red_50, 
     R.color.red_100, 
     R.color.red_200, 
     R.color.red_300, 
     R.color.red_400, 
     R.color.red_500, 
     R.color.red_600, 
     R.color.red_700, 
     R.color.red_800, 
     R.color.red_900, 
     R.color.red_A100, 
     R.color.red_A200, 
     R.color.red_A400, 
     R.color.red_A700, 
}; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_color_red); 

    web = getResources().getStringArray(R.array.values); 

    CustomListTwo adapter = new 
      CustomListTwo(ColorRed.this, web, imageId); 
    list=(ListView)findViewById(R.id.list_red); 
    list.setAdapter(adapter); 
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, 
           int position, long id) { 
      switch (position){ 
       case 0: r50(view); 
        break; 
       case 1: r50(view); 
        break; 
       default: 
        r50(view); 
        break; 
      } 

      } 
     }); 
    } 

Вот мой ListView элемент:

<?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="72dp" 
    android:background="?android:attr/selectableItemBackground"> 

    <ImageView 
    android:background="?android:attr/selectableItemBackground" 
    android:layout_width="match_parent" 
    android:layout_height="72dp" 
    android:id="@+id/item_color" 
    android:src="@drawable/myrect" /> 

    <TextView 
    android:id="@+id/item_hex" 
    android:layout_width="wrap_content" 
    android:layout_height="72dp" 
    android:textColor="#de000000" 
    android:textAllCaps="true" 
    android:textSize="18sp" 
    android:text="List Item" 
    android:paddingRight="16dp" 
    android:gravity="center_vertical" 
    android:layout_centerVertical="true" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentEnd="true" /> 

    <TextView 
    android:layout_width="wrap_content" 
    android:layout_height="72dp" 
    android:text="New Text" 
    android:textColor="#de000000" 
    android:textSize="18sp" 
    android:id="@+id/item_value" 
    android:layout_centerVertical="true" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentStart="true" 
    android:paddingLeft="16dp" 
    android:gravity="center_vertical"/> 

    </RelativeLayout> 

Так поясню, мой вопрос, как я могу добавить новый TextView и загрузить его с массивом из strings.xml как и в текущем TextView? Я хочу, чтобы TextView «hex» был заполнен текстом из массива, который я объявляю в файле strings.xml.

EDIT: Мой обновленный адаптер:

public class CustomListTwo extends ArrayAdapter<String> { 

    private final Activity context; 
    private final String[] web; 
    private final String[] hex; 
    private final Integer[] imageId; 

    public CustomListTwo(Activity context, String[] web, String[] hex, Integer[] imageId) { 
     super(context, R.layout.color_item_layout, web, hex); 
     this.context = context; 
     this.web = web; 
     this.hex = hex; 
     this.imageId = imageId; 
    } 

    @Override 
    public View getView(int position, View view, ViewGroup parent) { 
     LayoutInflater inflater = context.getLayoutInflater(); 

     View rowView= inflater.inflate(R.layout.color_item_layout, null, true); 
     TextView txtTitle = (TextView) rowView.findViewById(R.id.item_value); 
     ImageView imageView = (ImageView) rowView.findViewById(R.id.item_color); 

     TextView txtHex = (TextView) rowView.findViewById(R.id.item_hex); 
     txtHex.setText(hex[position]); 

     txtTitle.setText(web[position]); 
     imageView.setImageResource(imageId[position]); 

     return rowView; 
    } 
} 

Обновлено активность:

public class ColorRed extends Activity { 

    ListView list; 
    String[] web; 
    String[] hex; 
    Integer[] imageId = { 
      R.color.red_50, 
      R.color.red_100, 
      R.color.red_200, 
      R.color.red_300, 
      R.color.red_400, 
      R.color.red_500, 
      R.color.red_600, 
      R.color.red_700, 
      R.color.red_800, 
      R.color.red_900, 
      R.color.red_A100, 
      R.color.red_A200, 
      R.color.red_A400, 
      R.color.red_A700, 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_color_red); 

     web = getResources().getStringArray(R.array.values); 
     hex = getResources().getStringArray(R.array.hex_red); 

     CustomListTwo adapter = new 
       CustomListTwo(ColorRed.this, web, hex, imageId); 
     list=(ListView)findViewById(R.id.list_red); 
     list.setAdapter(adapter); 
     list.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> parent, View view, 
            int position, long id) { 
       switch (position){ 
        case 0: r50(view); 
         break; 
        case 1: r50(view); 
         break; 
        default: 
         r50(view); 
         break; 
       } 

      } 
     }); 
    } 

Теперь я получаю ошибку в этом коде:

super(context, R.layout.color_item_layout, web, hex); 

"Не удается разрешить метод"

ответ

0

Вы не можете объявить конечную переменную и не инициализировать ее нигде.

Пропустите шестнадцатеричный массив в конструкторе адаптера, назначьте его шестнадцатеричному [] в адаптере и используйте его в getView (..).

+0

Спасибо за помощь! Когда я добавляю переменную «hex» в super (контекст, R.layout.color_item_layout, web, hex); он дает мне сообщение об ошибке «Нельзя ссылаться на« CustomListTwo.hex »до того, как был создан конструктор супертипа». – fredthemugwump

+0

Добавлен обновленный адаптер. – fredthemugwump

+1

Измените строку 'super (context, R.layout.color_item_layout, web, hex);' в конструкторе 'CustomListTwo' на' super (context, R.layout.color_item_layout, web); '. –

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