草庐IT

android - 错误 : The specified child already has a parent. 您必须先在 child 的 parent 上调用 removeView()

coder 2023-12-27 原文

不明白哪里出了问题,第二天脑袋都碎了...

我想将 TabLayout 与 2 个选项卡一起使用,其中第一个 RecyclerView 与 ArtistModel, 但是当我用 RecyclerView 给 Fragment 充气时,会出现这个错误。

这是我的代码。 fragment

package com.shagi.yandex.lookart.fragment;    

import android.app.Fragment;
import android.os.Bundle;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.shagi.yandex.lookart.JsonHelper;
import com.shagi.yandex.lookart.MainActivity;
import com.shagi.yandex.lookart.R;
import com.shagi.yandex.lookart.adaptor.ArtistsAdapter;
import com.shagi.yandex.lookart.pojo.Artist;

import java.util.List;
import java.util.concurrent.ExecutionException;    

/**
 * A simple {@link Fragment} subclass.
 */
public class ArtistsFragment extends Fragment {

    private RecyclerView rvArtists;
    private RecyclerView.LayoutManager layoutManager;

    private ArtistsAdapter adapter;

    private List<Artist> artists;

    public MainActivity activity;

    public ArtistsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity() != null) {
            activity = (MainActivity) getActivity();
        }
        loadArtistModels();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_artists, container, false);

        rvArtists = (RecyclerView) rootView.findViewById(R.id.rvArtists);

        layoutManager = new LinearLayoutManager(getActivity());

        rvArtists.setLayoutManager(layoutManager);
        artists = loadArtistModels();

        adapter = new ArtistsAdapter(artists);

        rvArtists.setAdapter(adapter);

        // Inflate the layout for this fragment
        return rootView;
    }

    private List<Artist> loadArtistModels() {
        try {
            return new JsonHelper().execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}

适配器

package com.shagi.yandex.lookart.adaptor;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.shagi.yandex.lookart.DownloadImageTask;
import com.shagi.yandex.lookart.R;
import com.shagi.yandex.lookart.pojo.Artist;

import java.util.List;

/**
 * Created by Shagi on 06.04.2016.
 */
public class ArtistsAdapter extends RecyclerView.Adapter<ArtistsAdapter.ViewHolder> {

    List<Artist> artists;

    public ArtistsAdapter(List<Artist> artists) {
        this.artists = artists;
    }

    @Override
    public ArtistsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.model_artist, parent, false);

        ImageView smallCover = (ImageView) v.findViewById(R.id.small_cover);
        TextView name = (TextView) v.findViewById(R.id.tvArtistName);
        TextView style = (TextView) v.findViewById(R.id.tvStyle);
        TextView albums = (TextView) v.findViewById(R.id.tvAlbums);

        return new ViewHolder(parent, smallCover, name, style, albums);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        Artist artist = artists.get(position);
        new DownloadImageTask(holder.smallCover).execute(artist.getCover().getSmall());
        holder.artistName.setText(artist.getName());
        String style = "";
        for (String string : artist.getGenres()) {
            style += string + " ";
        }
        holder.artistStyle.setText(style);
        String albums = "альбомов " + artist.getAlbums() + ", треков " + artist.getTracks();
        holder.artistAlbums.setText(albums);
    }

    @Override
    public int getItemCount() {
        return artists.size();
    }    

    public static class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public ImageView smallCover;
        public TextView artistName;
        public TextView artistStyle;
        public TextView artistAlbums;

        public ViewHolder(View v, ImageView img, TextView artistName, TextView artistStyle, TextView artistAlbums) {
            super(v);
            smallCover = img;
            this.artistName = artistName;
            this.artistStyle = artistStyle;
            this.artistAlbums = artistAlbums;
        }
    }
}

和MainActivity

package com.shagi.yandex.lookart;

import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;    
import android.view.Menu;
import android.view.MenuItem;    
import com.shagi.yandex.lookart.adaptor.TabAdaptor;
import com.shagi.yandex.lookart.fragment.SplashFragment;

public class MainActivity extends AppCompatActivity {

    FragmentManager fragmentManager;
    PreferenceHelper preferenceHelper;
    TabAdaptor tabAdaptor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PreferenceHelper.getInstance().init(getApplicationContext());
        preferenceHelper = PreferenceHelper.getInstance();
        fragmentManager = getFragmentManager();


        //runSplash();
        setUI();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem splashItem = menu.findItem(R.id.action_splash);
        splashItem.setChecked(preferenceHelper.getBoolean(PreferenceHelper.SPLASH_IS_INVISIBLE));
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_splash) {
            item.setChecked(!item.isChecked());
            preferenceHelper.putBoolean(PreferenceHelper.SPLASH_IS_INVISIBLE, item.isChecked());
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void runSplash() {
        if (!preferenceHelper.getBoolean(PreferenceHelper.SPLASH_IS_INVISIBLE)) {
            SplashFragment splashFragment = new SplashFragment();
            fragmentManager.beginTransaction()
                    .replace(R.id.content_frame, splashFragment).addToBackStack(null).commit();
        }
    }

    public void setUI() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            toolbar.setTitleTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white));
            setSupportActionBar(toolbar);
        }

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText(R.string.artists_tab));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.selected_artist_tab));

        final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
        tabAdaptor = new TabAdaptor(fragmentManager, 2);

        viewPager.setAdapter(tabAdaptor);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });    
    }    
}

堆栈跟踪按要求

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
    at android.view.ViewGroup.addViewInner(ViewGroup.java:4066)
    at android.view.ViewGroup.addView(ViewGroup.java:3916)
    at android.view.ViewGroup.addView(ViewGroup.java:3857)
    at android.support.v7.widget.RecyclerView$5.addView(RecyclerView.java:585)
    at android.support.v7.widget.ChildHelper.addView(ChildHelper.java:107)
    at android.support.v7.widget.RecyclerView$LayoutManager.addViewInt(RecyclerView.java:6249)
    at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:6207)
    at android.support.v7.widget.RecyclerView$LayoutManager.addView(RecyclerView.java:6195)
    at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1384)
    at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1333)
    at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:562)
    at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2900)
    at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3071)
    at android.view.View.layout(View.java:16001)
    at android.view.ViewGroup.layout(ViewGroup.java:5181)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:639)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:574)
    at android.view.View.layout(View.java:16001)
    at android.view.ViewGroup.layout(ViewGroup.java:5181)
    at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1627)
    at android.view.View.layout(View.java:16001)
    at android.view.ViewGroup.layout(ViewGroup.java:5181)
    at android.support.design.widget.CoordinatorLayout.layoutChild(CoordinatorLayout.java:1037)
    at android.support.design.widget.CoordinatorLayout.onLayoutChild(CoordinatorLayout.java:747)
    at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42)
    at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1133)
    at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:760)
    at android.view.View.layout(View.java:16001)
    at android.view.ViewGroup.layout(ViewGroup.java:5181)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:639)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:574)
    at android.view.View.layout(View.java:16001)
    at android.view.ViewGroup.layout(ViewGroup.java:5181)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:639)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:574)
    at android.view.View.layout(View.java:16001)
    at android.view.ViewGroup.layout(ViewGroup.java:5181)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1959)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1813)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1722)
    at android.view.View.layout(View.java:16001)
    at android.view.ViewGroup.layout(ViewGroup.java:5181)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:639)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:574)
    at android.view.View.layout(View.java:16001)
    at android.view.ViewGroup.layout(ViewGroup.java:5181)
    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1959)
    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1813)
    at android.widget.LinearLayout.onLayout(LinearLayout.java:1722)
    at android.view.View.layout(View.java:16001)
    at android.view.ViewGroup.layout(ViewGroup.java:5181)
    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:639)
    at android.widget.FrameLayout.onLayout(FrameLayout.java:574)
    at android.view.View.layout(View.java:16001)
    at android.view.ViewGroup.layout(ViewGroup.java:5181)
    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2467)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2164)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1282)
    at android.

如有不明白之处,请追问。看来我自己解决不了。

最佳答案

您应该在 onCreateView() 方法中将 View v 而不是 parent 传递给 ViewHolder。此外,最好使用 initialise ViewsViewholder 中,而不是在 onCreateView()

View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.model_artist, parent, false);

更新这一行

return new ViewHolder(parent, smallCover, name, style, albums);

return new ViewHolder(v, smallCover, name, style, albums);

关于android - 错误 : The specified child already has a parent. 您必须先在 child 的 parent 上调用 removeView(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36485135/

有关android - 错误 : The specified child already has a parent. 您必须先在 child 的 parent 上调用 removeView()的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  3. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  4. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  5. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  6. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  7. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  8. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  9. arrays - 这是 Ruby 中 Array.fill 方法的错误吗? - 2

    这个问题在这里已经有了答案:Arraysmisbehaving(1个回答)关闭6年前。是否应该这样,即我误解了,还是错误?a=Array.new(3,Array.new(3))a[1].fill('g')=>[["g","g","g"],["g","g","g"],["g","g","g"]]它不应该导致:=>[[nil,nil,nil],["g","g","g"],[nil,nil,nil]]

  10. ruby-on-rails - Ruby on Rails 计数器缓存错误 - 2

    尝试在我的RoR应用程序中实现计数器缓存列时出现错误Unknownkey(s):counter_cache。我在这个问题中实现了模型关联:Modelassociationquestion这是我的迁移:classAddVideoVotesCountToVideos0Video.reset_column_informationVideo.find(:all).eachdo|p|p.update_attributes:videos_votes_count,p.video_votes.lengthendenddefself.downremove_column:videos,:video_vot

随机推荐