Как получить размер конкретной переменной из класса Model в Android? - PullRequest
0 голосов
/ 22 ноября 2018

У меня есть класс модели:

public class Home_Model_ViewPager {


public String buttonLink;
public String tipsDescription;
public String tipsButton;
public Context context;

public Home_Model_ViewPager( Context context, String tipsDescription, String tipsButton, String buttonLink) {
    this.context = context;
    this.tipsDescription = tipsDescription;
    this.tipsButton = tipsButton;
    this.buttonLink = buttonLink;
}

public String getButtonLink() {
    return buttonLink;
}

public void setButtonLink(String buttonLink) {
    this.buttonLink = buttonLink;
}

public String getTipsDescription() {
    return tipsDescription;
}

public void setTipsDescription(String tipsDescription) {
    this.tipsDescription = tipsDescription;
}

public String getTipsButton() {
    return tipsButton;
}

public void setTipsButton(String tipsButton) {
    this.tipsButton = tipsButton;
}

}

Я использовал этот класс модели, чтобы использовать его в адаптере viewpager.

Итак, я используюпереработчик просмотр и настройка данных к нему.Теперь у меня есть проблема, что у меня есть viewpager в Recycleleritem.Я хочу вернуть размер адаптера viewpager любого элемента в Home_Model_ViewPager, так как каждый элемент имеет разный размер.

Это то, что я пробовал в ViewPagerAdapter:

    public class ViewPagerAdapter extends PagerAdapter {
    // Declare Variables
    Context context;
    LayoutInflater inflater;
    List<Home_Model_ViewPager> totalList;

    public ViewPagerAdapter(Context context, List<Home_Model_ViewPager> totalList) {
        this.context = context;
        this.totalList = totalList;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {

        // Declare Variables
        TextView tricksDescription;
        Button tricksButton;

        View itemView = inflater.inflate(R.layout.viewpager_item, container,
                false);

        tricksDescription =  itemView.findViewById(R.id.xtv_tricks_description);
        tricksButton = itemView.findViewById(R.id.tricks_button);

        tricksDescription.setText(Html.fromHtml(totalList.get(position).getTipsDescription()));
        tricksButton.setText(Html.fromHtml(totalList.get(position).getTipsButton()));
        tricksButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    String url = totalList.get(position).getButtonLink();
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
         container.addView(itemView);

        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view = (View) object;
        container.removeView(view);

    }
}

Яиспользуя залп, чтобы получить значения как JSON ..

 private void Home() {
    try {
        if (getActivity()!=null)
            Commonfunctions.LoadPreferences(getActivity());
        System.out.println("Authtoken:" + Commonfunctions.Token_key);
        appservice.View_All_Events(Commonfunctions.Token_key, String.valueOf(pagenumber), new Server_Callback() {
            @Override
            public void onSuccess(String response) {
                System.out.println("HOME Response :" + response);
                try {
                    JSONObject signObject = new JSONObject(response);

                    String resStatus = signObject.getString(AppConstants.STATUS);
                    String resCode = signObject.getString(AppConstants.CODE);
                    String resMsg = signObject.getString(AppConstants.MSG);

                    if (resCode.equals(AppConstants.SUCCESS_CODE)) {

                        JSONArray allEvents = signObject.getJSONArray("all");

                        System.out.println("INNER Response :" + allEvents);
                        for (int i = 0; i < allEvents.length(); i++) {
                            JSONObject innerObj1 = allEvents.getJSONObject(i);
                            String backgroundImg = innerObj1.getString("backg_img");
                            String declinedCount = innerObj1.getString("decli_count");
                            String acceptedCount = innerObj1.getString("accep_count");
                            String invitedCount = innerObj1.getString("invi_count");
                            String messages = innerObj1.getString("i_chat");
                            String name = innerObj1.getString("name");
                            String eventTime = innerObj1.getString("duration");
                            String userPhoto = innerObj1.getString("photo");

                            JSONArray viewpagerEvents = innerObj1.getJSONArray("action");
                            for (int u = 0; u < viewpagerEvents.length(); u++) {
                                JSONObject innerObj3 = viewpagerEvents.getJSONObject(u);
                                String buttonText = innerObj3.getString("text");
                                String tipsDesc = innerObj3.getString("action_text");
                                String buttonLink = innerObj3.getString("button_link");
                            final Home_Model home_data = new Home_Model(name, messages,invitedCount,declinedCount,acceptedCount,eventTime,
                                    userPhoto,backgroundImg);
                            data.add(home_data);
                            final Home_Model_ViewPager home_viewpager = new Home_Model_ViewPager(getContext(),tipsDesc,buttonText, buttonLink);
                            viewPagerData.add(home_viewpager);
                            }
                            }
                            adapter = new HomeAdapter(getContext(),data);
                        pagerAdapter = new ViewPagerAdapter(getActivity(), viewPagerData);
                        home_recycler.setAdapter(adapter);
                        adapter.notifyDataSetChanged();

                        if (adapter.getItemCount()==0) {
                            noeventLayout.setVisibility(View.VISIBLE);
                        }
                        else {
                            noeventLayout.setVisibility(View.GONE);
                        }

                    } else if (resCode.equals(AppConstants.UPDATE_CODE)) {
                        //Version_Update versionUpdate=new Version_Update(SignIn.this,response);
                    } else {
                        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                        Commonfunctions.showerrorsnackbar(resMsg, getActivity(), parentLayout);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }//on success close

        });//server callback closed
    } catch (Exception e) {
        e.printStackTrace();
    }
}

HomeAdapter:

  class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ViewHolder> {
    Context context;
    List<Home_Model> students;
    public HomeAdapter(Context context,List<Home_Model> students) {
        this.context = context;
        this.students = students;
    }

    @Override
    public HomeAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.event_home_list, viewGroup, false);
        return new HomeAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final HomeAdapter.ViewHolder holder, final int position) {
        holder.title.setText(students.get(position).getName());
        holder.invited.setText(students.get(position).getInvited());
        holder.accepted.setText(students.get(position).getAccept());
        holder.declined.setText(students.get(position).getDecline());
        holder.eventTime.setText(students.get(position).getEvent_time());
        holder.messages.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            startActivity(new Intent(getActivity(),Chat_view.class));
            }
        });

        holder.viewPager.setAdapter(pagerAdapter);
        holder.dots = new ImageView[holder.dotsCount];
        for (int i = 0; i < holder.dotsCount; i++) {
            holder.dots[i] = new ImageView(context);
            holder.dots[i].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_gray ));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(8, 0, 8, 0);
            holder.sliderDots.addView(holder.dots[i], params);
        }
        holder.dots[0].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_colorprimary));
        holder.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {

                for (int i = 0; i < holder.dotsCount; i++) {
                    holder.dots[i].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_gray));
                }
                holder.dots[position].setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_dot_colorprimary));


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });



        if (students.get(position).getMessages().contentEquals("false")) {
        holder.status.setVisibility(View.INVISIBLE);
        }
        else {
        holder.status.setVisibility(View.VISIBLE);
        }
        holder.status.setVisibility(View.INVISIBLE);
        try {
            Glide.with(getActivity()).load(students.get(position).getProimg()).into(holder.pro_img);
            Glide.with(getActivity()).load(students.get(position).getBgimg()).into(holder.card_main);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView title, messages, invited, accepted, declined, eventTime;
        private PorterShapeImageView pro_img;
        ImageView card_main, status;
        ViewPager viewPager;
        LinearLayout sliderDots;
        private ImageView[] dots;
        private int dotsCount;

        public ViewHolder(View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.xtv_welcome);
            messages = itemView.findViewById(R.id.xtv_message);
            invited = itemView.findViewById(R.id.xtv_invited);
            accepted = itemView.findViewById(R.id.xtv_accepted);
            declined = itemView.findViewById(R.id.xtv_decline);
            eventTime = itemView.findViewById(R.id.contact_number);
            pro_img = itemView.findViewById(R.id.pro_pic);
            card_main = itemView.findViewById(R.id.card_main);
            status = itemView.findViewById(R.id.incoming_image);
            viewPager = itemView.findViewById(R.id.viewPagerTips);
            sliderDots = itemView.findViewById(R.id.sliderDots);
            dotsCount = pagerAdapter.getCount();

        }
    }
}

1 Ответ

0 голосов
/ 27 ноября 2018

Пожалуйста, попробуйте создать один другой список массивов для адаптера вашего пейджера:

ArrayList<Home_Model_ViewPager> tempList = new ArrayList<>();
for(int k=0;k<viewpagerData.size();k++){
        Home_Model_ViewPager object = viewPagerData.get(k);
        if(object.getTripDesc()!=null && object.getTripDesc().length() >0){
            tempList.add(object);
        }
}
ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getActivity(), tempList);
home_recycler.setAdapter(adapter);
adapter.notifyDataSetChanged();
...