我是繼承ImageButton以便在其上繪製線條並試圖找出實際按鈕座標在我的GridView中的位置。我使用onGlobalLayout來設置頂部,底部,右側和左側,但這些似乎是網格中的實際「方形」,而不是實際的按鈕(請參閱圖像)。在myImageButton.onDraw()中使用從myImageButton.onGlobalLayout()收集的座標來繪製紫色線條。我認爲這些將是按鈕,但他們似乎是從別的東西。不知道是什麼。我希望紫色線條與按鈕的輪廓相匹配,以便我繪製的線條出現在按鈕上,而不僅僅是浮動在某處的LinearLayout中。淺藍色是持有文本視圖(用於數字)和myImageButton的垂直LinearLayout的背景顏色。任何方式來獲得實際的按鈕大小?如何在Android GridView中獲取ImageButton大小?
XML佈局:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lay_cellframe"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="fill_vertical|fill_horizontal"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_cell"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:gravity="center"
android:text="TextView"
android:textSize="10sp" />
<com.example.icaltest2.myImageButton
android:id="@+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_margin="0dp"
android:adjustViewBounds="false"
android:background="@android:drawable/btn_default"
android:scaleType="fitXY"
android:src="@android:color/transparent" />
</LinearLayout>
</FrameLayout>
myImageButton.java
public myImageButton (Context context, AttributeSet attrs)
{
super (context, attrs);
mBounds = new Rect();
ViewTreeObserver vto = this.getViewTreeObserver();
vto.addOnGlobalLayoutListener (ogl);
Log.d (TAG, "myImageButton");
}
...
OnGlobalLayoutListener ogl = new OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
Rect b = getDrawable().getBounds();
mBtnTop = b.centerY() - (b.height()/2);
mBtnBot = b.centerY() + (b.height()/2);
mBtnLeft = b.centerX() - (b.width()/2);
mBtnRight = b.centerX() + (b.width()/2);
}
};
...
@Override
protected void onDraw (Canvas canvas)
{
super.onDraw (canvas);
Paint p = new Paint();
p.setStyle (Paint.Style.STROKE);
p.setStrokeWidth (1);
p.setColor (Color.MAGENTA);
canvas.drawCircle (mBtnLeft, mBtnTop, 2, p);
canvas.drawCircle (mBtnLeft, mBtnBot, 2, p);
canvas.drawCircle (mBtnRight, mBtnTop, 2, p);
canvas.drawCircle (mBtnRight, mBtnBot, 2, p);
canvas.drawRect (mBtnLeft, mBtnTop, mBtnRight, mBtnBot, p);
}
更新:與jsmith的建議添加的圖像
Rect r = canvas.getClipBounds(); //<- not sure about this
int w = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
int h = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();
int left = r.centerX() - (w/2);
int right = r.centerX() + (w/2);
int top = r.centerY() - (h/2);
int bot = r.centerY() + (h/2);
p.setColor (Color.GREEN);
canvas.drawRect (left, top, right, bot, p);
嗯..似乎與紫色矩形的結果大致相同(上圖中新上傳的圖片)。 – wufoo
你能描述一下你想在哪個方向繪製這個盒子嗎? – jsmith
基本上只是一個邊界框,它表示無論屏幕dpi(縮放等)如何,都需要使用平板電腦和手機才能使用按鈕小部件。我寧願不必爲9補丁填充做任何'欺騙'。看起來getClipBounds()返回正確的數字,但由於有一個透明的2,3,5像素邊框,它不完全在按鈕上。也許我應該嘗試添加一個透明的圖像到Android將正確放置在窗口小部件中的按鈕?然後使用透明圖像座標?嗯.. – wufoo