RecyclerView Activity 到片段

RecyclerView Activity to Fragment

我正在关注此处找到的关于 recyclerview 的教程 http://javatechig.com/android/android-recyclerview-example

我已经修改它以满足我的需要,除了一件事,MainActivity在这个,我需要在一个片段中,而不是Activity。这是我现在的片段:

    public class FeedZooperListFragment extends Fragment {
    private static final String TAG = "RecyclerViewExample";
    private List<FeedZ> feedItemList = new ArrayList<FeedZ>();
//added static might remove
    private static RecyclerView mRecyclerView;
    private static MyRecyclerAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /* Allow activity to show indeterminate progress-bar */
        getActivity().requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.fragment_recyclerview);

        /* Initialize recycler view */
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));

        /*Downloading data from below url*/
        final String url = "http://www.thisismyurl.com";
        new AsyncHttpTask().execute(url);
    }

    public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

     /*   @Override
        protected void onPreExecute() {
            setProgressBarIndeterminateVisibility(true);
        }*/

        @Override
        protected Integer doInBackground(String... params) {
            InputStream inputStream = null;
            Integer result = 0;
            HttpURLConnection urlConnection = null;

            try {
                /* forming th java.net.URL object */
                URL url = new URL(params[0]);
                urlConnection = (HttpURLConnection) url.openConnection();

                /* for Get request */
                urlConnection.setRequestMethod("GET");
                int statusCode = urlConnection.getResponseCode();

                /* 200 represents HTTP OK */
                if (statusCode ==  200) {
                    BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                        response.append(line);
                    }

                    parseResult(response.toString());
                    result = 1; // Successful
                }else{
                    result = 0; //"Failed to fetch data!";
                }

            } catch (Exception e) {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return result; //"Failed to fetch data!";
        }

        @Override
        protected void onPostExecute(Integer result) {
           // setProgressBarIndeterminateVisibility(false);
            /* Download complete. Lets update UI */
            if (result == 1) {
                adapter = new MyRecyclerAdapter(FeedZListFragment.this, feedItemList);
                mRecyclerView.setAdapter(adapter);
            } else {
                Log.e(TAG, "Failed to fetch data!");
            }
        }
    }

    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);
            JSONArray products = response.optJSONArray("products");

            /*Initialize array if null*/
            if (null == feedItemList) {
                feedItemList = new ArrayList<FeedZ>();
            }

            for (int i = 0; i < products.length(); i++) {
                JSONObject product = products.optJSONObject(i);

                FeedZ item = new FeedZ();
                item.setTitle(product.optString("title"));
                item.setImage_url(product.optString("image_url"));
                item.setPackage_url(product.optString("package_url"));
                item.setIds(product.optString("ids"));
                feedItemList.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

我的问题是无法解决 setContentView(R.layout.fragment_recyclerview)

的方法 setContentView(int)

以及无法解析

的 findviewByID 方法
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));

感谢任何帮助。

setContentView()仅在Activity中。您需要在将覆盖的 onCreateView() 方法中扩充布局。

public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recyclerview,
        container, false);
} 

有关详细信息,请参阅此处 - super.onCreateView in Fragments

对于 findViewById 你可以做以下两件事之一 -

你可以写getActivity().findViewById()

或者在 onCreateView 方法中你可以说:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
       View view =  inflater.inflate(R.layout.fragment_recyclerview,
            container, false)

      view.findViewById....

    return;
    }