Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamically add a xml defined layout at run-time outside of onCreate()
    text
    copied!<p>I have a custom ViewGroup (blue background) that when touched sometime during the app's life cycle, I want to add an arbitrary xml defined view layout (whitebox to be in foreground) to that custom view.</p> <p>Is there any way to do this outside of the activity's onCreate?</p> <p>whitebox.xml</p> <blockquote> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="100dp" android:layout_height="100dp" android:background="#FFFFFF" android:orientation="vertical" &gt; &lt;/LinearLayout&gt; </code></pre> </blockquote> <p>TestDynamicLayoutActivity.java</p> <pre><code>package net.lapasa.testdynamiclayout; import android.app.Activity; import android.os.Bundle; public class TestDynamicLayoutActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new MyCustomViewGroup(this)); } } </code></pre> <p>MyCustomViewGroup.java</p> <pre><code>package net.lapasa.testdynamiclayout; import java.lang.annotation.Target; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; public class MyCustomViewGroup extends ViewGroup { private Context context; public MyCustomViewGroup(Context context) { super(context); this.context = context; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { this.setBackgroundColor(Color.BLUE); } @Override public boolean onTouchEvent (MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { View whiteBoxView= LayoutInflater.from(context).inflate(R.layout.whitebox, this); ViewGroup targetParent = (ViewGroup) whiteBoxView.getParent(); targetParent.removeView(whiteBoxView); this.addView(whiteBoxView); } return true; } } </code></pre> <p>The block of code in the ACTION_DOWN doesn't do anything except present a black screen =( What is going on?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload