在tablayout viewpager中运行调整选项卡片段

问题描述 投票:1回答:1

我已经在其中实现了tablayout和view-pager。根据tab和view-pager视图显示正确,

但问题是,当我滑动或选择标签时,它也会调整选项卡代码,并在第一个标签中有警报对话框,当我选择第三个然后第二个时,第一个标签的警告对话框也显示在第二个标签中

这是我的代码

onefragement


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup containe,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_one, containe, false);
    nxt_followup = (EditText) view.findViewById(R.id.nextfollowup);
    img1 = (ImageView) view.findViewById(R.id.img1);
    img2 = (ImageView) view.findViewById(R.id.img2);
    img3 = (ImageView) view.findViewById(R.id.img3);
    sign = (TextView) view.findViewById(R.id.sign);
    issign = (ImageView) view.findViewById(R.id.ifsign);
    add = (EditText) view.findViewById(R.id.address);
    rg = (RadioGroup) view.findViewById(R.id.rg_isreg);
    rb_yes = (RadioButton) view.findViewById(R.id.rb_yes);
    rb_no = (RadioButton) view.findViewById(R.id.rb_no);
    cd = new ConnectionDetector(getActivity());
        //        tvsw=(TextView)view.findViewById(R.id.tvsw);
        //        handler = new Handler();
        //        StartTime = SystemClock.uptimeMillis();
        //        handler.postDelayed(runnable, 0);

        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                selectId = rg.getCheckedRadioButtonId();
                rb = (RadioButton) group.findViewById(checkedId);
                Str = rb.getText().toString();
                Log.d("RadioID", String.valueOf(checkedId));
                if (Str.contains("Yes")) {

                }
                if (Str.equals("No")) {


                    new android.app.AlertDialog.Builder(getActivity()).setTitle("Registration")
                            .setMessage("Do u want to make new Registration ?")
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    reg_dialog = new Dialog(getActivity());
                                    reg_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

                                    reg_dialog.setContentView(R.layout.reg_dialog);
                                    final RadioGroup utype = (RadioGroup) reg_dialog.findViewById(R.id.rg_signup);
                                    Button submit = (Button) reg_dialog.findViewById(R.id.btn_proceed);

                                    uname = (EditText) reg_dialog.findViewById(R.id.et_fullName);
                                    mobile = (EditText) reg_dialog.findViewById(R.id.et_mobile);
                                    email = (EditText) reg_dialog.findViewById(R.id.et_signUp_email);
                                    pwd = (EditText) reg_dialog.findViewById(R.id.et_pwd);
                                    repwd = (EditText) reg_dialog.findViewById(R.id.et_repass);
                                    ref_code = (EditText) reg_dialog.findViewById(R.id.et_referral);

                                    submit.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            int selectId = utype.getCheckedRadioButtonId();
                                            rb = (RadioButton) reg_dialog.findViewById(selectId);
                                            user = rb.getText().toString();
                                            strEmail = email.getText().toString();
                                            strMobile = mobile.getText().toString();
                                            boolean b = isValidEmail(strEmail);

                                            if (uname.getText().toString().equalsIgnoreCase("") |
                                                    email.getText().toString().equalsIgnoreCase("") |
                                                    pwd.getText().toString().equalsIgnoreCase("") |
                                                    repwd.getText().toString().equalsIgnoreCase("") |
                                                    mobile.getText().toString().equalsIgnoreCase("")) {
                                                Toast.makeText(getActivity(), "Please fill Complete form", Toast.LENGTH_SHORT).show();
                                            } else {
                                                if (pwd.getText().toString().equals(repwd.getText().toString())) {


                                                    if (b == true) {

                                                        if (strMobile.matches(mobilePattern)) {
                                                            if (ref_code.getText().toString().equalsIgnoreCase("")) {
                                                                ReferralCodeAlert();
                                                            } else {
                                                                isInternetPresent = cd.isConnectingToInternet();
                                                                if (isInternetPresent) {
                                                                    new HttpAsyncTask().execute("https://eprintpost.com/AndroidServlets/SignUpReg");
                                                                } else {
                                                                    Toast.makeText(getActivity(), "Please check internet connection", Toast.LENGTH_LONG).show();

                                                                }
                                                            }
                                                        } else {
                                                            mobile.setError("Enter Valid Mobile Number");
                                                        }

                                                    } else {
                                                        email.setError("Enter Valid Email");

                                                    }
                                                } else {

                                                    repwd.setError("Password not match");

                                                }
                                            }
                                        }
                                    });
                                    reg_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                        @Override
                                        public void onDismiss(final DialogInterface arg0) {
                                            Str = "";
                                        }
                                    });

                                    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
                                    lp.copyFrom(reg_dialog.getWindow().getAttributes());
                                    lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                                    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                                    lp.gravity = Gravity.CENTER;

                                    reg_dialog.getWindow().setAttributes(lp);

                                    reg_dialog.show();
                                }
                            }).setNegativeButton("No", null).show();


                }
            }

            private void ReferralCodeAlert() {
                new android.app.AlertDialog.Builder(getActivity()).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Alert")
                        .setMessage("Are you sure want to proceed without entering referral code?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                isInternetPresent = cd.isConnectingToInternet();
                                if (isInternetPresent) {
                                    new HttpAsyncTask().execute("https://eprintpost.com/AndroidServlets/SignUpReg");
                                } else {
                                    Toast.makeText(getActivity(), "Please check internet connection", Toast.LENGTH_LONG).show();

                                }


                            }
                        }).setNegativeButton("No", null).show();
            }

            public boolean isValidEmail(CharSequence target) {
                if (target == null) {
                    return false;
                } else {
                    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
                }
            }

        });

    final LocationManager manager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER))

    {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("GPS Is Disabled.Please Turn it ON")
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();

                    }
                });
        AlertDialog alert = builder.create();
        alert.show();


    } else {
        locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);

        location = locationManager.getLastKnownLocation(bestProvider);
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);

        if (location != null) {
            Log.v("Abhijit", "" + location.getLatitude() + "longgg" + location.getLongitude());
            Geocoder geocoder;
            List<Address> addresses = null;
            geocoder = new Geocoder(getActivity(), Locale.getDefault());

            try {
                addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

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

            if (addresses.get(0).getMaxAddressLineIndex() != 0)

                for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++) {
                    addline += " " + addresses.get(0).getAddressLine(i);
                }
            add.setText("" + addline);
        }
        //            String address = addresses.get(0).getAddressLine(0);
        //            // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        //            String city = addresses.get(0).getLocality();
        //            String state = addresses.get(0).getAdminArea();
        //            String country = addresses.get(0).getCountryName();
        //            String postalCode = addresses.get(0).getPostalCode();
        //            String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

    }
    tempDir = new File(Environment.getExternalStorageDirectory() + File.separator + ".Marketing");
    if (tempDir.exists())
        deleteDir(tempDir);
    if (tempDir.mkdir()) {
        signi = new File(tempDir.getAbsolutePath() + File.separator + "sign.png");
    }


    sign.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sign_dialog = new Dialog(getActivity());
            sign_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            sign_dialog.setContentView(R.layout.signature_dialog);
            sign_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(final DialogInterface arg0) {
                    if (signi.exists()) {
                        issign.setVisibility(View.VISIBLE);

                    }
                }
            });

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(sign_dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            lp.gravity = Gravity.CENTER;

            sign_dialog.getWindow().setAttributes(lp);
            mContent = (LinearLayout) sign_dialog.findViewById(R.id.linearLayout);
            mView = mContent;

            Button clear = (Button) sign_dialog.findViewById(R.id.clear);
            Button get_sign = (Button) sign_dialog.findViewById(R.id.sign_get);

            mSignature = new signature1(getActivity(), null);
            mSignature.setBackgroundColor(Color.WHITE);
            mContent.addView(mSignature, LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
            get_sign.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mView.setDrawingCacheEnabled(true);
                    mSignature.save(mView);
                    sign_dialog.dismiss();

                }
            });
            clear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mSignature.clear();

                }
            });

            sign_dialog.show();

        }
    });

    img1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, 1);

        }
    });

    img2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, 2);

        }
    });

    img3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, 3);

        }
    });
    nxt_followup.setClickable(true);
    nxt_followup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Calendar now = Calendar.getInstance();
            //display date picker dialog
            DatePickerDialog dpd = DatePickerDialog.newInstance(
                    OneFragment.this,
                    now.get(Calendar.YEAR),//current year
                    now.get(Calendar.MONTH),//current month
                    now.get(Calendar.DAY_OF_MONTH)//current date
            );
            dpd.setMinDate(now);

            //set the theme
            dpd.setThemeDark(false);
            //vibrate on open
            dpd.vibrate(true);
            dpd.setAccentColor(Color.parseColor("#ff4081"));
            dpd.dismissOnPause(false);
            dpd.show(getActivity().getFragmentManager(), "Follow Date");
        }
    });

    return view;
}

这是我的主要活动代码,我用tablayout设置viewpager

main activity.Java

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
private TabLayout tabLayout;
private ViewPager viewPager;
AppBarLayout ab;
private int[] tabIcons = {
        R.mipmap.ic_tab_contacts,
        R.mipmap.ic_tab_call,
        R.mipmap.ic_tab_report,
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    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);
    Log.v("Abhijit", "" + MainActivity.this.getResources().getConfiguration().orientation);
    toggle.syncState();
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setItemIconTintList(null);

    navigationView.setNavigationItemSelectedListener(this);
    ab = (AppBarLayout) findViewById(R.id.aaa);
    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();
    int tabIconColor = ContextCompat.getColor(MainActivity.this, R.color.yellow);
    tabLayout.getTabAt(0).getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
    tabLayout.setTabTextColors(Color.parseColor("#FFFFFF"), Color.parseColor("#FF9800"));
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            Log.e("abhijjit", String.valueOf(tab.getPosition()));
            int tabIconColor = ContextCompat.getColor(MainActivity.this, R.color.yellow);
            tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);
            tabLayout.setTabTextColors(Color.parseColor("#FFFFFF"), Color.parseColor("#FF9800"));


        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            int tabIconColor = ContextCompat.getColor(MainActivity.this, R.color.white);
            tab.getIcon().setColorFilter(tabIconColor, PorterDuff.Mode.SRC_IN);

        }

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

        }
    });
}

@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 onOptionsItemSelected(MenuItem item) {

    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_new) {
        // Handle the camera action
        viewPager.setCurrentItem(0);
    } else if (id == R.id.nav_existing) {
        viewPager.setCurrentItem(1);
    } else if (id == R.id.nav_report) {
        viewPager.setCurrentItem(2);

    } else if (id == R.id.nav_share) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey share successful");
        sendIntent.setType("text/plain");
        startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.app_name)));

    }

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

private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    tabLayout.getTabAt(2).setIcon(tabIcons[2]);

}


private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new OneFragment(), "New");
    adapter.addFragment(new TwoFragment(), "Existing");
    adapter.addFragment(new ThreeFragment(), "Reports");
    viewPager.setAdapter(adapter);


}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

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

    public void addFragment(Fragment fragment, String title) {

        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

}

如何克服不要从另一个tab中的其他选项卡执行代码。我只想运行哪个选项卡可见的代码

android android-viewpager android-tablayout
1个回答
0
投票

用这个。

viewPager.setOffscreenPageLimit(0) 

这将停止加载页面。

© www.soinside.com 2019 - 2024. All rights reserved.