片段中的捆绑包值变为 null

Bundle value in fragment becomes null

提问人:navi1111 提问时间:9/21/2021 最后编辑:navi1111 更新时间:9/21/2021 访问量:75

问:

我的主要活动是将 Api 连接到回收器视图。在回收器查看项目单击时,我需要打开片段,然后使用 viewpager 在页面之间滑动。我的问题是当我单击recview中的任何项目时,它总是打开第一页。那是因为在创建片段时,我传递的位置变为 null。有人有任何解决方案吗?

public class ArticleFragment extends Fragment {
    private TextView tvTitle, tvDescription;
    private ImageView ivSlika;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private NewsList mNewsList=new NewsList();
    private int mPosition;

    public ArticleFragment() { }

    
    public static ArticleFragment newInstance(NewsList param1, int param2) {
        ArticleFragment fragment = new ArticleFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, param1);
        args.putInt(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mNewsList = (NewsList) getArguments().getSerializable(ARG_PARAM1);
            mPosition = getArguments().getInt(ARG_PARAM2);
            Log.d(TAG, "onCreate: "+ getArguments());
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_article, container, false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tvTitle=view.findViewById(R.id.tvNaslov);
        tvDescription=view.findViewById(R.id.tv_description);
        ivSlika=view.findViewById(R.id.iv_article);


        //setParameters((NewsList) getArguments().getSerializable(ARG_PARAM1), getArguments().getInt(ARG_PARAM2));
        setParameters(mNewsList, mPosition);
    }

    public void setParameters( NewsList nl, int position){
        //nl=new NewsList();
        //nl=articleActivity.getMyList();
        //List<News> newsList=nl.getNewsList();
        /*ArticleActivity articleActivity=(ArticleActivity) getActivity();
        position=articleActivity.getPosition();
        tvTitle.setText(articleActivity.getMyTitle(position));
        tvDescription.setText(articleActivity.getMyDescription(position));
        Picasso.get().load(articleActivity.getMyImage(position)).fit().into(ivSlika);*/
        tvTitle.setText(nl.getNewsList().get(position).getTitle());
        tvDescription.setText(nl.getNewsList().get(position).getDescription());
        Picasso.get().load(nl.getNewsList().get(position).getImageUrl()).fit().into(ivSlika);
    }
}
public class ArticleActivity extends AppCompatActivity {
    private int position;
    private NewsList newsList;
    private ViewPager viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        initViews();

        newsList= (NewsList)getIntent().getSerializableExtra("List");
        position=getIntent().getIntExtra("Position",5);

        //getSupportFragmentManager().beginTransaction().add(R.id.viewPager, ArticleFragment.newInstance(newsList, position)).commit();
        setUpPager();
    }
    public  String getMyTitle(int position){
        return newsList.getNewsList().get(position).getTitle();
    }
    public String getMyDescription(int position){
        return newsList.getNewsList().get(position).getDescription();
    }
    public String getMyImage(int position){
        return newsList.getNewsList().get(position).getImageUrl();
    }
    private void initViews(){
        viewPager= findViewById(R.id.viewPager);
    }
    private void setUpPager(){
        PagerAdapter pagerAdapter=new ScreenSlidePagerAdapter(getSupportFragmentManager(), newsList, position);

        viewPager.setAdapter(pagerAdapter);

    }
    public NewsList getMyList(){
        return newsList;
    }

    public int getPosition() {
        return position;
    }
}
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
    private NewsList newsList;
    private int mPosition;
    private static final int NUM_PAGES =10;
    public ScreenSlidePagerAdapter(FragmentManager fragmentManager, NewsList newsList, int position){
        super(fragmentManager);
        this.newsList=newsList;
        this.mPosition=position;
    }
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return ArticleFragment.newInstance(newsList, 0);
            case 1:
                return ArticleFragment.newInstance(newsList, 1);
            case 2:
                return ArticleFragment.newInstance(newsList, 2);
            case 3:
                return ArticleFragment.newInstance(newsList, 3);
            case 4:
                return ArticleFragment.newInstance(newsList, 4);
            case 5:
                return ArticleFragment.newInstance(newsList, 5);
            case 6:
                return ArticleFragment.newInstance(newsList, 6);
            case 7:
                return ArticleFragment.newInstance(newsList, 7);
            case 8:
                return ArticleFragment.newInstance(newsList, 8);
            case 9:
                return ArticleFragment.newInstance(newsList, 9);
            default:
                return ArticleFragment.newInstance(newsList, position);
        }
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        return super.getItemPosition(object);
    }


}
public class RecyclerAdapter extends RecyclerView.Adapter<NameViewHolder> {
    private List<News> dataList = new ArrayList<>();
    private NameClickListener clickListener;

    public RecyclerAdapter(NameClickListener clickListener) {
        this.clickListener = clickListener;
    }

    @NonNull
    @Override
    public NameViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View cellView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
        return new NameViewHolder(cellView, clickListener);
    }

    @Override
    public void onBindViewHolder(@NonNull NameViewHolder holder, int position) {
        holder.setName(dataList.get(position));
    }

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

    public void addData(List<News> data){
        this.dataList.clear();
        this.dataList.addAll(data);
        notifyDataSetChanged();
    }

    public void addNewCell(News news, int position){
        if(dataList.size() >= position){
            dataList.add(position,news);
            notifyItemInserted(position);
        }
    }


}
public class MainActivity extends AppCompatActivity implements  NameClickListener{
    private Call<Root> apiCall;
    private List<News> newsList;
    RecyclerAdapter adapter;
    RecyclerView recyclerView;
    NewsList ListofNews;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setUpApiCall();
        setUpRecycler();
    }
    private void setUpApiCall(){
        apiCall=NetworkUtils.getApiInterface().getNews();
        apiCall.enqueue(new Callback<Root>() {
            @Override
            public void onResponse(Call<Root> call, Response<Root> response) {
                if(response.isSuccessful() && response.body()!=null){
                    /*newsList=new ArrayList<News>();
                    for(int i=0;i<response.body().articles.size();i++){
                        newsList.add(response.body().articles.get(i));
                    }
                    setData(newsList);
                }*/
                    ListofNews=new NewsList();
                    ListofNews.setNewsList(response.body().articles);
                    setData(ListofNews.getNewsList());
            }}

            @Override
            public void onFailure(Call<Root> call, Throwable t) {
                AlertDialog alertDialog=new AlertDialog.Builder(MainActivity.this).setTitle("Error").setMessage("Something went wrong").setPositiveButton("yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
            }
        });
    }
    private void setUpRecycler(){
        recyclerView = (RecyclerView) findViewById(R.id.recView);
        // Create adapter passing in the sample user data
        adapter = new RecyclerAdapter(this);
        // Attach the adapter to the recyclerview to populate items
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);


    }
    private void setData(List<News> newsList){
        adapter.addData(newsList);
    }
    public void onNameClick(int position){
        Intent intent=new Intent(MainActivity.this, ArticleActivity.class);
        intent.putExtra("List", ListofNews);
        intent.putExtra("Position", position);
        startActivity(intent);
        


    }}
java android android-fragments android-viewpager 参数传递

评论

0赞 EpicPandaForce 9/21/2021
您没有为 RecyclerView 点击处理添加相关代码
1赞 Vucko 9/21/2021
哇,这句话伤了我的眼睛。难道你看不出你的默认情况基本上是你唯一需要的东西,从而消除了对整个开关的需求吗?switch
0赞 navi1111 9/21/2021
那个开关是绝望的尝试,我知道所有这些都是多余的,但我不得不尝试......
0赞 navi1111 9/21/2021
我在问题中添加了主要活动和 RecyclerAdapter,即使我认为它们与问题无关且与问题无关。
0赞 Community 9/28/2021
请修剪您的代码,以便更轻松地找到您的问题。请遵循以下准则,创建一个最小的可重现示例

答: 暂无答案