使用多个循环视图的标签布局不起作用

时间:2017-07-08 11:15:36

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

在我的项目中,我试图在3个标签中显示Recycleview。在我的拳头选项卡中,我能够成功地在recycleview中显示项目。但在我的第二个标签片段中它不起作用。请参阅我的标签布局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/lib/zesteve.com.myapplication"
    android:layout_width="match_parent"
    xmlns:app1="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_height="wrap_content">

  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabGravity="fill"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        app:tabMode="fixed"
        android:elevation="10dp"
        style="@style/NavigationTab"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>

  </LinearLayout>

    <android.support.design.widget.FloatingActionButton
            app:backgroundTint="@color/colorPrimary"
            android:layout_width="56dp"
            android:layout_height="56dp"
            app:fabSize="normal"
            android:layout_gravity="bottom|right"
            android:src="@drawable/ic_action_fab_act_btn"
            android:id="@+id/post_new_event"
            android:layout_margin="16dp"/>

</FrameLayout>

和Tabfragement.java

public class TabFragment extends Fragment {

    public static TabLayout tabLayout;
    public static ViewPager viewPager;
    public static int int_items = 3 ;

    FloatingActionButton fab;

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

        View x =  inflater.inflate(R.layout.tab_layout,container, false);
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        viewPager = (ViewPager) x.findViewById(R.id.viewpager);
        //tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

        viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));

        fab = (FloatingActionButton) x.findViewById(R.id.post_new_event);

        fab.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.cpb_blue)));

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(),PostNewEvent.class);
                startActivity(intent);
            }
        });


        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });

        return x;

    }

    class MyAdapter extends FragmentStatePagerAdapter{

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }



        @Override
        public Fragment getItem(int position)
        {
            switch (position){
                case 0 : return new PrimaryFragment();
                case 1 : return new CityFeedFragment();
                case 2 : return new BuzzFragment();
            }
            return null;
        }

        @Override
        public int getCount() {

            return int_items;

        }



        @Override
        public CharSequence getPageTitle(int position) {

            switch (position){
                case 0 :
                    return "Category";
                case 1 :
                    return "City Feeds";
                case 2 :
                    return "Buzz";
            }
            return null;
        }
    }

}

我的第二个标签适配器

public class CityfeedAdapter extends RecyclerView.Adapter<CityfeedAdapter.MyViewHolder>{

    Context mContext;
    ArrayList<Cityfeed> cityfeedList = new ArrayList<Cityfeed>();
    private MaterialRippleLayout mRipple;


    public CityfeedAdapter(Context mContext, ArrayList<Cityfeed> cityfeedList){
        this.mContext = mContext;
        this.cityfeedList = cityfeedList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.city_feed_card, parent, false);

        return new MyViewHolder(itemView,mContext,cityfeedList);
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
        Cityfeed catlist = cityfeedList.get(position);
        holder.title.setText(catlist.getName());
        holder.count.setText(catlist.getNumOfEvents() + " Events");

        // loading album cover using Picasso library
        Picasso.with(mContext).load(catlist.getThumbnail()).into(holder.thumbnail);
    }

    @Override
    public int getItemCount() {
        return cityfeedList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        public TextView title, count;
        public ImageView thumbnail;

        ArrayList<Cityfeed> cityfeedList = new ArrayList<Cityfeed>();
        Context mContext;

        public MyViewHolder(View view , Context mContext, ArrayList<Cityfeed> cityfeedList ) {
            super(view);
            this.cityfeedList = cityfeedList;
            this.mContext = mContext;
            //view.setOnClickListener(this);
            title = (TextView) view.findViewById(R.id.title);
            count = (TextView) view.findViewById(R.id.count);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
            mRipple = (MaterialRippleLayout) view.findViewById(R.id.ripple);
            MaterialRippleLayout.on(mRipple).create();
            mRipple.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            int position = getAdapterPosition();
            Cityfeed cityfeedList = this.cityfeedList.get(position);
            Intent intent = new Intent(this.mContext, EventPostList.class);
            intent.putExtra("EveId", cityfeedList.getEventId());
            intent.putExtra("EveName", cityfeedList.getName());
            this.mContext.startActivity(intent);

        }
    }
}

第二个标签片段

public class CityFeedFragment extends Fragment {

    private RecyclerView recyclerView;
    private CityfeedAdapter adapter;
    private ArrayList<Cityfeed> cityfeedList;
    private Session session;
    private GridLayoutManager mLayoutManager;
    private ProgressDialog progressDialog;

    String ucl;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = LayoutInflater.from(container.getContext()).inflate(R.layout.cityfeed_layout,container,false);
        recyclerView = (RecyclerView) root.findViewById(R.id.crecycler_view);


        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setCancelable(false);

        cityfeedList = new ArrayList<>();
        adapter = new CityfeedAdapter(getActivity(), cityfeedList);
        session = new Session(getActivity());
        load_data_from_server(0);

        mLayoutManager= new GridLayoutManager(getActivity(),3);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(3, dpToPx(10), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        ucl = session.getUserLocation().get(session.KEY_UCITY);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                //super.onScrolled(recyclerView, dx, dy);

                if(mLayoutManager.findLastCompletelyVisibleItemPosition()  == cityfeedList.size()-1){
                    load_data_from_server(cityfeedList.get(cityfeedList.size()-1).getEventId());
                }

            }
        });


        return root;
    }

    private void load_data_from_server(int id){
        progressDialog.setMessage("Loading Please Wait...");
        showDialog();

        AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {
            @Override
            protected Void doInBackground(Integer... integers) {

                OkHttpClient client = new OkHttpClient();
                okhttp3.Request request = new okhttp3.Request.Builder()
                        .url("http://api.zesteve.com/catagory.php?city="+ucl+"&id="+integers[0])
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    JSONArray array = new JSONArray(response.body().string());

                    for (int i=0; i<array.length(); i++){

                        JSONObject object =array.getJSONObject(i);

                        Cityfeed events = new Cityfeed(object.getString("eventname"),
                                object.getInt("count"),
                                object.getInt("eveid"),
                                object.getString("event_image"));

                        cityfeedList.add(events);
                    }

                }catch (IOException e){
                    e.printStackTrace();
                } catch (JSONException e) {
                    System.out.println("End of Catagory");
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                hideDialog();
                adapter.notifyDataSetChanged();
            }
        };
        task.execute(id);

    }


    public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            int column = position % spanCount; // item column

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }
        }
    }

    private void showDialog() {
        if (!progressDialog.isShowing())
            progressDialog.show();
    }

    private void hideDialog() {
        if (progressDialog.isShowing())
            progressDialog.dismiss();
    }
    /**
     * Converting dp to pixel
     */
    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

    @Override
    public void onResume() {
        super.onResume();
        load_data_from_server(0);
    }

}

我的第二个标签的XML布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include layout="@layout/content_cityfeed" />

</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/viewBg"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="zesteve.com.myapplication.CityFeedFragment"
    tools:showIn="@layout/cityfeed_layout">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/crecycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:scrollbars="vertical" />

</RelativeLayout>

这是我的Cardview

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="@dimen/card_margin"
        android:elevation="8dp"
        card_view:cardCornerRadius="@dimen/card_album_radius">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <com.balysv.materialripple.MaterialRippleLayout
                android:id="@+id/ripple"
                android:layout_centerInParent="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:mrl_rippleOverlay="true"
                app:mrl_rippleColor="#000"
                app:mrl_rippleAlpha="0.2"
                app:mrl_rippleDimension="10dp"
                app:mrl_rippleHover="true"
                app:mrl_rippleRoundedCorners="10dp"
                app:mrl_rippleInAdapter="false"
                app:mrl_rippleDuration="350"
                app:mrl_rippleFadeDuration="75"
                app:mrl_rippleDelayClick="false"
                app:mrl_rippleBackground="#FFF"
                app:mrl_ripplePersistent="true">

                <ImageView
                    android:id="@+id/thumbnail"
                    android:layout_width="match_parent"
                    android:layout_height="160dp"
                    android:background="?attr/selectableItemBackgroundBorderless"
                    android:scaleType="fitXY" />

            </com.balysv.materialripple.MaterialRippleLayout>

            <LinearLayout
                android:id="@+id/framlayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:background="#80000000" >

                <TextView
                    android:id="@+id/title"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingLeft="@dimen/album_title_padding"
                    android:paddingRight="@dimen/album_title_padding"
                    android:paddingTop="@dimen/album_title_Top"
                    android:paddingBottom="3dp"
                    android:textColor="@color/white"
                    android:textSize="@dimen/album_title" />

                <TextView
                    android:id="@+id/count"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingBottom="@dimen/songs_count_padding_bottom"
                    android:paddingLeft="@dimen/album_title_padding"
                    android:paddingRight="@dimen/album_title_padding"
                    android:textColor="@color/white"
                    android:textSize="@dimen/songs_count" />
            </LinearLayout>



        </RelativeLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>

我希望我没有错过任何事情。 Recyleview没有在我的第二个标签片段中显示任何内容。当我在浏览器中检查时,我的Json响应正常,它显示响应,但不显示在片段中。

1 个答案:

答案 0 :(得分:1)

api中有错误:

在解析JSONArray时尝试这个:

 Cityfeed events = new Cityfeed(object.has("eventname")?object.getString("eventname"):"",
            object.has("count")?object.getInt("count"):0,
            object.has("eveid")?object.getInt("eveid"):"",
            object.has("event_image")?object.getString("event_image"):"");

希望这有帮助。