在android中动态创建标签

时间:2017-02-16 06:16:53

标签: java android json for-loop android-tablayout

嗨朋友们请帮帮我。我被困在这里超过2天,我不明白这里的错误是什么。我的问题是,我正在创建带有基于JSON数据的图标的选项卡,问题是图标即将到来,但是当片段中的剩余数据加载时它们就消失了。但是当我移除适配器时,图标即将到来,它们是在这里看到我发现了一个错误,当我评论这一行 sticker_tab.setupWithViewPager(sticker_pager); 然后一切正常,但无法根据viewpager更改或反之亦然移动选项卡 这是我的代码:

ChatHistory.java

public class ChatHistory extends AppCompatActivity {
@BindView(R.id.chat_his_list)
ListView chat_his_list;
@BindView(R.id.chat_his_toolbar)
Toolbar chat_his_toolbar;
@BindView(R.id.sendmsg)
EmojiconEditText sendmsg;
OkHttpClient chatclient = new OkHttpClient();
public static final String BroadCastAction = "chat";
BroadcastReceiver chatreceiver;
ArrayList<Chat_Pojo> chatlist = new ArrayList<>();
Chat_History_Adapter chat_history_adapter;
@BindView(R.id.smiley)
ImageView smiley;
EmojIconActions emojIcon;
@BindView(R.id.mainviewgroup)
RelativeLayout mainviewgroup;
@BindView(R.id.goondate)
Button goondate;
@BindView(R.id.buyagift_layout)
LinearLayout buyagift_layout;
boolean buyagiftclicked = false;
@BindView(R.id.sticker_tab)
TabLayout sticker_tab;
@BindView(R.id.sticker_pager)
ViewPager sticker_pager;
Chat_Sticker_Adapter chat_sticker_adapter;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat_history);
    ButterKnife.bind(this);
    setSupportActionBar(chat_his_toolbar);
    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
    chat_history_adapter = new Chat_History_Adapter(ChatHistory.this, chatlist);
    chat_his_list.setStackFromBottom(true);
    chat_his_list.setTranscriptMode(chat_his_list.TRANSCRIPT_MODE_NORMAL);
    chat_his_list.setAdapter(chat_history_adapter);
    emojIcon = new EmojIconActions(this, mainviewgroup, sendmsg, smiley);
    emojIcon.setIconsIds(R.mipmap.keyboard_chat, R.mipmap.smiley_chat);
    Session.pushnotification(getApplicationContext());
    stickermethd();
    emojIcon.setKeyboardListener(new EmojIconActions.KeyboardListener() {
        @Override
        public void onKeyboardOpen() {
            Constant.l("Open");
        }

        @Override
        public void onKeyboardClose() {
            emojIcon.closeEmojIcon();
            Constant.l("Close");
        }
    });
    emojIcon.ShowEmojIcon();
    if (getIntent().hasExtra("mtype")) {
        if (getIntent().hasExtra("popup")) {
            gondatepopup(getIntent().getStringExtra("oppusername").replace("$", " "), getIntent().getStringExtra("profileimg"));
        }
        chathistory(Session.getUserID(getApplicationContext()), getIntent().getStringExtra("oid"));
        getSupportActionBar().setTitle(getIntent().getStringExtra("oppusername").replace("$", " "));
        Session.oppuserimg(getApplicationContext(), getIntent().getStringExtra("profileimg"));
    } else {
        chathistory(Session.getUserID(getApplicationContext()), getIntent().getStringExtra("oid"));
        getSupportActionBar().setTitle(getIntent().getStringExtra("oppusername").replace("$", " "));
    }
    chat_his_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (chatlist.get(position).getType().equals("image")) {
                Intent chatimageintent = new Intent(getApplicationContext(), Chat_Image.class);
                chatimageintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                chatimageintent.putExtra("chatimage", chatlist.get(position).getMessage());
                startActivity(chatimageintent);
            }

        }
    });


    chatreceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            if (intent.getStringExtra("msg").equals("gondate")) {
                gondatepopup(getIntent().getStringExtra("oppusername").replace("$", " "), Session.getoppuserimg(getApplicationContext()).replace(",", ""));
            } else if (intent.getStringExtra("msg").equals("Your Go on date Rejected")) {
                goondate.setVisibility(View.VISIBLE);
            } else {
                chat_history_adapter.addmsg(intent.getStringExtra("sid"), intent.getStringExtra("msg"), intent.getStringExtra("type"));
            }

        }
    };
    IntentFilter intfil = new IntentFilter(BroadCastAction);
    registerReceiver(chatreceiver, intfil);
    /*buyagift_layout.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Constant.getScreenWidth(getApplicationContext()) / 4));*/


}

private void gondatepopup(String username, String userimage) {
    goondate.setVisibility(View.GONE);
    final Dialog gondatadialog = new Dialog(ChatHistory.this);
    gondatadialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    gondatadialog.setContentView(R.layout.gondate_dialog);
    gondatadialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    gondatadialog.setCancelable(false);
    TextView name = (TextView) gondatadialog.findViewById(R.id.name);
    name.setText(username);
    CircleImageView profile_image = (CircleImageView) gondatadialog.findViewById(R.id.profile_image);
    Glide.with(getApplicationContext()).load(userimage).into(profile_image);
    FancyButton accept = (FancyButton) gondatadialog.findViewById(R.id.accept);
    accept.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gondatadialog.dismiss();
            acceptdialog();
            gondatedisplay();
        }
    });
    FancyButton decline = (FancyButton) gondatadialog.findViewById(R.id.decline);
    decline.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            goondate.setVisibility(View.VISIBLE);
            sendmsgmethod("Your Go on date Rejected");
            gondatadialog.dismiss();
        }
    });
    gondatadialog.show();

}

@OnClick(R.id.gift)
public void gift() {
    if (!buyagiftclicked) {
        buyagiftclicked = true;
        buyagift_layout.setVisibility(View.VISIBLE);
    } else {
        buyagiftclicked = false;
        buyagift_layout.setVisibility(View.GONE);
    }
}

private void chathistory(String senderid, String receiverid) {
    Constant.showloader(ChatHistory.this);
    HttpUrl.Builder chthisurl = HttpUrl.parse(url + "chat&task=getchat").newBuilder();
    chthisurl.addQueryParameter("sender_id", senderid);
    chthisurl.addQueryParameter("reciever_id", receiverid);
    Request chathistoryreq = new Request.Builder().url(chthisurl.build().toString()).build();
    Constant.l(chthisurl.build().toString());
    chatclient.newCall(chathistoryreq).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Constant.l(e.toString());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            if (response.isSuccessful()) {
                try {
                    final JSONObject chathisobj = new JSONObject(response.body().string());
                    JSONArray chathisarray = chathisobj.getJSONArray("text");
                    for (int i = 0; i < chathisarray.length(); i++) {
                        JSONObject chathisarrayobj = chathisarray.getJSONObject(i);
                        final Chat_Pojo chat_pojo = new Chat_Pojo();
                        chat_pojo.setMessage(chathisarrayobj.getString("message"));
                        chat_pojo.setRid(chathisarrayobj.getString("rid"));
                        chat_pojo.setSid(chathisarrayobj.getString("sid"));
                        chat_pojo.setType(chathisarrayobj.getString("type"));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (chathisobj.has("godate")) {
                                    goondate.setVisibility(View.GONE);
                                }
                                chatlist.add(chat_pojo);
                                chat_history_adapter.notifyDataSetChanged();
                            }
                        });
                    }
                } catch (JSONException e) {
                    Constant.l(e.toString());
                }
                Constant.dismissloader();
            }
        }
    });
}

@Override
public void onBackPressed() {
    Session.removepushnotification(getApplicationContext());
    Intent chathistoryintent = new Intent(getApplicationContext(), Main_Screen.class);
    chathistoryintent.putExtra("chathis", "chathis");
    startActivity(chathistoryintent);
}

@Override
protected void onPause() {
    super.onPause();
    Session.removepushnotification(getApplicationContext());
}

@Override
protected void onStop() {
    super.onStop();
    Session.removepushnotification(getApplicationContext());
}

@Override
protected void onResume() {
    super.onResume();
    Session.pushnotification(getApplicationContext());
}

@OnClick(R.id.goondate)
public void goondate() {
    Request sendmsgreq = new Request.Builder().url(url + "godate&task=send&sender_id=" + Session.getUserID(getApplicationContext()) + "&reciever_id=" + getIntent().getStringExtra("oid")).build();
    chatclient.newCall(sendmsgreq).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Constant.l(e.toString());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Constant.l(response.toString());
            try {
                JSONObject sendobj = new JSONObject(response.body().string());
                if (sendobj.getString("status").equals("Success")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            goondate.setVisibility(View.GONE);
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
}

@Override
protected void onDestroy() {
    unregisterReceiver(chatreceiver);
    super.onDestroy();

}

private void acceptdialog() {
    final Dialog gondateacceptdialog = new Dialog(ChatHistory.this);
    gondateacceptdialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    gondateacceptdialog.setContentView(R.layout.gondate_accept);
    gondateacceptdialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    gondateacceptdialog.setCancelable(false);
    RecyclerView accept_list = (RecyclerView) gondateacceptdialog.findViewById(R.id.accept_list);
    accept_list.setLayoutManager(new LinearLayoutManager(ChatHistory.this, LinearLayoutManager.VERTICAL, false));
    final FastItemAdapter<GonDate_Accept_Adapter> gonacceptadapter = new FastItemAdapter<>();
    accept_list.setAdapter(gonacceptadapter);
    Request acceptrequest = new Request.Builder().url(url + "godatelist").build();
    chatclient.newCall(acceptrequest).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Constant.l(e.toString());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try {
                JSONObject acceptjsonobj = new JSONObject(response.body().string());
                JSONArray acceptarray = acceptjsonobj.getJSONArray("list");
                for (int i = 0; i < acceptarray.length(); i++) {
                    JSONObject acceptobjarray = acceptarray.getJSONObject(i);
                    Gson acceptgson = new Gson();
                    final GonDate_Accept_Adapter goacceptadapter = acceptgson.fromJson(String.valueOf(acceptobjarray), GonDate_Accept_Adapter.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            gonacceptadapter.add(goacceptadapter);
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    });
    gonacceptadapter.withOnClickListener(new FastAdapter.OnClickListener<GonDate_Accept_Adapter>() {
        @Override
        public boolean onClick(View v, IAdapter<GonDate_Accept_Adapter> adapter, GonDate_Accept_Adapter item, int position) {
            sendmsgmethod(item.getAceepttype());
            gondateacceptdialog.dismiss();
            return true;
        }
    });
    gondateacceptdialog.show();

}

@OnClick(R.id.attachment)
public void attachment() {
    TedBottomPicker bottomSheetDialogFragment = new TedBottomPicker.Builder(ChatHistory.this)
            .setOnImageSelectedListener(new TedBottomPicker.OnImageSelectedListener() {
                @Override
                public void onImageSelected(Uri uri) {
                    try {
                        Bitmap attachbitmap = MediaStore.Images.Media.getBitmap(ChatHistory.this.getContentResolver(), uri);
                        attach(attachbitmap);
                    } catch (IOException e) {
                        Constant.l(e.toString());
                    }
                }
            })
            .setPeekHeight(getResources().getDisplayMetrics().heightPixels / 2)
            .create();

    bottomSheetDialogFragment.show(getSupportFragmentManager());
}


@OnClick(R.id.smiley)
public void smiley() {
    emojIcon.ShowEmojIcon();
}

public String getStringImage(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    byte[] imagebytes = baos.toByteArray();
    String uploadencodedImage = Base64.encodeToString(imagebytes, Base64.DEFAULT);
    return uploadencodedImage;
}

private void attach(Bitmap bitmapimage) {
    Constant.showloader(ChatHistory.this);
    RequestBody formbody = new FormBody.Builder().add("document1", getStringImage(bitmapimage)).build();
    Request attachrequest = new Request.Builder().url(url + "chatdocument&task=send&sender_id=" + Session.getUserID(getApplicationContext()) + "&reciever_id=" + getIntent().getStringExtra("oid")).post(formbody).build();
    chatclient.newCall(attachrequest).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Constant.l(e.toString());
            Constant.dismissloader();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try {
                final JSONObject attachobj = new JSONObject(response.body().string());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            chat_history_adapter.addmsg(Session.getUserID(getApplicationContext()), attachobj.getString("url"), "image");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }

            Constant.dismissloader();
        }
    });
}


@OnClick(R.id.send)
public void send() {
    if (sendmsg.getText().toString().isEmpty()) {
        Constant.t(getApplicationContext(), "Please type message");
    } else {
        String msg = sendmsg.getText().toString();
        sendmsgmethod(msg);
    }

}

private void gondatedisplay() {
    Constant.showloader(ChatHistory.this);
    Request gonreqstatus = new Request.Builder().url(url + "changestatus&sender_id=" + Session.getUserID(getApplicationContext()) + "&reciever_id=" + getIntent().getStringExtra("oid") + "&status=0").build();
    chatclient.newCall(gonreqstatus).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Constant.l(e.toString());
            Constant.dismissloader();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Constant.l(response.body().string());
            Constant.dismissloader();
        }
    });
}

private void sendmsgmethod(final String sendsmsg) {
    chat_his_list.setSelection(chat_history_adapter.getCount() - 1);
    String message = StringEscapeUtils.escapeJava(sendsmsg);
    message = message.replace("\\", "$");
    Request sendmsgreq = new Request.Builder().url(url + "chat&task=send&sender_id=" + Session.getUserID(getApplicationContext()) + "&reciever_id=" + getIntent().getStringExtra("oid") + "&message=" + message).build();
    chatclient.newCall(sendmsgreq).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Constant.l(e.toString());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Constant.l(response.toString());
            try {
                JSONObject sendobj = new JSONObject(response.body().string());
                if (sendobj.getString("status").equals("Success")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            chat_history_adapter.addmsg(Session.getUserID(getApplicationContext()), sendsmsg, "text");
                            sendmsg.setText("");
                        }
                    });
                }
            } catch (JSONException e) {
                Constant.l(e.toString());
            }
        }
    });
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Session.removepushnotification(getApplicationContext());
            Intent chathistoryintent = new Intent(getApplicationContext(), Main_Screen.class);
            chathistoryintent.putExtra("chathis", "chathis");
            startActivity(chathistoryintent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

private void stickermethd() {
    Request stickerrequest = new Request.Builder().url(url + "gifts&facebook_id=" + Session.getUserID(getApplicationContext())).build();
    Constant.l(url + "gifts&facebook_id=" + Session.getUserID(getApplicationContext()));
    chatclient.newCall(stickerrequest).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Constant.l(e.toString());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try {
                JSONObject startobj = new JSONObject(response.body().string());
                JSONObject giftobj = startobj.getJSONObject("giftcategories");
                final JSONArray giftarray = giftobj.getJSONArray("giftmenu");
                for (int i = 0; i < giftarray.length(); i++) {
                    JSONObject gigtarrayboj=giftarray.getJSONObject(i);
                    InputStream is = (InputStream) new URL(gigtarrayboj.getString("giftcatimage")).getContent();
                    Constant.l(giftarray.getJSONObject(i).getString("giftcatimage"));
                    final Drawable d = Drawable.createFromStream(is, "caticon");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                sticker_tab.addTab(sticker_tab.newTab().setIcon(d));
                                Constant.l("Tab Count===>" + String.valueOf(sticker_tab.getTabCount()));
                            } catch (Exception e) {
                                Constant.l(e.toString());
                            }

                        }
                    });
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        chat_sticker_adapter = new Chat_Sticker_Adapter(getSupportFragmentManager(), giftarray);
                        sticker_pager.setAdapter(chat_sticker_adapter);
                        sticker_tab.setupWithViewPager(sticker_pager);
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    });
}

} Chat_Sticker_Adapter.java

public class Chat_Sticker_Adapter extends FragmentPagerAdapter {
    JSONArray jsonArray;

    public Chat_Sticker_Adapter(FragmentManager fm,JSONArray jsonArray) {
        super(fm);
        this.jsonArray = jsonArray;
    }


    @Override
    public Fragment getItem(int position) {
        return Buy_A_Gift_Fragment.getInstance(position);
    }

    @Override
    public int getCount() {
        return jsonArray.length();
    }


    /*public View getTabView(int position) {
        View v = LayoutInflater.from(context).inflate(R.layout.single_tab, null);
        CircleImageView img = (CircleImageView) v.findViewById(R.id.tab_icon);
        try {
            Glide.with(context).load(jsonArray.getJSONObject(position).getString("giftcatimage")).into(img);
            Constant.l(jsonArray.getJSONObject(position).getString("giftcatimage"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return v;
    }*/
}

标签的片段

public class Buy_A_Gift_Fragment extends Fragment {
    @BindView(R.id.buyagift_recyclerview)
    RecyclerView buyagift_recyclerview;
    Buy_a_gift_adapter buyAGiftAdapterFastItemAdapter;
    ArrayList<StickerImage_Icon> stickerarray = new ArrayList<>();


    public Buy_A_Gift_Fragment() {
    }

    public static Fragment getInstance(int position) {
        Buy_A_Gift_Fragment otcFragment = new Buy_A_Gift_Fragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        otcFragment.setArguments(bundle);
        return otcFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.buyagift_frag, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, view);
        buyAGiftAdapterFastItemAdapter = new Buy_a_gift_adapter(getActivity(), stickerarray);
        LinearLayoutManager buygridlayoutmanager = new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
        buyagift_recyclerview.setLayoutManager(buygridlayoutmanager);
        buyagift_recyclerview.setAdapter(buyAGiftAdapterFastItemAdapter);
        stickers();
    }

    private void stickers() {
        stickerarray.clear();
        OkHttpClient stickerclient = new OkHttpClient();
        Request stickerrequets = new Request.Builder().url(Constant.url + "gifts&facebook_id=" + Session.getUserID(getActivity())).build();
        final int position = getArguments().getInt("position", 1);
        stickerclient.newCall(stickerrequets).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Constant.l(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject startobj = new JSONObject(response.body().string());
                    JSONObject giftobj = startobj.getJSONObject("giftcategories");
                    JSONArray giftarray = giftobj.getJSONArray("giftmenu");
                    JSONObject giftobjposition = giftarray.getJSONObject(position);
                    JSONArray stickerarrayobj = giftobjposition.getJSONArray("gifts");
                    for (int j = 0; j < stickerarrayobj.length(); j++) {
                        JSONObject stickergiftimg = stickerarrayobj.getJSONObject(j);
                        StickerImage_Icon stickerImage = new StickerImage_Icon();
                        stickerImage.setSticker_iconimage(stickergiftimg.getString("image"));
                        stickerarray.add(stickerImage);
                    }

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            buyAGiftAdapterFastItemAdapter.notifyDataSetChanged();
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }
}

片段适配器

public class Buy_a_gift_adapter extends RecyclerView.Adapter<Buy_a_gift_adapter.Buyagift_viewholder> {
    Context context;
    ArrayList<StickerImage_Icon> stickerImages;

    public Buy_a_gift_adapter(Context context, ArrayList<StickerImage_Icon> stickerImages) {
        this.context = context;
        this.stickerImages = stickerImages;
    }

    @Override
    public Buyagift_viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
        View buyagiftview = LayoutInflater.from(context).inflate(R.layout.buy_a_gift_item, parent, false);
        return new Buyagift_viewholder(buyagiftview);
    }

    @Override
    public void onBindViewHolder(Buyagift_viewholder holder, int position) {
        StickerImage_Icon stickerImage = stickerImages.get(position);
        Glide.with(context).load(stickerImage.getSticker_iconimage()).into(holder.buy_image);
    }

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

    public static class Buyagift_viewholder extends RecyclerView.ViewHolder {
        @BindView(R.id.buy_image)
        ImageView buy_image;

        public Buyagift_viewholder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Constant.l("Clicked");
                }
            });
        }
    }

}

3 个答案:

答案 0 :(得分:2)

根据viewpager更改标签:

 viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
       tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    viewPager.setCurrentItem(tab.getPosition());

                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {

                }

                @Override
                public void onTabReselected(TabLayout.Tab tab) {

                }
            });

答案 1 :(得分:1)

rendering

答案 2 :(得分:1)

遵循此ViewPager实施,您可以动态创建标签:

viewPager = (ViewPager) view.findViewById(R.id.viewPager);

//adapter view
androidAdapter = new ViewPagerAdapter(getFragmentManager());
viewPager.setAdapter(androidAdapter);
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int tabposition) {
            tabHost.setSelectedNavigationItem(tabposition);
        }
    });

//        role = 1; //admin
//        role = 2; //master
        role = 3; //student

// Creating Dynamic TAB
    switch (role){
        case 1:
            break;
        case 2:
            // MASTERLOGIN
            tabHost.addTab(tabHost.newTab().setText("Slot History").setTabListener(this));
            tabHost.addTab(tabHost.newTab().setText("Create Template").setTabListener(this));
            tabHost.addTab(tabHost.newTab().setText("Scheduled").setTabListener(this));
            tabHost.setSelectedNavigationItem(1);
            viewPager.setCurrentItem(1);
            //--MASTERLOGIN
            break;
        case 3:
            //STUDENTLOGIN
            tabHost.addTab(tabHost.newTab().setText("Products").setTabListener(this));
            tabHost.addTab(tabHost.newTab().setText("Book A Slot").setTabListener(this));
            tabHost.addTab(tabHost.newTab().setText("Scheduled").setTabListener(this));
            tabHost.setSelectedNavigationItem(1);
            viewPager.setCurrentItem(1);
            //--STUDENT LOGIN
            break;
        default:
            break;
    }