如何将活动转换为片段

如何将活动转换为片段

本文介绍了安卓:如何将活动转换为片段,以便正确地使用导航抽屉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发,目前显示在MainActivity文章列表,并是否正常工作的A​​ndr​​oid应用程序,我想通过添加包含的物品类别导航抽屉和一个家,使应用程序稍微更复杂按钮上方他们。

I'm developing an android application that currently displays a list of articles in the MainActivity and is working correctly, i want to make the application a little more sophisticated by adding a navigation drawer that contains the articles' categories and a "Home" button above them.

所以我就开始在Android Studio的一个新项目,我选的空白应用与导航抽屉,然后我手动导入我的previous应用到这个新的项目,我重新命名previous MainActivity到HomePage.java,因为MainActivity这里是导航抽屉。

So i started a new project on Android Studio and i selected blank app with Navigation Drawer then i imported my previous app manually into this new project and i renamed my previous MainActivity to HomePage.java, because the MainActivity here is for the Navigation Drawer.

我做了很多的研究,我认为,我有我的活动转化为片段,以便与抽屉式导航工作,但我不知道怎么办。

I made many researches and i think that i have to convert my activities into fragments in order to work with Navigation Drawer, but i don't know how.

这是MainActivity.java:

This is the 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:

And this is 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。

Now what i want is to be navigated to the HomePage.java after clicking on the "Home" button on the Navigation Drawer (Side Menu).

任何人都可以帮忙吗?

推荐答案

我是新来的android但是从我从谷歌的官方文档明白了,他们是真的相似,参考文档的

I'm new to android but from what i understand from google's official documentation, they are really similar, refer to the documentation here

这篇关于安卓:如何将活动转换为片段,以便正确地使用导航抽屉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:27