2015-06-14 34 views
3

我有一個圖像(match_parent),其中有兩個包含選項的矩形。我試圖在圖像頂部放置2個透明按鈕,以便點擊圖像產生動作。但是,我試圖支持多種屏幕尺寸,因此儘管我可以利用佈局邊距來排列特定分辨率智能手機按鈕中的矩形,但測試平板電腦完全失敗。將按鈕放在ImageView的頂部,用不同的屏幕尺寸延伸

我該如何放置與圖像一致的按鈕,以延伸以填充不同的屏幕尺寸。

很簡單佈局代碼現在使用DP不工作

<ImageView 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:id="@+id/banner" 
    android:background="@drawable/banner" 
    android:contentDescription="@string/banner" /> 

<Button 
    android:layout_width="120dp" 
    android:layout_height="90dp" 
    android:id="@+id/vs_computer" 
    android:layout_marginTop="135dp" 
    android:layout_marginLeft="135dp" 
    android:alpha="0" 
    android:clickable="true" 
    android:shadowColor="@android:color/transparent" 
    android:singleLine="true" /> 

<Button 
    android:layout_width="120dp" 
    android:layout_height="100dp" 
    android:id="@+id/multiplayer" 
    android:layout_marginTop="260dp" 
    android:layout_marginLeft="135dp" 
    android:alpha="0" 
    android:clickable="true" 
    android:shadowColor="@android:color/transparent" 
    android:singleLine="true" /> 

臨時圖像我使用: options http://ft.trillian.im/17107e0bd3d38d3147acf89ff7b55b6543455af6/6ypgZtJZUrzBt6UacYIWSqvJotOJc.jpg

+0

你可以發佈你的佈局代碼? –

+0

您可以使用ImageButton進行相同的工作。 – Shvet

+0

已發佈。我需要一個透明的按鈕,所以不應該問題哪個對不對? –

回答

0

你可以忽略來自這兩個按鈕圖形背景圖片(只留下一個空白區域)並將它們分隔開來。然後你可以把它們放在兩個ImageButton之間。這解決了必須完美排列絕對像素的直接問題。

要確定這些按鈕的大小和位置,請確定它們的左/右邊界和頂部/底部邊距是屏幕寬度和高度的百分比。然後,您可以創建自定義佈局(ViewGroup的子類)並實施onLayout(...)方法,通過將這些百分比應用於任何視圖大小,將這兩個按鈕定位在背景圖像的所需區域內。

在這個定製的ViewGroup可能是這個樣子:

public class Blah extends ViewGroup { 

    Button b1; 

    @Override 
    protected void onFinishInflate() { 
     super.onFinishInflate(); 
     b1 = (Button) findViewById(R.id.button_1); 
    } 

    @Override 
    protected void onLayout(boolean changed, int l, int t, int r, int b) { 
     // In dimensions XML: <fraction name="button_margin_horizontal">20%p</fraction> 
     int left = (int) getResources().getFraction(R.fraction.button_margin_horizontal, 0, getWidth()); 
     int right = getWidth() - left; 
     int buttonHeight = b1.getMeasuredHeight(); 
     b1.layout(left, 0, right, buttonHeight); 
    } 
}