9

合計 4 つのテキストがあるボタンを使用してアプリケーションを作成し、最初の 2 つを揃えたいと考えています。

だからこれから:

前

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

これに:

After (これが欲しい)

setText(declare here a spannable);

私はSpannableAlignment.ALIGN_NORMALで作業する必要があると思います.andでいくつか試しましたAlignment.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 onLayoutScheduleItemsLayout.java)でこれをやろうとしました:

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

しかし、それはうまくいきません。を使用する必要があるかどうかわかりませんnew RelativeLayout(this)

Spannableこの場合は使った方が良いですか?

プロジェクトのソースはここからダウンロードできます(Eclipse にインポートできます)。

4

3 に答える 3

4

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)メソッドをオーバーライドしている理由がわかりません。

言うまでもなく、これは複雑なコード スニペットの 1 つです。何が起こっているかというと、目的の位置合わせを得るためにtitleとの間にどのくらいのスペースを配置する必要があるかを測定しているということです。roomIdコードは単純なので (非常に価値がありますが)、コメントは含まれていません。

一方、 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);          
    }
}

ここでは、3 つの TextView を作成し、適切な配置になるように LayoutParams を設定します。

出力はどちらも同じですが、2 番目のアプローチをお勧めします。

ここに画像の説明を入力

于 2013-12-07T04:30:04.260 に答える
2

この種の動作を実現するために私が見つけた最も簡単な方法の 1 つは、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 は、必要に応じて最上行の 2 つの文字列を適切に分離するために必要なスペースを占有します。

また、なぜ「別のクラスでボタンを拡張する」のですか? 質問に表示される丸みを帯びた角/オレンジ色の背景を取得するためだけにこれを行っている場合は、トップレベルの線形レイアウトの背景をボタンのスタイルの背景に設定することで、これと同じ効果を得ることができます。

于 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 に答える