我有一個自定義的ViewGroup(藍色背景),當在應用程序的生命週期中某個時候觸摸時,我想添加一個任意的xml定義的視圖佈局在前景中)到該自定義視圖。在運行時動態添加一個xml定義的佈局onCreate()
有沒有辦法在活動的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;
}
}
的代碼在ACTION_DOWN該塊沒有做幹啥g除了呈現黑屏=(發生什麼事了?
您確保佈局 - 需要延長的ViewGroup - 你想添加到有一個ID。那麼當你想稍後添加某些東西時,可以用layoutInflater(即getSystemService(Context.layoutInflator);並手動添加你想要的。 – L7ColWinters 2012-01-18 18:23:28
這不是我在onTouchEvent()裏面已經做的事嗎? – 2012-01-18 18:25:33
對不起,我只是調試你的代碼,以確保layoutinflater設置正確。我從未使用.from – L7ColWinters 2012-01-18 18:45:56