我正在制作一个画廊应用程序并使用下面的代码动态添加图像按钮,这适用于我的一台设备,但在另一台设备上我得到了
java.lang.RuntimeException: Unable to start activity ComponentInfo{package/package.MainActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
E/AndroidRuntime( 3358): at android.view.ViewGroup.addViewInner(ViewGroup.java:3381)
E/AndroidRuntime( 3358): at android.view.ViewGroup.addView(ViewGroup.java:3252)
E/AndroidRuntime( 3358): at android.view.ViewGroup.addView(ViewGroup.java:3197)
E/AndroidRuntime( 3358): at android.view.ViewGroup.addView(ViewGroup.java:3173)
E/AndroidRuntime( 3358): at package.MainActivity.onCreate(MainActivity.java:74)
错误,但在其他设备上完全没有问题,并且运行良好。它运行的一个运行 4.1.2,而它崩溃的运行 4.1.1 可能是这样吗?该项目的最小和目标 sdk 为 16
setContentView(R.layout.activity_main);
// Hook up clicks on the thumbnail views.
imgHolder = (LinearLayout)findViewById(R.id.imgHolder);
for(int x = 0; x < files.length; x++)
{
Log.d("Conor",files[x].getAbsolutePath());
Drawable img = Drawable.createFromPath(files[x].getAbsolutePath());
imgs.add(img);
thumbs.add(new ImageButtons(this, files[x].getAbsolutePath(),x));
thumbs.get(x).setImageDrawable(img);
thumbs.get(x).setOnClickListener(onCl);
imgHolder.addView(thumbs.get(x));
}
// Retrieve and cache the system's default "short" animation time.
mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
ImageButtons 类thumbs
是一个 `ArrayList
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Xml;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
public class ImageButtons extends ImageButton{
Resources res = getResources();
public ImageButtons(Context context,String img,int id)
{
super(context);
XmlPullParser parser = res.getXml(R.layout.imagebuttons);
AttributeSet attributes = null;
int state = 0;
while(state != XmlPullParser.END_DOCUMENT)
{
try {
state = parser.next();
} catch (XmlPullParserException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
if (state == XmlPullParser.START_TAG) {
if (parser.getName().equals("ImageButton")) {
attributes = Xml.asAttributeSet(parser);
break;
}
}
}
setId(id);
setLayoutParams(new LayoutParams(context, attributes));
}
}
thumbs 是一个ArrayList<ImageButton>
,第 74 行指的是 `imgHolder.addView(thumbs.get(x));
我的问题再次是为什么这适用于某些设备而不适用于其他设备