programing tip

두 개의 TextView가 나란히 있고 하나만 타원 크기입니까?

itbloger 2020. 11. 22. 19:08
반응형

두 개의 TextView가 나란히 있고 하나만 타원 크기입니까?


TextView목록 항목에서 요소를 나란히 표시하고 하나는 왼쪽에, 하나는 오른쪽에 정렬합니다. 다음과 같은 것 :

|<TextView>               <TextView>|

( |화면의 사지를 나타냄)

그러나 TextView왼쪽에는 화면에 맞추기에는 너무 긴 콘텐츠가있을 수 있습니다. 이 경우 타원 크기를 원하지만 여전히 전체 오른쪽을 표시합니다 TextView. 다음과 같은 것 :

|This is a lot of conte...<TextView>|

나는 이것에 대해 많은 시도를했고, 둘 다 사용 LinearLayout했고 RelativeLayout, 내가 생각 해낸 유일한 해결책은 a를 사용 하고 오른쪽을 지울만큼 충분히 큰 왼쪽에 a RelativeLayout를 두는 것 marginRight입니다 . 하지만 상상할 수 있듯이 이것은 최적이 아닙니다.TextViewTextView

다른 해결책이 있습니까?

최종 LinearLayout솔루션 :

<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:orientation="horizontal"
    >
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_weight="1"
        android:ellipsize="end"
        android:inputType="text"
        />
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_weight="0"
        android:layout_gravity="right"
        android:inputType="text"
        />
</LinearLayout>

기존 TableLayout솔루션 :

<TableLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1"
    android:shrinkColumns="0"
    >
    <TableRow>
        <TextView android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            />
        <TextView android:id="@+id/date"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:singleLine="true"
            android:ellipsize="none"
            android:gravity="right"
            />
    </TableRow>
</TableLayout>

TableLayout을 사용하고 두 TextView를 테이블 행에 넣으십시오. 나는 시도하지 않았다


그냥 생각, xml 레이아웃에서 먼저 오른쪽의 textview를 선언하고 너비를 랩 내용으로 설정 android:layout_alignParentRight="true"하고 android:gravity="right". 그런 다음 왼쪽에 텍스트 뷰를 선언하고 너비를 채우기 부모로 설정하고 android:layout__toLeftOf= {오른쪽 텍스트 RelativeView의 ID}를 루트 뷰로 설정합니다.

먼저 오른쪽 텍스트 뷰를 선언하면 필요한 너비가 먼저 계산되어 뷰를 차지하고 왼쪽 텍스트 뷰가 뷰의 나머지 공간을 차지합니다.

나는 당신에게 약간의 아이디어를 줄 수도 있지만 이것을 시도하지 않았습니다.

[최신 정보]

xml 리소스 레이아웃을 만들려고했는데 어떻게 든 작동합니다 ...

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
  <TextView 
    android:id="@+id/right"
    android:layout_alignParentRight="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="right"
    android:text="right"
    >
  </TextView>
  <TextView 
    android:id="@+id/left"
    android:layout_alignParentLeft="true"
    android:layout_toLeftOf="@id/right"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ellipsize="end"
    android:lines="1"
    android:singleLine="true"
    android:maxLines="1"
    android:text="too looooooooooong ofskgjo sdogj sdkogjdfgds dskjgdsko jgleft"
    >
  </TextView>
</RelativeLayout>

The LinearLayout answer worked for me with this same problem. Posted as a separate answer because it wasn't clear what did and didn't work for the asker.

One difference. TableLayout was less ideal for me because I had two rows of data, and I wanted the bottom row to behave as this question describes, and the top row to span the area. That question's been answered in another SO question: Colspan in TableLayout, but LinearLayout was simpler.

Though getting the widths right took me a bit. I included the android lint tweak of using 0dp width on the scaling item for performance.

<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:orientation="horizontal"
    >
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:ellipsize="end"
        android:inputType="text"
        />
    <TextView
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_weight="0"
        android:layout_gravity="right"
        android:inputType="text"
        />
</LinearLayout>

There are many answers to this and practically equivalent, duplicate questions on SO. The suggested approaches usually work, sort of. Putting it into a LinearLayout, wrap the whole in an extra RelativeLayout, use a TableLayout; all these seem to solve it for a simpler layout but if you need these two TextViews inside something more complicated, or the same layout will be reused, for instance, by a RecyclerView, things get broken very quickly.

The only solution I found that really works all the time, regardless of what bigger layout you put it into, is a custom layout. It's very simple to implement, and being as lean as it possibly gets, it will keep the layout reasonably flat, it's easy to maintain—so in the long run, I consider this the best solution to the problem.

public class TwoTextLayout extends ViewGroup {

  public TwoTextLayout(Context context) {
    super(context);
  }

  public TwoTextLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public TwoTextLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  @Override
  protected void onLayout(boolean changed, int l, int t, int r, int b) {
    final int count = getChildCount();
    if (count != 2)
      throw new IllegalStateException("TwoTextLayout needs exactly two children");

    int childLeft = this.getPaddingLeft();
    int childTop = this.getPaddingTop();
    int childRight = this.getMeasuredWidth() - this.getPaddingRight();
    int childBottom = this.getMeasuredHeight() - this.getPaddingBottom();
    int childWidth = childRight - childLeft;
    int childHeight = childBottom - childTop;

    View text1View = getChildAt(0);
    text1View.measure(MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.AT_MOST));
    int text1Width = text1View.getMeasuredWidth();
    int text1Height = text1View.getMeasuredHeight();

    View text2View = getChildAt(1);
    text2View.measure(MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.AT_MOST));
    int text2Width = text2View.getMeasuredWidth();
    int text2Height = text2View.getMeasuredHeight();

    if (text1Width + text2Width > childRight)
      text1Width = childRight - text2Width;

    text1View.layout(childLeft, childTop, childLeft + text1Width, childTop + text1Height);
    text2View.layout(childLeft + text1Width, childTop, childLeft + text1Width + text2Width, childTop + text2Height);
  }
}

The implementation couldn't be simpler, it just measures the two texts (or any other child views, actually) and if their combined width exceeds the layout width, reduces the width of the first view.

And if you need modifications, eg. to align the second text to the baseline of the first, you can solve that easily, too:

text2View.layout(childLeft + text1Width, childTop + text1Height - text2Height, childLeft + text1Width + text2Width, childTop + text1Height);

Or any other solution, like shrinking the second view in relation to the first, aligning to the right, etc.


Why don't you put a left margin on the right TextView? I'm using this approach for a

|<TextView>       <ImageButton>|

and it works.

참고URL : https://stackoverflow.com/questions/3785221/two-textviews-side-by-side-only-one-to-ellipsize

반응형