【问题标题】:Instantiating multiple buttons from a for loop throwing error从 for 循环抛出错误实例化多个按钮
【发布时间】:2014-07-26 13:51:54
【问题描述】:

我试图从 for 循环中实例化多个按钮,但我收到以下错误:

The specified child already has a parent. You must call removeView() on the child's parent first.

我尝试删除视图,但只有 1 个按钮实例化。我已经查看了具有相同错误的其他解决方案,但它们对我不起作用..任何建议都会很棒。谢谢..

这是代码

 public void onClick(View v) {
            speakOut("setting devices");
            DeviceHelper db = new DeviceHelper(getActivity());
            List<String> devs = db.getAllDevices();
            int id = getResources().getIdentifier("lock", "drawable",getActivity().getPackageName());
            final ImageView imageView = new ImageView(getActivity());

            int amm = devs.size();
            for (int i = 0; i < amm; i++) {
                String nas2 = devs.get(i);
                 //layout.removeView(imageView);
                Log.v("NAS", " db info for devices " + nas2);
                imageView.setTag(ii);
                imageView.setX(t + 100);
                LinearLayout.LayoutParams vp = new LinearLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT);
                imageView.setLayoutParams(vp);
                imageView.setImageResource(id);

                layout.addView(imageView);

            }

【问题讨论】:

    标签: java android button instantiation


    【解决方案1】:

    将此行放在for循环中:

    ImageView imageView = new ImageView(getActivity());
    

    【讨论】:

    • 如果它解决了您的问题,请在回复中签名:D 它真的很有帮助。谢谢
    【解决方案2】:

    错误说您正在添加一个已经在屏幕上的子视图并定义了它的父视图,所以首先删除它。所以简而言之,您永远不应该将相同的视图对象添加到它的父视图。

    由于您的 imageView 在循环之外声明,并且您不断将该视图添加到限制您这样做的布局父级。

    所以你的imageview 声明应该在循环内,每次都会创建新的imageView

    编辑您的评论

    你可以这样实现监听器

    public class YouClass extends Activity implements OnClickListener {
    //Your Code
        @Override
        public void onClick(View arg0) {
        //Applicable to all buttons which has setOnClickListener(this)
        //Get Data from View arg0 to determine which button has been clicked
        }
    }
    

    并在循环中使用button.setOnClickListener(this);。 :)

    【讨论】:

    • 感谢您的回复。我得到了它(新的onClickListener)..感谢您的信息:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 2014-04-12
    • 2013-12-18
    • 2014-06-06
    • 1970-01-01
    相关资源
    最近更新 更多