2014-10-22 3 views
0

У меня есть 4 поля в настраиваемом макете строк для списка. У меня есть 4 поля в моем массиве, я хочу, чтобы отобразить в этих 4-х полей на ListView:Заполнение ListView элементами из массива в Java

  1. cat_ID_PK
  2. cat_name
  3. cat_amount
  4. is_recurring

Я не знаю, как правильно это сделать. Вот то, что я до сих пор:

private void loadListView(Expenses[] mExpenseArray) { 

//This code will write the "name" variable correctly to the logcat, so I know I'm 
getting the right values in my array. 

    String name = mExpenseArray[0].getCatName(); 
    Log.v("log_tag", name); 

    ArrayAdapter<Expenses> adapter = new ArrayAdapter<Expenses>(getApplicationContext(), R.layout.list_row, R.id.catName, mExpenseArray); 
    final ListView listView = (ListView) findViewById(R.id.list); 
    listView.setAdapter(adapter); 
} 

Этот код заполнит только R.id.catName, но когда она заполнит его, это выглядит следующим образом: [email protected] (или что-то подобное). Ни одно из других полей не заполнено вообще, что, как я предполагаю, связано с 3-м параметром в моем массиве ArrayAdapter R.id.catName. Однако, если я возьму этот параметр, что я получаю эту ошибку:

java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView 

Вот код для моего пользовательского макета строки:

<?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="wrap_content" 
    android:background="@drawable/list_selector" 
    android:orientation="horizontal" 
    android:padding="5dip" > 

<TextView 
    android:id="@+id/catName" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginLeft="15dip" 
    android:layout_centerVertical="true" 
    android:paddingBottom ="10dip" 
    android:text="@string/catName" 
    android:textColor="#040404" 
    android:textSize="25dip" 
    android:textStyle="bold" 
    android:typeface="sans" /> 

<TextView 
    android:id="@+id/catAmount" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginRight="27dip" 
    android:layout_centerVertical="true" 
    android:layout_alignParentRight="true" 
    android:paddingBottom ="10dip" 
    android:text="$45.00" 
    android:textColor="#040404" 
    android:textSize="25dip" 
    android:textStyle="bold" 
    android:typeface="sans" /> 

<TextView 
    android:id="@+id/catType" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/catName" 
    android:layout_alignLeft="@+id/catName" 
    android:paddingTop="5dip" 
    android:layout_centerHorizontal="true" 
    android:text="@string/catType" 
    android:textColor="#343434" 
    android:textSize="15dip" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="catID" 
    android:id="@+id/catID" 
    android:layout_alignBottom="@+id/catType" 
    android:layout_toRightOf="@+id/catType" 
    android:layout_toEndOf="@+id/catType" 
    android:layout_marginLeft="27dp" 
    android:visibility="invisible" /> 
</RelativeLayout> 

Как правильно отображающие мои 4 поля массива в моей ListView?

+0

Вы должны использовать пользовательский адаптер – Abdellah

+0

попробуйте использовать пользовательский адаптер. –

+0

«Расходы» должны быть моделью данных, поэтому вам нужно использовать пользовательский адаптер, чтобы получить значение от модели. –

ответ

0

сделать пользовательский адаптер, как это, а затем присвоить значения с видом текста

проход массива, как это к адаптеру

UserList disadpt = new UserList(HomePage.this, mEmployeeList); 
    userList.setAdapter(disadpt); 

затем адаптер сделать это ..

public class UserList extends BaseAdapter 
{ 
    private Context mContext; 
    private ArrayList<Employee> items; 

    public UserList(Context c, ArrayList<Employee> items) 
    { 
     this.mContext = c; 
     this.items = items; 
    } 

     public int getCount() { 
     return this.items.size(); 
    } 

    public Object getItem(int position) { 
     return this.items.get(position); 
    } 

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

    @Override 
    public View getView(int pos, View child, ViewGroup arg2) { 
    Holder mHolder; 
    LayoutInflater layoutInflater; 
    if (child == null) { 
     layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     child = layoutInflater.inflate(R.layout.listcell, null); 
     mHolder = new Holder(); 

     //mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id); 
     mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName); 
     mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName); 
     mHolder.txt_userName = (TextView) child.findViewById(R.id.txt_userName); 

     child.setTag(mHolder); 
    } else { 
     mHolder = (Holder) child.getTag(); 
    } 

    Employee employee = this.items.get(pos); 

    ArrayList<String> employeeInfo = new ArrayList<String>(); 
    employeeInfo.add(employee.employeeId); 
    employeeInfo.add(employee.firstName); 
    employeeInfo.add(employee.lastName); 

    mHolder.Details.setTag(employeeInfo); 

    mHolder.txt_fName.setText(employee.firstName + " " + employee.lastName);  
    mHolder.txt_userName.setText(employee.emailId); 

    return child; 
} 

public class Holder 
{ 
    //TextView txt_id; 
    TextView txt_fName; 
    TextView txt_lName; 
    TextView txt_userName; 
    Button Details; 
} 
} 

надеюсь, что это поможет ...

+0

Я бы передал массив к пользовательскому адаптеру. В вашем примере вы проходите в каждом отдельном элементе. Должен ли я проходить в каждом отдельном элементе? Если я могу передать в моем массиве, как мне обрабатывать это после его передачи в пользовательский адаптер? Новое в java, так что это все сложнее, чем должно быть. – hyphen

+0

@hyphen Я только что отредактировал свой ответ, вы можете передать массив в пользовательский адаптер, попробовав отредактированный ответ, а потом скажите мне? :) – Umair

0

Создать тип струнного массива Адаптер и использовать -

adapter.add(mExpenseArray[0].getCatName()); 

используя любой цикл.

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