【问题标题】:Specified child already has a parent error on inflated view指定的孩子在膨胀视图上已经有一个父错误
【发布时间】:2011-12-14 00:54:27
【问题描述】:

需要立即帮助!!以前的代码可以正常工作,但过了一会儿我注意到 rating doest work anymore and gives "the specified child already has a parent, call removeView() first..." on thealertDialog.show();` 行:

///// 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();

        }
    });

    //////

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

【问题讨论】:

  • 错误指向哪一行?
  • 它在问题中,alertDialog.show();给出错误

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


【解决方案1】:

您遇到的错误是您在将 View 添加到父级之后,将其添加到父级。

看看你的代码,看起来像,

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

custom_rate_dialog 添加到您layout_root。然后,当您执行 rateDialogBuilder.setView(layout); 时,您将其添加到另一个父级

如果您只是想扩大该布局以将其设置为ViewDialog,那么就这样做

layout = inflater.inflate(R.layout.custom_rate_dialog, null);

【讨论】:

  • 感谢这可能是更好的做法,但问题是我碰巧将 android:id="@+id/layout_root" 添加到主要活动的布局 xml 中......愚蠢的我花了 4小时通知
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
  • 1970-01-01
  • 2017-05-21
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多