9

我用一个按钮制作了一个应用程序,其中总共有 4 个文本,我想对齐前 2 个。一个位于底部文本的最左侧,另一个位于底部文本的右侧。

所以从这里:

前

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

对此:

之后(这就是我想要的)

setText(declare here a spannable);

我想我应该使用Spannable,我已经尝试了一些东西,Alignment.ALIGN_NORMALAlignment.ALIGN_OPPOSITE我认为应该首先计算底部文本的长度,然后进行对齐。(我在这里找到了一个很好的例子,但它在我的设置中不起作用)。

我希望有人能给我指出一个好的方向。

编辑:

我不能(我认为)使用RelativeLayout或者LinearLayout是我在不同的类(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 onLayout( ScheduleItemsLayout.java) 中执行此操作:

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

但这行不通。我不确定是否应该使用new RelativeLayout(this).

Spannable在这种情况下使用更好吗?

项目的源代码可以在这里下载(可以在 Eclipse 中导入)

4

3 回答 3

4

好吧,如果您不能从 a 转移Button到 a 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)andonMeasure(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 以获得正确的对齐方式。

两者的输出是相同的,但我会推荐第二种方法:

在此处输入图像描述

于 2013-12-07T04:30:04.260 回答
2

我发现实现这种行为的最简单方法之一是利用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”?如果您这样做纯粹是为了获得问题中显示的圆角/橙色背景,则可以通过将顶级线性布局的背景设置为按钮样式的背景来获得相同的效果。

于 2013-11-26T20:42:54.127 回答
1

在 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"
于 2013-11-25T12:25:40.013 回答