从活动启动视图时出错

时间:2012-01-20 01:02:02

标签: android view

public class MAINActivity extends TabActivity {    
host.addTab(host.newTabSpec("Settings")
            .setIndicator("Settings", getResources().getDrawable(R.drawable.icon_user))
       .setContent(new Intent(this, TwoDScrollView.class)));
........
}

 public class TwoDScrollView extends Activity {

 private RelativeLayout container;
 private int currentX;
 private int currentY;

 protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.design);

container = (RelativeLayout)findViewById(R.id.container);

int top = 0;
int left = 0;

ImageView image1 = (ImageView)findViewById(R.id.imageView1);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(left, top, 0, 0);               
container.addView(image1, layoutParams);

ImageView image2 = (ImageView)findViewById(R.id.imageView2);
left+= 100;
layoutParams.setMargins(left, top, 0, 0);               
container.addView(image2, layoutParams);

ImageView image3 = (ImageView)findViewById(R.id.imageView3);
left= 0;
top+= 100;

layoutParams.setMargins(left, top, 0, 0);               
container.addView(image3, layoutParams);

ImageView image4 =  (ImageView)findViewById(R.id.imageView4);
left+= 100;     

layoutParams.setMargins(left, top, 0, 0);               
container.addView(image4, layoutParams);
}     

  @Override 
  public boolean onTouchEvent(MotionEvent event) {
  switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN: {
        currentX = (int) event.getRawX();
        currentY = (int) event.getRawY();
        break;
    }

    case MotionEvent.ACTION_MOVE: {
        int x2 = (int) event.getRawX();
        int y2 = (int) event.getRawY();
        container.scrollBy(currentX - x2 , currentY - y2);
        currentX = x2;
        currentY = y2;
        break;
    }   
    case MotionEvent.ACTION_UP: {
        break;
    }
}
  return true; 
}

}

当我尝试将TwoDScrollView类添加到tabbars时,我收到IllegalStateException错误。指定的子项已有父项。您必须首先删除孩子父母的View()。这些意味着什么?

1 个答案:

答案 0 :(得分:1)

发生的事情是你通过调用setContentView来隐式地夸大你的布局,这会创建一堆视图,包括显然在RelativeLayout中的四个ImageView。然后你正在findViewById找到这些ImageViews和RelativeLayout,并在以编程方式更改它们的边距后,将它们添加回已经包含它们的相同布局。这就是你得到例外的原因。那些ImageViews已经有了一个父级(RelativeLayout),并且你试图给它们一个新的父级(即使它是相同的RelativeLayout)而没有先从父级中删除它们。在这种情况下,您根本不需要致电addView