簡體   English   中英

對齊2個文本,1個正常,1個相反

[英]Align 2 texts, 1 normal, 1 opposite

我做了一個 帶有按鈕的應用程序,其中總共有4個文本,我想對齊第一個2.一個位於底部文本的最左側,另一個位於底部文本的右側。

所以從這個:

之前

setText(item.title + " " + item.roomId + "\\n" + item.teacher + " " + item.classes);

對此:

之后(這就是我想要的)

setText(declare here a spannable);

我想我應該使用Spannable ,我已經用Alignment.ALIGN_NORMALAlignment.ALIGN_OPPOSITE嘗試了一些東西,但我認為首先應該計算底部文本的長度,然后進行對齊。 (我在這里找到了一個很好的例子但它在我的設置中沒有用)。

我希望有人能指出我的方向。

編輯:

我不能(我認為)使用RelativeLayoutLinearLayout是我在另一個類( ScheduleItemView.java )中擴展按鈕:

/**
 * Custom view that represents a {@link ScheduleItem} instance, including its
 * title and time span that it occupies. Usually organized automatically by
 * {@link ScheduleItemsLayout} to match up against a {@link TimeRulerView}
 * instance.
 */
public class ScheduleItemView extends Button {

    private ScheduleItem mItem;

    public ScheduleItemView(Context context, ScheduleItem item) {
        super(context);

        mItem = item;

        setSingleLine(false);
        setText(item.title + " " + item.roomId + "\n" + item.teacher + " "
                + item.classes);

        // TODO: turn into color state list with layers?
        int textColor = Color.WHITE;
        int accentColor = item.accentColor;

        LayerDrawable buttonDrawable = (LayerDrawable) context.getResources()
                .getDrawable(R.drawable.btn_block);
        buttonDrawable.getDrawable(0).setColorFilter(accentColor,
                PorterDuff.Mode.SRC_ATOP);
        buttonDrawable.getDrawable(1).setAlpha(item.containsStarred ? 255 : 0);

        setTextColor(textColor);
        setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources()
                .getDimensionPixelSize(R.dimen.text_size_small));

        setGravity(Gravity.CENTER | Gravity.BOTTOM);

        setBackgroundDrawable(buttonDrawable);
    }

    public ScheduleItem getScheduleItem() {
        return mItem;
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(),
                MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(
                getMeasuredHeight(), MeasureSpec.EXACTLY));
        // layout(getLeft(), getTop(), getRight(), getBottom());
        setGravity(Gravity.CENTER);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getRight() - getLeft(), getBottom() - getTop());
    }
}

我試圖在protected void onLayoutScheduleItemsLayout.java )中執行此操作:

child.setLayoutParams(new LayoutParams(
        LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

但那不起作用。 我不確定我是否應該使用new RelativeLayout(this)

在這種情況下使用Spannable更好嗎?

項目源可以在這里下載(你可以在Eclipse中導入)

好吧,如果你不能從Button移動到ViewGroup ,那么你可以在擴展的Button類中做些什么:

去掉:

setText(item.title + " " + item.roomId + "\n" + item.teacher + " "
            + item.classes);

將以下內容添加到ScheduleItemView's構造函數中:

float[] fl1 = new float[item.title.length()];
getPaint().getTextWidths(item.title, fl1);

float[] fl2 = new float[item.roomId.length()];
getPaint().getTextWidths(item.roomId, fl2);

float[] fl3 = new float[item.teacher.length() + item.classes.length() + 1];
getPaint().getTextWidths(item.teacher + " " + item.classes, fl3);

float differenceInWidth = sumUpTheArray(fl3) 
                          - sumUpTheArray(fl1) 
                          - sumUpTheArray(fl2);

float fSpaceArray[] = new float[1];

getPaint().getTextWidths(" ", fSpaceArray);

int numOfSpaces = (int) (differenceInWidth / fSpaceArray[0]);

char[] spaceCharArr = new char[numOfSpaces];

Arrays.fill(spaceCharArr, ' ');

setText(item.title + String.valueOf(spaceCharArr) + item.roomId + "\n" 
                            + item.teacher + " " + item.classes);

添加這個輔助方法,它總結了一個float數組:

public float sumUpTheArray(float[] arr) {
    float sum = 0f;

    for (int i = 0; i < arr.length; i++) {
        sum += arr[i];
    }

    return sum;
}

不確定為什么要覆蓋onDraw(Canvas)onMeasure(int, int)方法。

不用說,這是一個錯綜復雜的代碼片段。 發生的事情是我們正在測量我們必須在titleroomId之間放置多少空間才能獲得所需的對齊。 代碼是直截了當的(雖然令人畏懼),因此沒有包含任何評論。

另一方面,您可以擴展RelativeLayout:

public class ScheduleItemAlternateView extends RelativeLayout {

    private ScheduleItem mItem;  

    public ScheduleItemAlternateView(Context context, ScheduleItem item) {
        super(context);

        mItem = item;

        int textColor = Color.WHITE;
        int accentColor = item.accentColor;

        LayerDrawable buttonDrawable = (LayerDrawable) context.getResources()
            .getDrawable(R.drawable.btn_block);
        buttonDrawable.getDrawable(0).setColorFilter(accentColor,
            PorterDuff.Mode.SRC_ATOP);
        buttonDrawable.getDrawable(1).setAlpha(item.containsStarred ? 255 : 0);

        // Three TextViews to hold the `title`, `roomId`
        // and `teacher&room` independently
        TextView tvTitle = new TextView(context);
        TextView tvRoomId = new TextView(context);
        TextView tvTeacherAndClasses = new TextView(context);

        // Example ids
        tvTitle.setId(100);
        tvRoomId.setId(101);
        tvTeacherAndClasses.setId(102);

        tvTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources()
            .getDimensionPixelSize(R.dimen.text_size_small));
        tvRoomId.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources()
            .getDimensionPixelSize(R.dimen.text_size_small));
        tvTeacherAndClasses.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources()
            .getDimensionPixelSize(R.dimen.text_size_small));

        tvTitle.setPadding(30, 20, 30, 0);
        tvRoomId.setPadding(30, 20, 30, 0);
        tvTeacherAndClasses.setPadding(30, 5, 30, 20);

        tvTitle.setTextColor(textColor);
        tvRoomId.setTextColor(textColor);
        tvTeacherAndClasses.setTextColor(textColor);

        // Set text
        tvTitle.setText(item.title);        
        tvRoomId.setText(item.roomId);      
        tvTeacherAndClasses.setText(item.teacher + " " + item.classes);

        // LayoutParms
        RelativeLayout.LayoutParams paramsTitle = 
                                 new RelativeLayout.LayoutParams(
                                     RelativeLayout.LayoutParams.WRAP_CONTENT,
                                     RelativeLayout.LayoutParams.WRAP_CONTENT);

        paramsTitle.addRule(RelativeLayout.ALIGN_LEFT, 
                                                  tvTeacherAndClasses.getId());

        RelativeLayout.LayoutParams paramsRoomId = 
                                 new RelativeLayout.LayoutParams(
                                     RelativeLayout.LayoutParams.WRAP_CONTENT,
                                     RelativeLayout.LayoutParams.WRAP_CONTENT);

        paramsRoomId.addRule(RelativeLayout.ALIGN_RIGHT, 
                                                  tvTeacherAndClasses.getId());

        RelativeLayout.LayoutParams paramsTeacherAndClasses = 
                                 new RelativeLayout.LayoutParams(
                                     RelativeLayout.LayoutParams.WRAP_CONTENT,
                                     RelativeLayout.LayoutParams.WRAP_CONTENT);

        paramsTeacherAndClasses.addRule(RelativeLayout.CENTER_HORIZONTAL);
        paramsTeacherAndClasses.addRule(RelativeLayout.BELOW, tvTitle.getId());

        // Add Views to this RelativeLayout
        addView(tvTitle, paramsTitle);
        addView(tvRoomId, paramsRoomId);
        addView(tvTeacherAndClasses, paramsTeacherAndClasses);

        // Set the background as LayerDrawable
        setBackgroundDrawable(buttonDrawable);          
    }
}

在這里,我們創建三個TextView,並設置他們的LayoutParams以獲得正確的對齊。

兩者的輸出相同,但我建議采用第二種方法:

在此輸入圖像描述

我發現實現這種行為的最簡單方法之一是利用android layout_weight屬性,如下所示:

<?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"
    android:layout_margin="30dp"
    android:background="@color/Orange"
    android:orientation="vertical"
    android:padding="20dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/top_left_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="SCHK" />

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" >
        </LinearLayout>

        <TextView
            android:id="@+id/top_right_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="G102" />
    </LinearLayout>

    <TextView
        android:id="@+id/bottom_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="VIM M4O3WI, M404WI, M402SJ" />

</LinearLayout>

通過這種方式,權重為1的LinearLayout將占用根據需要正確分離頂行上的兩個字符串所需的空間。

另外你為什么“將Button擴展到另一個班級”? 如果您這樣做純粹是為了獲得問題中顯示的圓角/橙色背景,您可以通過將頂級線性布局的背景設置為按鈕樣式的背景來獲得相同的效果。

在RelativeLayout中使用3個TextView。

title

    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"

對於roomId

    android:id="@+id/roomId"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"

teacher

    android:id="@+id/teacher"
    android:layout_below="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM