РАЗЫСКИВАЕТСЯ: ListView, похожий на TableLayout

У меня может быть вопрос: «Как создать однострочный горизонтальный LinearLayout с двумя однострочными TextView без переноса, где левый TextView всегда занимает 1/3 доступной ширины экрана, правый TextView всегда занимает 2/3 доступной ширины экрана, а текстовые метки усекаются ... когда они слишком длинные для отображения? " (Если этот вопрос достаточно ясен и читатель - это вы - уже имеет в виду решение, которым они готовы поделиться, дальнейшее чтение проблемы и описания вопроса может быть ненужным.)

ListView, заполненный четырьмя такими LinearLayouts будет выглядеть примерно так:

medium length text ---- short text
short text         ---- text that is too loooooooooooooo...
loooooooooooooo... ---- short text
loooooooooooooo... ---- text that is too loooooooooooooo...
В этом макете в первой строке ,

Из различных сообщений о stackoverflow и других местах я понял, что, хотя использование TableLayout с ArrayAdapter в некоторой степени возможно, есть и обратные стороны, и, вероятно, это неправильный подход.

Я определенно пробовал много комбинаций параметров макета, но еще ничего не подошло вплотную к цели. Я пытаюсь найти решение, которое будет работать на экранах разных размеров, поэтому указание определенной ширины в пикселях, вероятно, не будет работать очень хорошо.

Возможно, следующий простой пример кода (со снимком экрана) является хорошей отправной точкой для

(Форматировщик кода stackoverflow волновался из-за этого кода. Так что простите, пожалуйста, за любопытное форматирование.)

public class TableLayoutLikeListView extends ListActivity
{
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);

    List<Datum> data = new ArrayList<Datum>();
    data.add(new Datum("short", "short"));
    data.add(new Datum("short", "loooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnnnnnnng"));
    data.add(new Datum("loooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnnnnnnng", "short"));
    data.add(new Datum("loooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnnnnnnng",
        "loooooooooooooooooooooooooooooooooooooooooonnnnnnnnnnnnnnnnnnnnnng"));
    setListAdapter(new MyAdapter(this, R.layout.row, data));
  }
}
class Datum
{
  String left, right;

  Datum(String left, String right)
  {
    this.left = left;
    this.right = right;
  }
}

class MyAdapter extends ArrayAdapter<Datum>
{
  List<Datum> data;
  int textViewResourceId;

  MyAdapter(Context context, int textViewResourceId, List<Datum> data)
  {
    super(context, textViewResourceId, data);
    this.data = data;
    this.textViewResourceId = textViewResourceId;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent)
  {
    if (convertView == null)
    {
      LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      convertView = inflater.inflate(textViewResourceId, null);
    }
    Datum datum = data.get(position);
    if (datum != null)
    {
      TextView leftView = (TextView) convertView.findViewById(R.id.left);
      TextView rightView = (TextView) convertView.findViewById(R.id.right);
      if (leftView != null)
      {
        leftView.setText(datum.left);
      }
      if (rightView != null)
      {
        rightView.setText(datum.right);
      }
    }
    return convertView;
  }
}

list.xml: 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ListView
        android:id="@+id/android:list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="3">
    <TextView
        android:id="@+id/left"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:singleLine="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="----" />
    <TextView
        android:id="@+id/right"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:singleLine="true" />
</LinearLayout>

(Обратите внимание, что хотя TextView имеет атрибут ellipsize, он не имеет ' t кажется необходимым изменить, поскольку установка singleLine в true уже усекает и преобразует метки в многоточие. Я могу ошибаться насчет этого.)

Ниже приведен снимок экрана этого кода в действии:

Любые советы, конечно, приветствуются.

9
задан Thane Anthem 1 April 2011 в 05:28
поделиться