簡體   English   中英

Android:使用Listfragment而不是Fragment

[英]Android : Using Listfragment instead of Fragment

我正在制作一個新聞應用程序,該應用程序在新聞活動中有一個帶有2個標簽的標簽滑塊,稱為“新新聞”-“隨機或熱門新聞”。 每個選項卡的內容都是片段。(希望您能得到我!)。

但問題是即時通訊使用代碼來解析此頁面內容> http://aliak.xzn.ir/rap/get_all_products.php (我想您可以找到即時通訊使用的網站代碼)...

問題是,如果我想在片段(而非活動)中顯示此代碼,則必須編寫以下代碼:

public class tab1 extends ListFragment {}

代替這個:

public class tab1 extends Fragment {}

和我的尋呼機適配器,我有問題,這告訴我listfragment不被接受! 如果我不使用列表片段,我會有很多錯誤!

APP的代碼:

我的tab1片段::

public class tab1 extends ListFragment {

    //static final String url_all_products = "http://aliak.xzn.ir/rap/get_all_products.php";
    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    final String TAG_SUCCESS = "success";
    final String TAG_PRODUCTS = "products";
    final String TAG_PID = "pid";
    final String TAG_NAME = "name";

    // JSON Node names


    // products JSONArray
    JSONArray products = null;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tab_1, container, false);


        /**
         * Background Async Task to Load all product by making HTTP Request
         */
        class LoadAllProducts extends AsyncTask<String, String, String> {

            /**
             * Before starting background thread Show Progress Dialog
             */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(getActivity());
                pDialog.setMessage("درحال دريافت اخبار،کمي صبر کنيد!");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();
            }


            /**
             * getting All products from url
             */
            protected String doInBackground(String... args) {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                // getting JSON string from URL
                JSONObject json = jParser.makeHttpRequest("http://aliak.xzn.ir/rap/get_all_products.php", "GET", params);

                // Check your log cat for JSON reponse
                Log.d("All Products: ", json.toString());

                try {
                    // Checking for SUCCESS TAG
                    int success = json.getInt(TAG_SUCCESS);

                    if (success == 1) {
                        // products found
                        // Getting Array of Products
                        products = json.getJSONArray(TAG_PRODUCTS);

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

                            // Storing each json item in variable
                            String id = c.getString(TAG_PID);
                            String name = c.getString(TAG_NAME);

                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key => value
                            map.put(TAG_PID, id);
                            map.put(TAG_NAME, name);

                            // adding HashList to ArrayList
                            productsList.add(map);
                        }
                    } else {
                        // no products found
                        // Launch Add New product Activity
                        Intent i = new Intent(getActivity().getApplicationContext(),
                                Main.class);
                        // Closing all previous activities
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(i);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return null;
            }

            /**
             * After completing background task Dismiss the progress dialog
             * *
             */

            protected void onPostExecute(String file_url) {
                // dismiss the dialog after getting all products
                pDialog.dismiss();
                // updating UI from Background Thread
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        /**
                         * Updating parsed JSON data into ListView
                         * */
                        ListAdapter adapter = new SimpleAdapter(
                                getActivity(), productsList,
                                R.layout.list_item, new String[]{TAG_PID,
                                TAG_NAME},
                                new int[]{R.id.pid, R.id.name});
                        // updating listview
                        setListAdapter(adapter);
                    }
                });

            }


        }


        productsList = new ArrayList<HashMap<String, String>>();


        // Loading products in Background Thread
        new LoadAllProducts().execute();


        return v;

    }


}

我的適配器類:

/**
* Created by hp1 on 21-01-2015.
*/
public class ViewPagerAdapter extends FragmentStatePagerAdapter {

CharSequence Titles[]; // This will Store the Titles of the Tabs which   are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created


// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
    super(fm);

    this.Titles = mTitles;
    this.NumbOfTabs = mNumbOfTabsumb;
}

//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {


    if (position == 0) // if the position is 0 we are returning the First tab
    {
        tab1 tab1 = new tab1();
        return tab1;
    } else             // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
    {
        tab2 tab2 = new tab2();
        return tab2;

    }


}
/*


*/


// This method return the titles for the Tabs in the Tab Strip

@Override
public CharSequence getPageTitle(int position) {
    return Titles[position];
}

// This method return the Number of tabs for the tabs Strip

@Override
public int getCount() {
    return NumbOfTabs;
}
}

如果需要更多編碼,請告訴我,請在2分鍾內答復!

檢查您的導入,並確保您的Fragment和ListFragment來自相同的程序包,即android.support.v4.app.Fragment / ListFragment或android.app.Fragment / ListFragment。 無論您使用哪種,都必須與您實際的片段類實現保持一致。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM