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

Java Android:如何将活动转换为片段,以便正确使用导航抽屉?,java,android,android-fragments,android-studio,navigation-drawer,Java,Android,Android Fragments,Android Studio,Navigation Drawer,我正在开发一个android应用程序,它当前在MainActivity中显示文章列表,并且工作正常。我希望通过添加一个导航抽屉(包含文章类别)和上面的“主页”按钮,使该应用程序更加复杂 因此,我在Android Studio上启动了一个新项目,我选择了带有导航抽屉的空白应用程序,然后我手动将以前的应用程序导入到这个新项目中,并将以前的MainActivity重命名为HomePage.java,因为这里的MainActivity用于导航抽屉 我做了很多研究,我认为我必须将我的活动转换成片段,以便使

我正在开发一个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);
        }
    }
}
import java.util.ArrayList;
导入java.util.List;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.ListActivity;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.text.Html;
导入android.util.Log;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.AdapterView.OnItemClickListener;
导入android.widget.Button;
导入android.widget.ListView;
导入android.widget.TextView;
公开课主页扩展列表活动{
//创建进度对话框实例
私人对话;
//JSON节点名称
私有静态最终字符串标记_ARTICLES=“ARTICLES”;
私有静态最终字符串标记\u ID=“ID”;
私有静态最终字符串标记_TITLE=“TITLE”;
私有静态最终字符串标记\u striser=“striser”;
私有静态最终字符串标记\u COVER\u PHOTO=“COVER\u PHOTO”;
字符串调用\u url=”http://www.ana.fm/api/main/?start=0&count=20";
int start_get=0;
int count_get=20;
int lastItemIndex=0;
ListView lv;
//文章JSONArray
JSONArray articles=null;
//使用Article类型定义项目列表
物品清单;
按钮加载按钮;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home_页面);
articleList=新的ArrayList();
//获取列表视图
lv=getListView();
//在添加适配器之前添加页脚,否则将不会加载页脚!
视图页脚视图=((LayoutInflater)this.getSystemService(Context.LAYOUT\u INFLATER\u SERVICE)).inflate(R.LAYOUT.list\u footer,null,false);
lv.addFooterView(footerView);
//将click listener添加到“加载更多”按钮
loadMoreButton=(按钮)findViewById(R.id.loadMoreBtn);
loadMoreButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
lastItemIndex=lv.getLastVisiblePosition();
开始获取=开始获取+20;
调用url=”http://www.ana.fm/api/main/?start=.concat(String.valueOf(start_get)).concat(“&count=20”);
//调用异步任务以获取json
新建GetArticles().execute();
}
});
//单击项目上的Listview侦听器
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
String article_id=((TextView)view.findViewById(R.id.article_id))
.getText().toString();
//开始单品活动
Intent in=新的Intent(getApplicationContext(),
(活动类);
in.putExtra(标签ID、物品ID);
星触觉(in);
}
});
//调用异步任务以获取json
新建GetArticles().execute();
}
/**
*异步任务类通过HTTP调用获取json
*/
私有类GetArticles扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//显示进度对话框
pDialog=新建进度对话框(HomePage.this);
setMessage(“请稍候…”);
pDialog.setCancelable(假);
pDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…arg0){
//创建服务处理程序类实例
ServiceHandler sh=新的ServiceHandler();
//向url发出请求并获得响应
//调用url之前已定义
字符串jsonStr=sh.makeServiceCall(调用url,ServiceHandler.GET);
if(jsonStr!=null){
试一试{
JSONObject jsonObj=新的JSONObject(jsonStr);
//获取JSON数组节点
articles=jsonObj.getJSONArray(TAG_articles);
//循环浏览所有文章
对于(int i=0;i