0

ImageViewその上に があるビューを作成しようとしてTextViewいます。

私はこれに関する良い例を見つけようとして立ち往生しているので、誰かが私が間違ったことや例を探す場所を教えてくれることを願っています. http://developer.android.com/guide/topics/ui/custom-components.html#compoundを見たことがありますが、実際には最小限の要件しか説明していません。

カスタム XML 属性を使用した複合コントロールの作成のようなものをいくつか見つけましたが、私の設定は少し異なります。

私のコードは以下の通りLinearLayoutです。レイアウトには何も表示されません。

ImageWithOverlay

public class ImageWithOverlay extends LinearLayout {
    ImageView image;
    TextView text;

    public ImageWithOverlay(Context context) {
        super(context);
        setupDisplay(context);
    }

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

    public ImageWithOverlay(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setupDisplay(context);
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        image.draw(canvas);
        text.draw(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {     
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);      
    }

    private void setupDisplay(Context context) {
        image = new ImageView(context);
        image.setImageResource(R.drawable.flowers);
        LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        image.setLayoutParams(lp);

        text = new TextView(context);
        text.setText("testing");
        lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        text.setLayoutParams(lp);
    }
}

status.xml

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

    <com.package.blah.ImageWithOverlay
        android:id="@+id/imageWithOverlay1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </com.package.blah.ImageWithOverlay>

</RelativeLayout>
4

1 に答える 1

1

LinearLayout の代わりに RelativeLayout を使用すると、画像の上にテキストを配置できます。

それらが表示されない理由は、addView を使用して追加されていないためです。したがって、それぞれの LayoutParams を設定した後でこれを呼び出します。

onDraw() 呼び出しを削除します。これは、明示的に要求しない限り、ViewGroups には使用されません。ビューが追加されると、自動的に描画されます。

于 2012-06-21T15:31:15.737 に答える