Android, плохие результаты в использовании адаптера массива - PullRequest
0 голосов
/ 19 октября 2011

У меня есть массив строк, и я хочу показать его элементы в списке.У меня есть row.xml, который содержит таблицу, и в каждой строке у меня есть три TextView.Я хочу показать все три элемента массива в каждой строке.

sample: String[] str = {"1", "2", "3", "4", "5", "6"}; Каждая строка должна выглядеть следующим образом:

str[1]----str[2]----str[3]
str[4]----str[5]----str[6]

мой код xml:

<?xml version="1.0" encoding="utf-8"?>

<TableLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:shrinkColumns="*"  
android:stretchColumns="*" >
    <TableRow 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:layout_marginTop="10dip"
    android:layout_marginBottom="10dip" >
        <TextView
            android:id="@+id/outstanding_contractdate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:textSize="15sp" />
        <TextView
            android:id="@+id/outstanding_contractno"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:textSize="15sp" />
        <TextView
            android:id="@+id/outstanding_contractamount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:textColor="#ffffff"
            android:textSize="15sp" />
    </TableRow>

</TableLayout>

в OnCreate () я положил (у меня есть некоторые другие представления и listView):

lvOutstanding = (ListView) findViewById(R.id.outstanding_list);
lvOutstanding.setAdapter(new MyListAdapter());

и это мой адаптер:

class MyListAdapter extends ArrayAdapter<String>{
        MyListAdapter(){
            super(MSOutStanding.this, R.layout.list_outstanding, tokens);
        }

        public View getView(int position, View convertView, ViewGroup parent){
            View row = convertView;

            //String str = llData.get(position);
            //String[] tokens = str.split(",");

            if(row == null){
                LayoutInflater inflater = getLayoutInflater();
                row = inflater.inflate(R.layout.list_outstanding, parent, false);
            }

            TextView tvContDate = (TextView) row.findViewById(R.id.outstanding_contractdate);
            TextView tvContNo = (TextView) row.findViewById(R.id.outstanding_contractno);   
            TextView tvContAmount = (TextView) row.findViewById(R.id.outstanding_contractamount);

            tvContDate.setText(tokens[0]);
            tvContNo.setText(tokens[1]);
            tvContAmount.setText(tokens[2]);

            return(row);
        }
    }

MyПервая проблема, я не вижу результат, как я хочу.а во-вторых, я определил «токены» как строковый массив в верхней части моего класса (private static String[] tokens = {"", "", ""};) таким образом, когда я запускаю приложение, оно показывает мне три строки с одинаковыми результатами.но если я изменю определение, такое как Private static String[] tokens;, программа вылетает.У меня болит голова :( если это возможно, скажите мне, где моя вина?

Спасибо

1 Ответ

1 голос
/ 19 октября 2011

При использовании:

static String[] tokens;

вместо:

static String[] tokens = { "", "", "" };

токены не инициализированы, что означает, что токены [n] равны нулю, что вызывает сбой. В ваших комментариях выполнение токенов [position * count + 1] быстро выйдет за пределы массива - если вы использовали tokens = {"", "", ""}, как указано выше, в массиве всего 3 элемента .

Когда вы передаете токены в супер-конструктор с этой строкой:

super(MSOutStanding.this, R.layout.list_outstanding, tokens);

Вы говорите, что в списке должно быть 3 строки, поскольку в массиве 3 элемента. Для третьего элемента позиция = 3 * count = 3 == boom идет в массив.

Один из способов решить: Передайте массив (или ArrayList) объектов в супер-конструктор:

public class Contract {
        String date;
        String no;
        String amount;

        Contract(String d, String n, String a) {
            date = d;
            no = n;
            amount = a;
        }    
    }

Contract[] contracts = { new Contract("1", "2", "3"), new Contract("4", "5", "6") };
    class MyListAdapter extends ArrayAdapter<Contract>{
         MyListAdapter(){
                super(MSOutStanding.this, R.layout.list_outstanding, contracts);
            }
    }
    ...

    public View getView(int position, View convertView, ViewGroup parent){
        ...
        Contract c = getItem(position);
        tvContDate.setText(c.date);
        tvContNo.setText(c.no);
        tvContAmount.setText(c.amount);
...
    }
...