Android:如何将活动转换为片段以正确使用导航抽屉?

时间:2015-02-18 21:27:04

标签: java android android-fragments android-studio navigation-drawer

我正在开发一个Android应用程序,当前在MainActivity中显示文章列表并且工作正常,我想通过添加包含文章类别和“主页”的导航抽屉使应用程序更复杂一些“按钮在他们上面。

所以我在Android Studio上开始了一个新项目,我选择了导航抽屉的空白应用程序,然后我手动将我以前的应用程序导入到这个新项目中,并将我以前的MainActivity重命名为HomePage.java,因为这里的MainActivity用于导航抽屉。

我做了很多研究,我认为我必须将我的活动转换成碎片才能使用导航抽屉,但我不知道如何。

这是MainActivity.java:

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;



public class MainActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                .commit();


    }

    public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                mTitle = getString(R.string.title_section1); //The Home Button
                break;
            case 2:
                mTitle = getString(R.string.title_section2);
                break;
            case 3:
                mTitle = getString(R.string.title_section3);
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @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_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }
    }

}

这是HomePage.java:

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;



public class HomePage extends ListActivity  {

    //Create a progress dialog instance
    private ProgressDialog pDialog;

    // JSON Node names
    private static final String TAG_ARTICLES = "articles";
    private static final String TAG_ID = "id";
    private static final String TAG_TITLE = "title";
    private static final String TAG_TEASER = "teaser";
    private static final String TAG_COVER_PHOTO = "cover_photo";
    String call_url = "http://www.ana.fm/api/main/?start=0&count=20";
    int start_get = 0;
    int count_get = 20;
    int lastItemIndex = 0;
    ListView lv;

    //Articles JSONArray
    JSONArray articles = null;

    //Defining the articles list with type Article
    List<Article> articleList;

    Button loadMoreButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_page);

        articleList = new ArrayList<>();

        //Getting the ListView
        lv = getListView();

        //add the footer before adding the adapter, else the footer will not load!
        View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.list_footer, null, false);
        lv.addFooterView(footerView);

        //Add click listener to the load more button
        loadMoreButton = (Button) findViewById(R.id.loadMoreBtn);


        loadMoreButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                lastItemIndex = lv.getLastVisiblePosition();
                start_get = start_get + 20;
                call_url = "http://www.ana.fm/api/main/?start=".concat(String.valueOf(start_get)).concat("&count=20");
                // Calling async task to get json
                new GetArticles().execute();
            }
        });

        // Listview on item click listener
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String article_id = ((TextView) view.findViewById(R.id.article_id))
                        .getText().toString();
                // Starting single article activity
                Intent in = new Intent(getApplicationContext(),
                        SingleArticleActivity.class);
                in.putExtra(TAG_ID, article_id);
                startActivity(in);

            }
        });
        // Calling async task to get json
        new GetArticles().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetArticles extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(HomePage.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            //call_url is defined previously

            String jsonStr = sh.makeServiceCall(call_url, ServiceHandler.GET);
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    articles = jsonObj.getJSONArray(TAG_ARTICLES);

                    // looping through All Articles
                    for (int i = 0; i < articles.length(); i++) {
                        JSONObject c = articles.getJSONObject(i);

                        String id = c.getString(TAG_ID);
                        String title = c.getString(TAG_TITLE);
                        title = Html.fromHtml(title).toString();
                        String teaser = c.getString(TAG_TEASER);
                        teaser = Html.fromHtml(teaser).toString();
                        String cover_photo = "http://www.ana.fm/med_photos/articles/";
                        cover_photo = cover_photo.concat(c.getString(TAG_COVER_PHOTO));


                        //Getting an object from the Article class
                        Article article = new Article();

                        //Setting the values to the object's variables
                        article.setId(id);
                        article.setTitle(title);
                        article.setTeaser(teaser);
                        article.setImageUrl(cover_photo);


                        // adding article to the article list
                        articleList.add(article);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
                //new GetContacts().execute();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();

            /**
             * Calling my custom adapter to view the images as well
             * */
            MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.list_item, articleList);
            setListAdapter(adapter);
            lv.setSelection(lastItemIndex);
        }
    }
}

现在我想要的是在点击导航抽屉(侧面菜单)上的“主页”按钮后导航到HomePage.java。

任何人都可以提供帮助吗?

1 个答案:

答案 0 :(得分:0)

我是Android的新手,但据我从谷歌的官方文档中了解到,它们非常相似,请参阅文档here