Реализовать TextViews, если расширяет прошлый контейнер - PullRequest
0 голосов
/ 25 мая 2011

У меня есть ListView, и я хочу настроить макет каждого элемента в списке так, чтобы он имел кнопку справа и раздел слева от кнопки, в котором есть несколько слов, которые являются TextViews (т.е. каждый TextViewв левой части будет одно слово).Вот изображение того, что я имею в виду: Image button on right and left side has TextViews (squiggly lines)

Прямо сейчас я смог успешно получить ButtonImage, где я хочу (с определенной шириной 40dp).Если я просто поместил TextViews в RelativeLayout, я заметил, что они накладываются друг на друга, поэтому я добавил «android: layout_toRightOf» в каждый из TextView соответственно.Очевидно, это означает, что у меня никогда не будет слов ниже друг друга.Я настроил левую сторону этого макета так, чтобы он имел отступ 40 dp справа от него (чтобы TextViews не шли за кнопкой и не сталкивались с ней).Что происходит, так это то, что TextViews будут идеально выровнены вверху, а затем последние несколько, которые не могут сжаться, будут расширяться по вертикали, чтобы заполнить левую боковую сторону.Я хотел бы, чтобы область левого поля (с TextViews) была настроена таким образом, чтобы, если TextView собирается ударить по правой стене (технически отступ 40dp от правой стены родителя), он будет перемещен вниз и полностьюслева слова читаются как книга.Также обратите внимание, что для любого данного элемента в ListView будет где-то от 1 до 5 TextViews (слов) в этой левой части.Я почти уверен, что если я смогу получить свой макет так, как я хочу, мне никогда не придется беспокоиться о том, что левая сторона будет располагаться выше, чем изображение кнопки (что в любом случае будет легко решаемой проблемой).Вот мой код:

<?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="fill_parent"
    android:orientation="horizontal"
>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:paddingRight="40dp"
        android:id="@+id/kwds"
    >
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/first"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    />
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/second"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/first"
    />
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/third"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/second"
    />
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fourth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/third"
    />
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fifth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/fourth"
    />
    </RelativeLayout>   
    <ImageButton android:id="@+id/bkmbtn"
    android:src="@drawable/bkbtn"
    android:layout_width="40dp"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    >
    </ImageButton>
</RelativeLayout>

Прежде чем вы, ребята, спросите, да, действительно нужно иметь TextView для каждого слова (к сожалению).Если что-то неясно, дайте мне знать.И спасибо за любую помощь, которую вы можете предложить мне!Я действительно надеюсь, что это возможно.

Ответы [ 2 ]

0 голосов
/ 04 июня 2011

Итак, я достиг этого первым естественным путем, о котором можно подумать.Я установил 5x5 «таблицу» горизонтально ориентированных LinearLayouts, которые накладываются друг на друга, чтобы придать ему вид TableLayout.Я не использовал TableLayout, поэтому я мог легко установить для каждой «строки» LinearLayout начальную видимость «ушел» и сделать ее видимой при необходимости (чтобы она не давала каждой записи ощущение раздутости).Вот пример того, что я сделал:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:paddingLeft="2dp"
    android:paddingRight="40dp"
    android:id="@+id/kwds"
    android:orientation="vertical"
>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:id="@+id/kwdsone"
    >
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/first"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:textSize="20sp"
        />
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/second"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/first"
            android:textColor="#000000"
            android:textSize="20sp"
        />
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/third"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/second"
            android:textColor="#000000"
            android:textSize="20sp"
        />
    </LinearLayout>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:id="@+id/kwdstwo"
        android:layout_below="@id/kwdsone"
        android:visibility="gone"
    >
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/fourth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:textSize="20sp"
        />
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/fifth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/fourth"
            android:textColor="#000000"
            android:textSize="20sp"
        />
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/sixth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/fifth"
            android:textColor="#000000"
            android:textSize="20sp"
        />
    </LinearLayout>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:id="@+id/kwdsthree"
        android:layout_below="@id/kwdstwo"
        android:visibility="gone"
    >
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/seventh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:textSize="20sp"
        />
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/eighth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/seventh"
            android:textColor="#000000"
            android:textSize="20sp"
        />
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/ninth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/eighth"
            android:textColor="#000000"
            android:textSize="20sp"
        />
    </LinearLayout>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:id="@+id/kwdsfour"
        android:layout_below="@id/kwdsthree"
        android:visibility="gone"
    >
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/tenth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:textSize="20sp"
        />
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/eleventh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/tenth"
            android:textColor="#000000"
            android:textSize="20sp"
        />
        <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/twelth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/eleventh"
            android:textColor="#000000"
            android:textSize="20sp"
        />
    </LinearLayout> 
</RelativeLayout>

В этом примере я использую макет «таблицы» типа 4x3, но я изменил его на 5x5 (в сценарии может быть 5 TextViews).все они занимают целую строку).

Далее я создал очень простой алгоритм, в котором я заполняю первый TextView каждой строки, несмотря ни на что, но каждый TextView после этого будетзаполняется, только если максимальная ширина контейнера минус ширина слова, которое входило в TextView, и ширина предыдущих уже заполненных TextViews в той же строке была больше или равна нулю.То есть, если ширина следующего слова не будет превышать ширину родительского слова.Вот как это выглядело:

Paint paint = new Paint();
// Convert the dps and sps to pixels with scale variable 
float scale = getContext().getResources().getDisplayMetrics().density;
paint.setTextSize(20*scale);
//pWidth is the parent width, subtracting 55dps because of the button on the right of each entry
pWidth = parent.getWidth() - (55*scale);
//decide which index to set
            if (indx==1){
                if ((pWidth-(paint.measureText(((Spannable)((TextView)v.findViewById(R.id.first)).getText()).toString())+paint.measureText(word+"...")))<0)
                    indx=3;
            }
            if (indx==2){
                if ((pWidth-(paint.measureText(((Spannable)((TextView)v.findViewById(R.id.first)).getText()).toString())+paint.measureText(((Spannable)((TextView)v.findViewById(R.id.second)).getText()).toString())+paint.measureText(word+"...")))<0)
                    indx=3;
            }
            if (indx==3){
                v.findViewById(R.id.kwdstwo).setVisibility(View.VISIBLE);
                if ((pWidth-paint.measureText(word+"..."))<0)
                    ((TextView)v.findViewById(R.id.fourth)).setTextSize(16);
            }
            if (indx==4){
                if ((pWidth-(paint.measureText(((Spannable)((TextView)v.findViewById(R.id.fourth)).getText()).toString())+paint.measureText(word+"...")))<0)
                    indx=6;
            }
            if (indx==5){
                if ((pWidth-(paint.measureText(((Spannable)((TextView)v.findViewById(R.id.fourth)).getText()).toString())+paint.measureText(((Spannable)((TextView)v.findViewById(R.id.fifth)).getText()).toString())+paint.measureText(word+"...")))<0)
                    indx=6;
            }
            if (indx==6){
                v.findViewById(R.id.kwdsthree).setVisibility(View.VISIBLE);
                if ((pWidth-paint.measureText(word+"..."))<0)
                    ((TextView)v.findViewById(R.id.seventh)).setTextSize(16);
            }
            if (indx==7){
                if ((pWidth-(paint.measureText(((Spannable)((TextView)v.findViewById(R.id.seventh)).getText()).toString())+paint.measureText(word+"...")))<0)
                    indx=9;
            }
            if (indx==8){
                if ((pWidth-(paint.measureText(((Spannable)((TextView)v.findViewById(R.id.seventh)).getText()).toString())+paint.measureText(((Spannable)((TextView)v.findViewById(R.id.eighth)).getText()).toString())+paint.measureText(word+"...")))<0)
                    indx=9;
            }
            if (indx==9){
                v.findViewById(R.id.kwdsfour).setVisibility(View.VISIBLE);
                if ((pWidth-paint.measureText(word+"..."))<0)
                    ((TextView)v.findViewById(R.id.tenth)).setTextSize(16);
            }
//based on the indx, populate the given TextView, again this is based on the 4x3 model and not the 5x5 model
if (indx==0)
    index = (TextView) v.findViewById(R.id.first);
else if (indx==1)
index = (TextView) v.findViewById(R.id.second);
else if (indx==2)
index = (TextView) v.findViewById(R.id.third);
else if (indx==3)
index = (TextView) v.findViewById(R.id.fourth);
else if (indx==4)
index = (TextView) v.findViewById(R.id.fifth);
else if (indx==5)
index = (TextView) v.findViewById(R.id.sixth);
else if (indx==6)
index = (TextView) v.findViewById(R.id.seventh);
else if (indx==7)
index = (TextView) v.findViewById(R.id.eighth);
else if (indx==8)
index = (TextView) v.findViewById(R.id.ninth);
else if (indx==9)
index = (TextView) v.findViewById(R.id.tenth);
else if (indx==10)
index = (TextView) v.findViewById(R.id.eleventh);
else
index = (TextView) v.findViewById(R.id.twelth);
indx++;

Обратите внимание, что в этом случае indx - это глобальная переменная, определенная в моем классе и установленная в 0. Итак, когда это происходит снова для другой записи в ListView, indxустанавливается на 0. Вы должны учитывать это, если будете использовать этот метод снова и снова.Если что-то из этого не имеет смысла, не стесняйтесь комментировать здесь, чтобы я мог уточнить мой ответ.

0 голосов
/ 25 мая 2011

Я работал над вашим кодом и внес некоторые изменения. Теперь он работает нормально, как вы ожидаете.

Не дайте забыть проголосовать.

<?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="fill_parent"
    android:orientation="horizontal"
>
<ImageButton android:id="@+id/bkmbtn"
    android:background="@drawable/a_thumb"
    android:layout_width="40dp"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    >
    </ImageButton>
    <LinearLayout 
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:paddingRight="40dp"
        android:id="@+id/kwds"
        android:layout_toLeftOf="@+id/bkmbtn"
        android:orientation="horizontal"
    >
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/first"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="first"
        android:background="#ffffff"
    />
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/second"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="second"
        android:background="#ffffff"

    />
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/third"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/second"
        android:text="third"
        android:background="#ffffff"
    />
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fourth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fourth"
        android:background="#ffffff"

    />
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fifth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="fifth"
        android:background="#ffffff"

    />
    </LinearLayout>   

</RelativeLayout>

Спасибо Дипак

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...