如何以编程方式覆盖按钮?

时间:2010-10-21 01:29:10

标签: android view dialog overlay

我想要完成的是,在运行时,在屏幕中间放置一个按钮,作为最顶层,覆盖其下方的任何内容。 (它不大,所以它不会完全覆盖屏幕,只是在它下面发生的任何事情。)

我查看了创建自定义对话框,但是阻止了所有其他用户输入。我希望这个新按钮下方的所有视图都能正常运行并响应用户,但我只是想在所有内容上添加(以后删除)按钮。

希望这是有道理的。我只是想知道什么是最好的方法来研究?

2 个答案:

答案 0 :(得分:2)

使用FrameLayout,按钮作为第二个孩子。当你不希望它可见时,将它设置为GONE。

答案 1 :(得分:1)

我必须在任何可见活动的基础上以编程方式覆盖一个简单的布局。正常活动布局xmls对叠加层一无所知。布局有一个textview组件,但可以有你认为合适的任何结构。这是我的叠加布局。

<强> RES /布局/ identity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/identitylayout"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:layout_centerInParent="true" >

<TextView 
    android:id="@+id/identityview"
    android:padding="5dp"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:textColor="#FFFFFF" android:background="#FF6600"
    android:textSize="30dp"            
/>

</RelativeLayout>

在从屏幕删除超时后,覆盖显示在现有内容的顶部。应用程序调用此函数来显示叠加。

private void showIdentity(String tag, long duration) {
    // default text with ${xx} placeholder variables
    String desc = getString(R.string.identity);
    desc = desc.replace("${id}", reqId!=null ? reqId : "RequestId not found" );
    desc = desc.replace("${tag}", tag!=null ? tag : "" );
    desc = desc.trim();

    // get parent and overlay layouts, use inflator to parse
    // layout.xml to view component. Reuse existing instance if one is found.
    ViewGroup parent = (ViewGroup)findViewById(R.id.mainlayout);
    View identity = findViewById(R.id.identitylayout);
    if (identity==null) {
        LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        identity = inflater.inflate(R.layout.identity, parent, false);
        parent.addView(identity);
    }

    TextView text = (TextView)identity.findViewById(R.id.identityview);
    text.setText(desc);
    identity.bringToFront();

    // use timer to hide after timeout, make sure there's only
    // one instance in a message queue.
    Runnable identityTask = new Runnable(){
        @Override public void run() {
            View identity = findViewById(R.id.identitylayout);
            if (identity!=null)
                ((ViewGroup)identity.getParent()).removeView(identity);
        }
    };
    messageHandler.removeCallbacksAndMessages("identitytask");
    messageHandler.postAtTime(identityTask, "identitytask", SystemClock.uptimeMillis()+duration);
}

计时器messageHandler是主Activity实例(私有Handler messageHandler)的成员,我在其中放置了所有计划任务。我使用的Android 4.1设备低于我不知道会发生什么。

相关问题