Правильное использование TwoLineListItem Android

Я новичок в разработке на Android и пытаюсь создать список, который имеет жирный заголовок
и меньшее описание для каждого элемента. Как показано здесь (извините, пока не можете публиковать изображения):

Это XML, с которого я должен начать:

<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TwoLineListItem android:layout_width="fill_parent"
android:layout_height="wrap_content" android:mode="twoLine">
<TextView android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@android:id/text1" android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView android:layout_below="@android:id/text1"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_alignLeft="@android:id/text1" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@android:id/text2" />
</TwoLineListItem>
</LinearLayout> 

Есть ли способ заполнить список из массива в другом файле XML? Если нет, то как бы я заполнил такой список из кода Java? Как я уже сказал, я новичок в разработке, так что я, вероятно, далеко. Спасибо за любой вклад!

3 ответа

Решение

Вы используете просмотр списка http://developer.android.com/reference/android/widget/ListView.html

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

Например, если у меня есть список элементов следующего типа:

public class ProfileItem {
    public String host, name, tag;

    public ProfileItem(String host, String name, String tag) {
        this.host = host;
        this.name = name;
        this.tag = tag;
    }

    @Override
    public String toString() {
        return name+"#"+tag;
    }
}

Затем я создаю следующий адаптер:

public class ProfileItemAdapter extends ArrayAdapter<ProfileItem> {

private Context context;
private int layoutResourceId;   
private List<ProfileItem> objects = null;

public ProfileItemAdapter(Context context, int layoutResourceId, List<ProfileItem> objects) {
    super(context, layoutResourceId, objects);
    this.context = context;
    this.layoutResourceId = layoutResourceId;
    this.objects = objects;
}

public View getView(int position, View convertView, ViewGroup parent)  {
    View v = convertView;
    if(v == null)
    {
        LayoutInflater inflater = ((Activity)context).getLayoutInflater();
        v = inflater.inflate(layoutResourceId, parent, false);
    }

    ProfileItem item = objects.get(position);
    TextView titletext = (TextView)v.findViewById(android.R.id.text1);
    titletext.setText(item.toString());
    TextView mainsmalltext = (TextView)v.findViewById(android.R.id.text2);
    mainsmalltext.setText(item.host);
    return v;
}

}

Тогда все на своем месте, в моей деятельности (или фрагмент), я просто должен установить этот адаптер в onCreate метод:

setListAdapter(new ProfileItemAdapter(getActivity(),
            android.R.layout.two_line_list_item, // or my own custom layout 
            ProfileListContent.ITEMS));

У меня есть аналогичная реализация, но вместо 2-строчного списка, у меня есть 3 строки.

Это XML:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="vertical"  >
    <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#111111"
        android:textSize="17sp"
        android:textStyle="bold"
        android:text="PROJECT NAME"
        android:typeface="monospace"
        android:paddingBottom="2dp"
        android:paddingTop="2dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:gravity="left|center"   >
    </TextView>
    <TextView
        android:id="@+id/text2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#111111"
        android:text="Selected Type"
        android:textSize="16sp"
        android:paddingBottom="1dp"
        android:paddingTop="1dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"  >
    </TextView>
    <TextView
        android:id="@+id/text3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#111111"
        android:textSize="16sp"
        android:paddingTop="1dp"
        android:paddingBottom="1dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:text="Project Description"  >
    </TextView>
</LinearLayout>

И это код JAVA для заполнения строк данными, возвращаемыми из БД. Этот код находится в методе onCreate():

String[] fields = new String[]  {   db.TABLE_PRJ_NAME, db.TABLE_PRJ_TYPE, db.TABLE_PRJ_DESC };
    int[] views = new int[] {   R.id.text1, R.id.text2, R.id.text3  };

    c = db.getAllProjects();
    startManagingCursor(c);

    // Set the ListView
    SimpleCursorAdapter prjName = new SimpleCursorAdapter(
            this,
            R.layout.project_list_rows,
            //android.R.layout.simple_list_item_1,
            c, fields, views);
    setListAdapter(prjName);
Другие вопросы по тегам