How to make Views overlap each other by a specified amount?

為{幸葍}努か 提交于 2020-01-07 05:49:05

问题


Let's say I'm trying to stack cards, and I want to put a queen on top of a king, but still have the top 20 or so pixels of the king be visible so you can tell it's under the queen. How do you do this?

I've defined a grid layout, with linear layout containers. Each container contains one imagebutton. The closest I can get it is the encroaching imagebutton shrinks under the occupying imagebutton.

Like so: http://i.stack.imgur.com/broaD.png

I would like to stack the imagebuttons, but still have the underlying imagebuttons still be clickable.

Edit: I was able to figure it out by extensive searching here and learning a lot about views. I'm now using

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 0, -60);
view.setLayoutParams(lp); 

回答1:


You can set android:layout_marginBottom="-50dp" for the top view so as to overlap the view below it. Here, 50dp is the amount by which you want to overlap the views.

Like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/imageButton1"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="#ff0000"
            android:layout_marginBottom="-50dp" />

        <ImageButton
            android:id="@+id/imageButton2"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="#00ff00"
            android:layout_marginBottom="-50dp" />

        <ImageButton
            android:id="@+id/imageButton3"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="#0000ff" />

    </LinearLayout>

</RelativeLayout>

Through code:

ImageButton imageButton1 = (ImageButton) findViewById(R.id.imageButton1);
        LinearLayout.LayoutParams layoutParams = (LayoutParams) imageButton1
                .getLayoutParams();
        layoutParams.setMargins(layoutParams.leftMargin,
                layoutParams.topMargin, layoutParams.rightMargin,
                (layoutParams.bottomMargin - 50));
        imageButton1.setLayoutParams(layoutParams);


来源:https://stackoverflow.com/questions/27744786/how-to-make-views-overlap-each-other-by-a-specified-amount

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!