使用ViewPager的TabLayout以片段形式显示JSON数据

时间:2017-05-11 12:04:25

标签: android android-fragments android-recyclerview android-viewpager tableview

我在选项卡式视图模式下的导航活动中有三个可滑动片段。每个片段都必须显示API中的JSON数据。问题是我无法获取片段中的数据..我使用recyclerView来查看数据。

这是我的片段:

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


import droidmentor.bnv_with_viewpager.MyAdapter;
import droidmentor.bnv_with_viewpager.Config;
import droidmentor.bnv_with_viewpager.R;
import droidmentor.bnv_with_viewpager.Products;

public class FindFragment extends Fragment implements SearchView.OnQueryTextListener {

    /*private RecyclerView recyclerview;
    private List<CountryModel> mCountryModel;
    private RVAdapter adapter;*/
    //Creating Views
   private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;
     private List<Products> productsList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_find, container, false);

      /*  recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerview.setLayoutManager(layoutManager);
        //Initializing Views */
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);


        return view;

    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setHasOptionsMenu(true);

        final ProgressDialog loading = new ProgressDialog(getActivity());
        loading.setMessage("Loading Data");
        loading.show();
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                //Dismissing progress dialog
                loading.dismiss();
               // parseData(response);
                JSONArray array = response;
                for(int i = 0; i<array.length(); i++) {
                    Products products = new Products();
                    JSONObject json = null;
                    try {
                        json = array.getJSONObject(i);
                        products.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
                        products.setNamee(json.getString(Config.TAG_NAME));
                        products.setRank(json.getInt(Config.TAG_RANK));
                        products.setRealName(json.getString(Config.TAG_REAL_NAME));


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    productsList.add(products);
                }

                //Finally initializing our adapter
                adapter = new MyAdapter(productsList, getActivity());

                //Adding adapter to recyclerview
                recyclerView.setAdapter(adapter);


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(jsonArrayRequest);





     /*   String[] locales = Locale.getISOCountries();
        mCountryModel = new ArrayList<>();

        for (String countryCode : locales) {
            Locale obj = new Locale("", countryCode);
            mCountryModel.add(new CountryModel(obj.getDisplayCountry(), obj.getISO3Country()));
        }

        adapter = new RVAdapter(mCountryModel);
        recyclerview.setAdapter(adapter);*/
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_main, menu);

        final MenuItem item = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
        searchView.setOnQueryTextListener(this);

        MenuItemCompat.setOnActionExpandListener(item,
                new MenuItemCompat.OnActionExpandListener() {
                    @Override
                    public boolean onMenuItemActionCollapse(MenuItem item) {
                        // Do something when collapsed
                       // adapter.setFilter(mCountryModel);
                        return true; // Return true to collapse action view
                    }

                    @Override
                    public boolean onMenuItemActionExpand(MenuItem item) {
                        // Do something when expanded
                        return true; // Return true to expand action view
                    }
                });
    }

    @Override
    public boolean onQueryTextChange(String newText) {
       // final List<CountryModel> filteredModelList = filter(mCountryModel, newText);
       // adapter.setFilter(filteredModelList);
        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }


    private List<CountryModel> filter(List<CountryModel> models, String query) {
        query = query.toLowerCase();

        final List<CountryModel> filteredModelList = new ArrayList<>();
        for (CountryModel model : models) {
            final String text = model.getName().toLowerCase();
            if (text.contains(query)) {
                filteredModelList.add(model);
            }
        }
        return filteredModelList;
    }
    //This method will parse json data
    private void parseData(JSONArray array){

        for(int i = 0; i<array.length(); i++) {
            Products products = new Products();
            JSONObject json = null;
            try {
                json = array.getJSONObject(i);
                products.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
                products.setNamee(json.getString(Config.TAG_NAME));
                products.setRank(json.getInt(Config.TAG_RANK));
                products.setRealName(json.getString(Config.TAG_REAL_NAME));



            } catch (JSONException e) {
                e.printStackTrace();
            }
            productsList.add(products);
        }

        //Finally initializing our adapter
        adapter = new MyAdapter(productsList, getActivity());

        //Adding adapter to recyclerview
        recyclerView.setAdapter(adapter);
    }

}

导航活动:

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import droidmentor.bnv_with_viewpager.Fragment.FindFragment;
import droidmentor.bnv_with_viewpager.Fragment.AnalyseFragment;
import droidmentor.bnv_with_viewpager.Fragment.ContactsFragment;

public class Display extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    BottomNavigationView bottomNavigationView;

    //This is our viewPager
    private ViewPager viewPager;

    //Fragments
    AnalyseFragment analyseFragment;
    FindFragment findFragment;
    ContactsFragment contactsFragment;
    MenuItem prevMenuItem;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();

        actionBar.setDisplayHomeAsUpEnabled(true);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        //Initializing viewPager
        viewPager = (ViewPager) findViewById(R.id.viewpager);

        //Initializing the bottomNavigationView
        bottomNavigationView = (BottomNavigationView)findViewById(R.id.bottom_navigation);

        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.action_call:
                                viewPager.setCurrentItem(0);
                                break;
                            case R.id.action_chat:
                                viewPager.setCurrentItem(1);
                                break;
                            case R.id.action_contact:
                                viewPager.setCurrentItem(2);
                                break;
                        }
                        return false;
                    }
                });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (prevMenuItem != null) {
                    prevMenuItem.setChecked(false);
                }
                else
                {
                    bottomNavigationView.getMenu().getItem(0).setChecked(false);
                }
                Log.d("page", "onPageSelected: "+position);
                bottomNavigationView.getMenu().getItem(position).setChecked(true);
                prevMenuItem = bottomNavigationView.getMenu().getItem(position);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

       /*  //Disable ViewPager Swipe

       viewPager.setOnTouchListener(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                return true;
            }
        });

        */

        setupViewPager(viewPager);
    }
    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        findFragment=new FindFragment();
        analyseFragment=new AnalyseFragment();
        contactsFragment=new ContactsFragment();
        adapter.addFragment(findFragment);
        adapter.addFragment(analyseFragment);
        adapter.addFragment(contactsFragment);
        viewPager.setAdapter(adapter);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.display, menu);
        return true;
    }

    @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);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}

adapterVieawPage:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;

import java.util.ArrayList;
import java.util.List;

import droidmentor.bnv_with_viewpager.Fragment.AnalyseFragment;
import droidmentor.bnv_with_viewpager.Fragment.ContactsFragment;
import droidmentor.bnv_with_viewpager.Fragment.FindFragment;

/**
 * Created by hamza on 23/4/17.
 */


public class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }
    @Override
    public Fragment getItem(int position) {
       // return mFragmentList.get(position);
        switch (position) {
            case 0:
                FindFragment findFragment = new FindFragment();
                return findFragment;
            case 1:
                AnalyseFragment analyseFragment  = new AnalyseFragment();
                return analyseFragment;
            case 2:
                ContactsFragment  contactsFragment = new ContactsFragment();
                return contactsFragment;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment) {
        mFragmentList.add(fragment);
    }

}

recyclerView适配器:

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;


import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hamza on 07/05/2017.
 */

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    private ImageLoader imageLoader;
    private Context context;
   // private RequestQueue mRequestQueue;
   // private ImageLoader mImageLoader;
    private LayoutInflater inflater;

    //List of products
    List<Products> productsList;


    public MyAdapter(List<Products> productsList, Context context){
        super();
        //Getting all the productsList
        this.productsList = productsList;
        inflater = LayoutInflater.from(context);
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.product_list, parent, false);
        ViewHolder viewHolder = new ViewHolder(v,context,productsList);
        return viewHolder;
    }


    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {


        Products products =  productsList.get(position);

        imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
        imageLoader.get(products.getImageUrl(), ImageLoader.getImageListener(holder.imageView,
                R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
      /*  mRequestQueue = Volley.newRequestQueue(context);
        mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(10);
            public void putBitmap(String url, Bitmap bitmap) {
                mCache.put(url, bitmap);
            }
            public Bitmap getBitmap(String url) {
                return mCache.get(url);
            }
        });*/

        holder.imageView.setImageUrl(products.getImageUrl(), imageLoader);
        //holder.imageView.setImageUrl(products.getImageUrl(), mImageLoader);
        holder.textViewName.setText(products.getNamee());
        holder.textViewRank.setText(String.valueOf(products.getRank()));
        holder.textViewRealName.setText(products.getRealName());



    }

    @Override
    public int getItemCount() {
        if(productsList != null)
        return productsList.size();
        return 0;
    }
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        public NetworkImageView imageView;
        public TextView textViewName;
        public TextView textViewRank;
        public TextView textViewRealName;

        public  List<Products> productsList = new ArrayList<Products>();
        public Context context;

        public ViewHolder(View itemView , Context context,List<Products> productsList ) {

            super(itemView);
            itemView.setOnClickListener(this);
            this.productsList = productsList;
            this.context = context;
            imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
            textViewName = (TextView) itemView.findViewById(R.id.textViewName);
            textViewRank= (TextView) itemView.findViewById(R.id.textViewRank);
            textViewRealName= (TextView) itemView.findViewById(R.id.textViewRealName);

        }

        @Override
        public void onClick(View v) {
            int position = getAdapterPosition();
            Products productsList = this.productsList.get(position);
            BitmapDrawable bd = (BitmapDrawable) ((NetworkImageView) v.findViewById(R.id.imageViewProduct))
                    .getDrawable();

            Bitmap bitmap=bd.getBitmap();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bd.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] imgByte = baos.toByteArray();

            Intent intent = new Intent(this.context,start.class);
            intent.putExtra("image",imgByte);
            intent.putExtra("name",productsList.getNamee());
            this.context.startActivity(intent);

        }
    }
}

0 个答案:

没有答案