指定的子项已在膨胀的视图中出现父错误

时间:2011-12-14 00:54:28

标签: android android-layout view dialog android-inflate

需要立即帮助!!以前的代码工作正常,但过了一段时间后我注意到评级没有t work anymore and gives "the specified child already has a parent, call removeView() first..." on the alertDialog.show();`line:

///// Rating bar initialising
    Context mContext = ShowActivity.this;
    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    layout = inflater.inflate(R.layout.custom_rate_dialog, (ViewGroup) findViewById(R.id.layout_root));

    final RatingBar rating_indicator = (RatingBar)findViewById(R.id.rating_bar_cafe_indicator);
    final float current_rating = (float)mDbHelper.getInt(mRowId, type, RATE_COLUMN);
    rating_indicator.setRating(current_rating);


    rateDialogBuilder = new AlertDialog.Builder(ShowActivity.this);
    rateDialogBuilder.setView(layout);
    rateDialogBuilder.setCancelable(false);
    rateDialogBuilder.setIcon(R.drawable.rate_star_med_on);
    rateDialogBuilder.setTitle("RATE IT!");
    rateDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            rating_indicator.setRating(mDbHelper.getInt(mRowId, type, RATE_COLUMN));
            ((ViewGroup)layout.getParent()).removeView(layout);
            dialog.cancel();
        }
    });

    ratingText = (TextView) layout.findViewById(R.id.rate_text);
    rating = (RatingBar) layout.findViewById(R.id.rating_bar_cafe);
    rating.setRating(current_rating);
    rating.setStepSize(1);
    rating.setOnRatingBarChangeListener(ShowActivity.this);

    if ((int)current_rating != 0) ratingText.setText("Your rating: " + (int)current_rating); 

    Button rateButton = (Button) findViewById(R.id.button_rate); 
    rateButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

            AlertDialog alertDialog = rateDialogBuilder.create(); 
            alertDialog.show();

        }
    });

    //////

奇怪的是,如果我在removeAllViews()之前拨打removeView()alertDialog.show();,它就不会崩溃但会打开混乱对话,我可以看到评级和当前活动或smth。此问题可能是代码中的其他地方,因为这曾经工作正常,任何想法我应该寻找什么或如何更改它使其工作?

1 个答案:

答案 0 :(得分:9)

您收到的错误是,在父母已添加到父级后,您正在向父级添加View

查看代码,看起来像,

layout = inflater.inflate(R.layout.custom_rate_dialog, (ViewGroup) findViewById(R.id.layout_root));

将custom_rate_dialog添加到layout_root。然后,当您执行rateDialogBuilder.setView(layout);

时,您将其添加到另一个父级

如果您只想尝试对该布局进行充气,将其设置为View的{​​{1}},那么只需执行

Dialog