Альтернативная ширина пузыря чата - PullRequest
3 голосов
/ 01 февраля 2012

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

<RelativeLayout
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1"
    >

 <ListView android:id="@+id/list"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:stackFromBottom="true"
    android:transcriptMode="alwaysScroll"
    android:cacheColorHint="#00000000"
    android:listSelector="@android:color/transparent"
    android:divider="@null"
    />
 </RelativeLayout>

<LinearLayout android:id="@+id/footer" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:orientation="horizontal"
    android:gravity="bottom" style="@android:style/ButtonBar">
    <Button
        android:id="@+id/stt_button"
        android:layout_width="45dp"
        android:layout_height="50dp"
        android:background="@drawable/microphone"
    />   

    <EditText android:id="@+id/chat_msg"
        android:inputType="text" 
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_weight="1" />

    <Button android:id="@+id/send_button"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_gravity="center_vertical"
        android:text="@string/send_button" />
</LinearLayout>
</LinearLayout>

Это мой макет list_item:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content" android:weightSum="1.0"
android:layout_weight="1" android:layout_height="wrap_content">
<LinearLayout         
    android:id="@+id/linearLayoutLeft" 
    android:layout_width="0dp"
    android:layout_weight="0.8"
    android:layout_height="wrap_content">
    <RelativeLayout 
        android:id="@+id/relativeLayoutLeft" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content">
        <TextView 
            android:id="@+id/lefttext" 
            android:layout_width="wrap_content" 
            android:gravity="top" 
            android:layout_height="wrap_content" 
            android:paddingLeft="10dip" 
            android:paddingRight="10dip" 
            android:paddingTop="5dip" 
            android:layout_alignParentLeft="true">
        </TextView>
    </RelativeLayout>
</LinearLayout>
<LinearLayout         
    android:id="@+id/linearLayoutRight"
    android:layout_width="0dp"         
    android:layout_weight="0.8"
    android:layout_height="wrap_content">
    <RelativeLayout 
        android:id="@+id/relativeLayoutRight" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content">
        <TextView 
            android:id="@+id/righttext" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:paddingLeft="10dip" 
            android:paddingRight="10dip" 
            android:paddingTop="5dip" 
            android:layout_alignParentRight="true" 
            android:layout_alignParentTop="true">
        </TextView>
    </RelativeLayout>
</LinearLayout>

Это код внутри метода getView моего адаптера массива:

    View view = convertView;
    if(view == null){
        view = mInflater.inflate(R.layout.list_item, null);
    }

    Resources res = getContext().getResources();
    Drawable bubblesChat = res.getDrawable(R.drawable.bubbles_chat);
    Drawable bubblesResponse = res.getDrawable(R.drawable.bubbles_response);
    TextView left = (TextView) view.findViewById(R.id.lefttext);
    TextView right = (TextView) view.findViewById(R.id.righttext);
    View leftLayout = view.findViewById(R.id.relativeLayoutLeft);
    View rightLayout = view.findViewById(R.id.relativeLayoutRight); 
    LinearLayout linearLeft = (LinearLayout) view.findViewById(R.id.linearLayoutLeft);
    LinearLayout linearRight = (LinearLayout) view.findViewById(R.id.linearLayoutRight);

    LayoutParams leftParams = (LayoutParams) linearLeft.getLayoutParams();
    LayoutParams rightParams = (LayoutParams) linearRight.getLayoutParams();

    String txt = super.getItem(position);
    if(txt.startsWith("s:")) {
        left.setText(getItem(position));
        leftLayout.setBackgroundDrawable(bubblesChat);
        leftParams.weight = 0.8f;
        linearLeft.setLayoutParams(leftParams);
        rightParams.weight = 0.2f;
        linearRight.setLayoutParams(rightParams);
        right.setText("");
        rightLayout.setBackgroundDrawable(null);
    } else {
        right.setText(getItem(position));
        rightLayout.setBackgroundDrawable(bubblesResponse);
        rightParams.weight = 0.8f;
        linearRight.setLayoutParams(rightParams);           
        leftParams.weight = 0.2f;
        linearLeft.setLayoutParams(leftParams);
        left.setText("");
        leftLayout.setBackgroundDrawable(null);
    }
    return view;

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

enter image description here

Вы видите, что пузырьки справа не оборачивают ширину в соответствии с размером текста. Я понимаю, почему это происходит - я назначаю вес 0,8 для текущего сообщения чата (может быть слева направо) и 0,2 для остальных. Когда текущее сообщение от левого пузыря, оно работает нормально, так как оно рисуется сначала как вес 0,8 с wrap_content. Но когда правый пузырь является текущим сообщением, левый пузырь рисуется первым и имеет фиксированную ширину 0,2, поэтому правый пузырь всегда получает 0,8 независимо от wrap_content. Как я могу это исправить? Все, что я хочу, это получить пузыри в соответствии с шириной текста и выровнять влево или вправо. Я могу полностью отказаться от моего нынешнего пути, если вы можете предложить лучший способ сделать это правильно.

1 Ответ

5 голосов
/ 06 июля 2012

Когда я впервые опубликовал этот вопрос, я только начал программировать на Android. Проблема была в том, что я слишком усложнил свои определения макета и код. Теперь, когда я упростил свою иерархию макетов, я достиг того, чего хотел, без использования веса макета и с помощью очень простого кода / конфигурации. Здесь я публикую свои обновленные фрагменты кода.

Мой главный макет сейчас:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent">

    <ListView android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:stackFromBottom="true"
        android:transcriptMode="alwaysScroll"
        android:cacheColorHint="#00000000"
        android:listSelector="@android:color/transparent"
        android:divider="@null"/>

    <LinearLayout android:id="@+id/footer" android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="horizontal"
        android:gravity="bottom" style="@android:style/ButtonBar">
        <Button android:id="@+id/stt_button"
            android:layout_width="45dp"
            android:layout_height="50dp"
            android:background="@drawable/microphone"/>   

        <EditText android:id="@+id/chat_msg"
            android:inputType="text" 
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="1" />

        <Button android:id="@+id/send_button"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:layout_gravity="center_vertical"
            android:text="@string/send_button" />
    </LinearLayout>
</LinearLayout>

Расположение элементов списка:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:weightSum="1.0"
    android:layout_weight="1" android:layout_height="wrap_content">

    <TextView android:id="@+id/lefttext" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_marginLeft="10dip" 
        android:layout_marginRight="10dip" 
        android:layout_marginTop="10dip"
        android:layout_marginBottom="5dip"
        android:layout_alignParentLeft="true"
        android:maxWidth="250dip"/>

    <TextView 
        android:id="@+id/righttext" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip" 
        android:layout_marginRight="10dip" 
        android:layout_marginTop="10dip"
        android:layout_marginBottom="5dip"
        android:layout_alignParentRight="true"
        android:maxWidth="250dip"/>
</RelativeLayout>

Это код внутри метода getView моего адаптера массива:

    View view = convertView;
    if(view == null){
         view = mInflater.inflate(R.layout.list_item, null);
    }

    Resources res = getContext().getResources();
    Drawable bubblesChat = res.getDrawable(R.drawable.bubbles_chat);
    Drawable bubblesResponse = res.getDrawable(R.drawable.bubbles_response);
    TextView left = (TextView) view.findViewById(R.id.lefttext);
    TextView right = (TextView) view.findViewById(R.id.righttext);

    String txt = super.getItem(position);
    if(txt.startsWith("s:")) {
        left.setText(getItem(position));
        left.setBackgroundDrawable(bubblesChat);
        right.setText("");
        right.setBackgroundDrawable(null);
    } else {
        right.setText(getItem(position));
        right.setBackgroundDrawable(bubblesResponse);
        left.setText("");
        left.setBackgroundDrawable(null);
    }
    return view;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...