如何将此活动转换为片段?

时间:2014-11-10 16:17:18

标签: android android-fragments navigation-drawer

我有一个Activity,它解析json并显示为list view。现在我想将这个Activity与导航抽屉一起使用。

所以我想将此Activity转换为Fragment。我尝试了自己并使用this one转换了活动的某些部分。

我将所有流程都移到了On Activity Created。但它显示了许多错误,所以我删除了它。

我不知道我在哪里错了。所以请指导我。 在此先感谢。

活动

public class FeedListActivity extends Activity {

    private Toolbar mToolbar;
    private NavigationDrawerFragment mNavigationDrawerFragment;
    private static final String TAG = "FeedListActivity";

    private ListView NewsView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;
    ProgressBarCircularIndetermininate progressBar;
    private String URL_FEED = "http://www.amss.et/ins/ws.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed_list);
        mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
        progressBar = (ProgressBarCircularIndetermininate) findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);
        mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.fragment_drawer);
        mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
        feedItems = new ArrayList<FeedItem>();
        listAdapter = new FeedListAdapter(this, feedItems);
        NewsView = (ListView) findViewById(R.id.feed_list);
        NewsView.setAdapter(listAdapter);

        // making fresh volley request and getting json
        GsonRequest<FeedResult> gsonRequest = new GsonRequest<FeedResult>(URL_FEED, FeedResult.class,
                new Response.Listener<FeedResult>() {
                    @Override
                    public void onResponse(FeedResult response) {
                        feedItems = response.getFeedItems();
                        listAdapter.setData(feedItems);
                        listAdapter.notifyDataSetChanged();
                        progressBar.setVisibility(View.INVISIBLE);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d(TAG, "Error: " + error.getMessage());
                    }
                });

        // Adding request to volley request queue
        AppController.getInstance().addRequest(gsonRequest, TAG);
        getimg();
    }

//    @Override protected int getLayoutResource() {
//        return R.layout.activity_feed_list;
//    }
    /**
     * Parsing json reponse and passing the data to News view list adapter
     */
    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("feed");

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                FeedItem item = new FeedItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("name"));

                // Image might be null sometimes
                String image = feedObj.isNull("image") ? null : feedObj
                        .getString("image");
                item.setImageUrl(image);
                item.setStatus(feedObj.getString("status"));
                item.setProfilePic(feedObj.getString("profilePic"));
                item.setTimeStamp(feedObj.getString("timeStamp"));

                // url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj
                        .getString("url");
                item.setUrl(feedUrl);
                feedItems.add(item);
            }

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void getimg(){
        Log.d(TAG,"Entered");
        NewsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                img(feedItems.get(arg2).getImageUrl());
            }
        });
    }

    public void img(String img){
        Toast.makeText(this, img, Toast.LENGTH_LONG).show();
    }

    public void Search(View v){
        Intent intent = getIntent();
        finish();
        startActivity(intent);
        Toast.makeText(this, "Searching", Toast.LENGTH_LONG).show();
    }
}

已转换的片段

public class FeedFragment extends Fragment {

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

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

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ListView NewsView;
        final FeedListAdapter listAdapter;
        final List<FeedItem> feedItems;
        final ProgressBarCircularIndetermininate progressBar;
        String URL_FEED = "http://www.amss.et/ins/ws.json";
        View v = getView();
        progressBar = (ProgressBarCircularIndetermininate) v.findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);

        feedItems = new ArrayList<FeedItem>();
        listAdapter = new FeedListAdapter(getActivity(), feedItems);
        NewsView = (ListView) v.findViewById(R.id.feed_list);
        NewsView.setAdapter(listAdapter);
    }

    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Uri uri);
    }

}

1 个答案:

答案 0 :(得分:1)

这是你应该做的......

public class FeedFragment extends Fragment {

    private static final String TAG = "FeedListActivity";

    private ListView NewsView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;
    private ProgressBarCircularIndetermininate progressBar;
private String URL_FEED = "http://www.amss.et/ins/ws.json";

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

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

    progressBar = (ProgressBarCircularIndetermininate)v.findViewById(R.id.progressBar);
    progressBar.setVisibility(View.VISIBLE);
    feedItems = new ArrayList<FeedItem>();
    listAdapter = new FeedListAdapter(getActivity(), feedItems);
    NewsView = (ListView) v.findViewById(R.id.feed_list);
    NewsView.setAdapter(listAdapter);

    // making fresh volley request and getting json
    GsonRequest<FeedResult> gsonRequest = new GsonRequest<FeedResult>(URL_FEED, FeedResult.class,
            new Response.Listener<FeedResult>() {
                @Override
                public void onResponse(FeedResult response) {
                    feedItems = response.getFeedItems();
                    listAdapter.setData(feedItems);
                    listAdapter.notifyDataSetChanged();
                    progressBar.setVisibility(View.INVISIBLE);

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d(TAG, "Error: " + error.getMessage());
                }
            });

    // Adding request to volley request queue
    AppController.getInstance().addRequest(gsonRequest, TAG);
    getimg();

        return v;
}

//    @Override protected int getLayoutResource() {
//        return R.layout.activity_feed_list;
//    }
    /**
     * Parsing json reponse and passing the data to News view list adapter
     */
    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("feed");

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                FeedItem item = new FeedItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("name"));

                // Image might be null sometimes
                String image = feedObj.isNull("image") ? null : feedObj
                        .getString("image");
                item.setImageUrl(image);
                item.setStatus(feedObj.getString("status"));
                item.setProfilePic(feedObj.getString("profilePic"));
                item.setTimeStamp(feedObj.getString("timeStamp"));

                // url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj
                        .getString("url");
                item.setUrl(feedUrl);
                feedItems.add(item);
            }
                        // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void getimg(){
        Log.d(TAG,"Entered");
        NewsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                img(feedItems.get(arg2).getImageUrl());
            }
        });
    }
    public void img(String img){
        Toast.makeText(getActivity(), img, Toast.LENGTH_LONG).show();
    }}