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.
Is there any way to do this outside of the activity’s onCreate?
whitebox.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="100dp" android:layout_height="100dp" android:background="#FFFFFF" android:orientation="vertical" > </LinearLayout>
TestDynamicLayoutActivity.java
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));
}
}
MyCustomViewGroup.java
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;
}
}
The block of code in the ACTION_DOWN doesn’t do anything except present a black screen =( What is going on?
Did I get that right – you just want to have some blue view containing a white view that shows up when the blue view is clicked?
Then it would be better not to implement your own
ViewGroupbut using one of the existing ones likeFrameLayout. Set the layout’s background to blue. Add a childViewwith it’s background set to white and it’s visibility set toView.INVISIBLEorView.GONE.Add a click handler to the
ViewGroupthat sets the visibility of your whiteViewtoView.VISIBLE.You could do it like this:
main.xml:
MyActivity.java: