简体   繁体   中英

No view found for id for fragment when replacing from Adapter

I'm trying to replace my current fragment with another one. I'm doing this from the Adapter, since I wanna do it when clicking on a Card. This is my code into the adapter:

itemView.setOnClickListener(v -> {
            if (mMovieCategory.getImageUrl() != null) {
                try {
                    //TODO
                    FragmentTransaction ft = ((AppCompatActivity) v.getContext()).getSupportFragmentManager()
                            .beginTransaction();
                    ft.replace(R.id.movie_container, new Fragment_Movie());
                    ft.addToBackStack(null);
                    ft.commit();
                } catch (Exception e) {
                    Log.e(TAG, "onClick: Image url is not correct");
                }
            }
        });

In the replace function I used the id assigned to the fragment I want to invoke. This is the XML:

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/movie_container"
        tools:context=".MainActivity" >

        <ListView
            android:id="@+id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:divider="@color/list_divider"
            android:dividerHeight="1dp"
            android:listSelector="@drawable/list_row_selector"/>
    </RelativeLayout>

This is the fragment I want to invoke:

package com.lab.movietime;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;

import static com.android.volley.VolleyLog.TAG;

public class Fragment_Movie extends Fragment {

    private static final String url = "https://api.androidhive.info/json/movies.json";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

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

    public static Fragment_Movie newInstance() {
        Fragment_Movie fragment = new Fragment_Movie();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_movie, container, false);
        listView = (ListView) view.findViewById(R.id.list);
        adapter = new CustomListAdapter(getActivity(), movieList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(getContext());
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                movie.setTitle(obj.getString("title"));
                                movie.setThumbnailUrl(obj.getString("image"));
                                movie.setRating(((Number) obj.get("rating"))
                                        .doubleValue());
                                movie.setYear(obj.getInt("releaseYear"));

                                // Genre is json array
                                JSONArray genreArry = obj.getJSONArray("genre");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < genreArry.length(); j++) {
                                    genre.add((String) genreArry.get(j));
                                }
                                movie.setGenre(genre);

                                // adding movie to movies array
                                movieList.add(movie);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });
        AppController.getInstance().addToRequestQueue(movieReq);
        return view;
    }
}

The error I get is:

No view found for id 0x7f0900ab (com.lab.movietime:id/movie_container) for fragment Fragment_Movie{1f8531a}

Why? Is the id: container_movie incorrect?

Assuming that movie_container is within the Fragment : You need to pass the ID of the container view in the Activity 's layout, not the ID of the Fragment 's view.

This will be the ID of the View containing the Fragment , as opposed to the View contained within the Fragment .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM