如何以编程方式叠加按钮?

问题描述:

我想要做的是在运行时在屏幕中间放置一个按钮,作为顶层,覆盖它下面的任何东西。 (这不是很大,所以它不会完全覆盖屏幕,只是发生在屏幕下方)如何以编程方式叠加按钮?

我看过创建自定义对话框,但是阻止所有其他用户输入。我希望这个新按钮下面的所有视图都能正常工作并对用户作出响应,但我只想添加(以后再删除)该按钮。

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

感谢

使用FrameLayout,与按钮,因为它的第二个孩子。如果您不希望它可见,请将其设置为“已结束”。

+0

完美运作。谢谢。你知道一种方法来实现这一点,而不必改变活动的XML布局?我的应用程序中的所有活动都需要这样做,并且将所有活动的布局封装到一个框架布局中以便在需要时使这个弹出按钮出现在它们上面似乎效率低下。 – cottonBallPaws 2010-10-21 21:09:51

+2

您可以创建Activity的所有活动的子类,并在其中有一些逻辑以编程方式将特定布局插入到FrameLayout中。 – 2010-10-21 21:21:24

我不得不以编程方式在任何可见活动之上覆盖一个简单的布局。正常活动布局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实例(private Handler messageHandler)的成员,我放置所有计划任务。我使用的Android 4.1设备低于我不知道会发生什么情况。