如何从viewpager片段

时间:2017-01-31 07:48:58

标签: android android-fragments android-viewpager google-maps-android-api-2

enter image description here 我有一个viewpager,它有五个选项卡,并使用tablayout控制选项卡。我遇到的问题是,当想要从一个活动转到另一个活动时,标题不会改变。我做的是我在活动中的onTabSelected中改变了tablayout中的textview标题,但是在select选项卡和reselect tab方法中都改变了,但有时它不再改变。 另一件事就是我在主要活动标题中使用地图地址的地图。我使用setOnCameraChangeListener方法更改了地址,这种情况的问题是它运行了几次,即使我在另一个片段中,因为我在我的主要活动标题中使用了它的地址,它会改变它。

他还在每个片段中更改了onViewCreate和onCreateView中的标题,但它不能正常工作。

这就是我所做的一切:

public class MainPageActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    public Context context;
    public Typeface tf;
    public LinearLayout linearLayout;
    public static boolean a=false;
    private CustomViewPager viewPager;
    private int[] tabIcons = {
            R.drawable.home,
            R.drawable.ic_tab_montakhab,
            R.drawable.ic_tab_search,
            R.drawable.ic_tab_issue,
            R.drawable.ic_tab_profile
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page);
         tf = Typeface.createFromAsset(getAssets(), "IRANSans_Bold.ttf");
        context=this;

        TextView google_header_address=(TextView)findViewById(R.id.google_header_address);

        tabCustomization();

        setupTabIcons();

        tabLayout.getTabAt(0).getIcon().setColorFilter(Color.parseColor("#f6fda6"), PorterDuff.Mode.SRC_IN);
        linearLayout=(LinearLayout)tabLayout.getTabAt(0).getCustomView();
        ImageView firstTab=(ImageView)linearLayout.getChildAt(0);
        firstTab.setColorFilter(Color.parseColor("#f6fda6"), PorterDuff.Mode.SRC_IN);


        google_header_address.setText("");


        google_header_address.setVisibility(View.VISIBLE);


    }


    private void tabCustomization() {
        viewPager = (CustomViewPager) findViewById(R.id.viewPager);
        viewPager.setPagingEnabled(false);

        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);

        tabLayout.setupWithViewPager(viewPager);
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        adapter.addFragment(new MenuFragment(), "tab1");

        adapter.addFragment(new AddressFragment(), "tab2");
        adapter.addFragment(new SearchFragment(), "tab3");
        adapter.addFragment(new IssueFragment(), "tab4");
        adapter.addFragment(new ProfileFragment(), "tab5");

        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(5);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);


            tab.setCustomView(adapter.getTabView(tabLayout,i));

        }


        ViewGroup vg = (ViewGroup) tabLayout.getChildAt(0);
        int tabsCount = vg.getChildCount();
        Log.i("TabChild",String.valueOf(tabsCount));


// Iterate over all tabs and set the custom view

    }

    public void setupViewPager(ViewPager viewPager) {

    }
    private void setupTabIcons() {

        tabLayout.getTabAt(0).setIcon(tabIcons[0]);
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);
        tabLayout.getTabAt(3).setIcon(tabIcons[3]);
        tabLayout.getTabAt(4).setIcon(tabIcons[4]);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){


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

                TabChanges(tab);

            }

            private void TabChanges(TabLayout.Tab tab) {
                linearLayout=(LinearLayout)tab.getCustomView();
                ImageView v=(ImageView)linearLayout.getChildAt(0);
                v.setColorFilter(Color.parseColor("#f6fda6"), PorterDuff.Mode.SRC_IN);
                TextView google_header_address=(TextView)findViewById(R.id.google_header_address);


                switch (tab.getPosition())
                {
                    case 0:
                        Log.d("Position", String.valueOf(tab.getPosition()));


                        google_header_address.setVisibility(View.VISIBLE);
                        google_header_address.setText("");

                        ClearFragmentStack();
                        Toast.makeText(context,"title"+String.valueOf((int)getResources().getDimension(R.dimen.text_size_bw_small)),Toast.LENGTH_LONG).show();
                        break;
                    case 1:
                        Log.d("Position", String.valueOf(tab.getPosition()));
                    google_header_address.setText("tab2 title");

                        ClearFragmentStack();



                        Log.i("bwSmall", "title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)));
                        break;
                    case 2:
                        ClearFragmentStack();
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab3 title ");

                        Toast.makeText(context,"title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)),Toast.LENGTH_LONG).show();
                        break;
                    case 3:
                        ClearFragmentStack();
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab4 title");

                        Log.i("bwSmall", "title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)));

                        break;
                    case 4:
                        ClearFragmentStack();
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab5 title");

                        Log.i("bwSmall", "title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)));
                        break;

                }
            }

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

                 linearLayout=(LinearLayout)tab.getCustomView();
                ImageView v=(ImageView)linearLayout.getChildAt(0);
                v.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN);
                TextView google_header_address=(TextView)findViewById(R.id.google_header_address);
                google_header_address.setText("");
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                linearLayout=(LinearLayout)tab.getCustomView();
                ImageView v=(ImageView)linearLayout.getChildAt(0);
                v.setColorFilter(Color.parseColor("#f6fda6"), PorterDuff.Mode.SRC_IN);
                TextView google_header_address=(TextView)findViewById(R.id.google_header_address);

                switch (tab.getPosition())
                {

                    case 0:
                        Log.d("Position", String.valueOf(tab.getPosition()));

                        google_header_address.setVisibility(View.VISIBLE);
                        google_header_address.setText("");

                        ClearFragmentStack();
                        Toast.makeText(context,"title"+String.valueOf((int)getResources().getDimension(R.dimen.text_size_bw_small)),Toast.LENGTH_LONG).show();
                        break;
                    case 1:
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab2 title");

                        ClearFragmentStack();



                        Log.i("bwSmall", "title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)));
                        break;
                    case 2:
                        ClearFragmentStack();
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab3 title");

                        Toast.makeText(context,"title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)),Toast.LENGTH_LONG).show();
                        break;
                    case 3:
                        ClearFragmentStack();
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab4 title");

                        Log.i("bwSmall", "title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)));

                        break;
                    case 4:
                        ClearFragmentStack();
                        Log.d("Position", String.valueOf(tab.getPosition()));
                        google_header_address.setText("tab5 title");

                        Log.i("bwSmall", "title"+String.valueOf((int)getResources().getDimension(R.dimen.mtext_size_button)));
                        break;

                }
            }
        });


    }

    private void ClearFragmentStack() {
        FragmentManager fm = getSupportFragmentManager();
        for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
            fm.popBackStack();
        }
    }

    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);
        }
        public View getCustomView(TabLayout tabLayout,int position){
            View view = LayoutInflater.from(getApplicationContext())
                    .inflate(R.layout.custom_tab, tabLayout, false);
            TextView textView= (TextView) view.findViewById(R.id.tabText);

            textView.setText(getPageTitle(position));
            textView.setTypeface(tf);

            ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
            imageView.setImageResource(tabIcons[position]);

            return view;
        }
        public View getTabView(TabLayout tabLayout,int position) {
            // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView

            View view = LayoutInflater.from(getApplicationContext())
                    .inflate(R.layout.custom_tab, tabLayout, false);
            TextView textView= (TextView) view.findViewById(R.id.tabText);

            textView.setText(getPageTitle(position));
            textView.setTypeface(tf);

            ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
            imageView.setImageResource(tabIcons[position]);

            return view;
        }

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

    }

    //Caligraphy Library
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

这就是我在第一个标签中做的所有内容,我在标题中使用了产品地址,并在地图上显示了当前位置。

public class _step1_mapfragment extends Fragment {


    MapView mMapView;

    private GoogleMap googleMap;
    public static boolean Stop_searcLocation=true;

    public LatLng GetCurrentLocation;

    public ImageView IV_title;
    public ImageView IV_marker;

    private static final int PICK_IMAGE_ID = 234;
    private String FilePath;
    public String FIleName = "images.jpg";

    ImageView Prescription_img;

    // directory name to store captured images and videos


    public _step1_mapfragment() {
        // Required empty public constructor
    }
    Uri file;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView= inflater.inflate(R.layout.fragment__step1_mapfragment, container, false);
        Change_MarkerImage(rootView);
        Control_Map(savedInstanceState,rootView);

        GeocodeAsyncTask AddressTask=new GeocodeAsyncTask(UIHelper.Latitude,
                UIHelper.Logitude);
        AddressTask.execute();


        FilePath=getActivity().getFilesDir().getParentFile().getPath() + "/files/";
        try {
            copyfile(getActivity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        File f = new File(FilePath + FIleName);
        Log.d("FileName:",f.getName());
        Prescription_img= (ImageView) getActivity().findViewById(R.id.prescription);

        ClearFragmentStack();
        fav_GetAddress(rootView);
        return rootView;
    }

    private void ClearFragmentStack() {
        FragmentManager fm = getActivity().getSupportFragmentManager();
        for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
            fm.popBackStack();
        }
    }

    private void Change_MarkerImage(final View rootView) {
        IV_marker = (ImageView) rootView.findViewById(R.id.confirm_address_map_custom_marker);
        IV_title = (ImageView) rootView.findViewById(R.id.Image_title);
        IV_marker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                IV_marker.setImageResource(R.drawable.ic_new_mark_icon);

                IV_title.setVisibility(View.VISIBLE);
            }
        });

        IV_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getActivity(),"Clicked well",Toast.LENGTH_LONG).show();
               /* checksCameraPermission(view);*/
                IV_title.setVisibility(View.GONE);
                TakeImage();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100) {
            if (resultCode == -1) {

                Bundle args=new Bundle();

                // I'll assume this is a Context and bitmap is a Bitmap

                File fileUrl=new File(file.getPath());
                args.putString("image",fileUrl.getAbsolutePath());
                _step2_fragmentconfirm_pic confirmPicFragment=new _step2_fragmentconfirm_pic();
                confirmPicFragment.setArguments(args);
                Toast.makeText(getActivity(),"getting image ready",Toast.LENGTH_LONG).show();
                FragmentTransaction transaction=getFragmentManager().beginTransaction();
                transaction.replace(R.id.root_menu_fragment,confirmPicFragment);
                transaction.addToBackStack("mapView");
                transaction.commit();
                Toast.makeText(getActivity(), "Everything is ok but frag error is the case", Toast.LENGTH_SHORT).show();
            }
        }


    }


    public void copyfile(Context context) throws IOException {

        Log.d("File Path:",FilePath);
        InputStream myInput=context.getAssets().open(FIleName);

        String outFileName=FilePath+FIleName;
        OutputStream myOutPut=new FileOutputStream(outFileName);
        byte[] buffer=new byte[1024];
        int length;
        while ((length=myInput.read(buffer))>0)
        {
            myOutPut.write(buffer,0,length);
        }
        myOutPut.flush();
        myOutPut.close();
        myInput.close();
    }

    private void TakeImage() {

        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(getActivity(), new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        try {


            file = Uri.fromFile(ImagePicker.getTempFile(getActivity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
        startActivityForResult(intent, 100);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == 0) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                TakeImage();
            }
        }

    }






    @Override
    public void onResume() {
        super.onResume();

        Stop_searcLocation=true;
        mMapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();

        mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mMapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();

        mMapView.onLowMemory();
    }

    private void Control_Map(Bundle savedInstanceState, View rootView) {
        mMapView = (MapView) rootView.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);

        mMapView.onResume(); // needed to get the map to display immediately

        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        mMapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap mMap) {


                googleMap = mMap;
                googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                    @Override
                    public void onMapClick(LatLng latLng) {

                    }
                });
                googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
                    @Override
                    public void onCameraChange(CameraPosition cameraPosition) {

                        UIHelper.Latitude=cameraPosition.target.latitude;
                        UIHelper.Logitude=cameraPosition.target.longitude;

                        GeocodeAsyncTask AddressTask=new GeocodeAsyncTask(cameraPosition.target.latitude,
                                cameraPosition.target.longitude);
                        AddressTask.execute();


                    }
                });

                // For showing a move to my location button
                if(ContextCompat.checkSelfPermission(getActivity(),
                        android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED  &&
                        ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)==
                                PackageManager.PERMISSION_GRANTED){
                    googleMap.setMyLocationEnabled(true);
                } else
                {
                    ActivityCompat.requestPermissions(getActivity(),new String[]{
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                    },1);
                }

                // For dropping a marker at a point on the Map

                googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

                    @Override
                    public void onMyLocationChange(Location location) {
                       {
                            Stop_searcLocation=false;
                            GetCurrentLocation = new LatLng(location.getLatitude(), location.getLongitude());
                            Toast.makeText(getActivity(), "Set Location", Toast.LENGTH_SHORT).show();
                            CameraPosition cameraPosition = new CameraPosition.Builder().target(GetCurrentLocation).zoom(18).build();
                            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                        }

                    }


                });


            }
        });
    }





    class GeocodeAsyncTask extends AsyncTask<Void, Void, Address> {
        double strLatitude;
        double strLongitude;
        public GeocodeAsyncTask(double strLatitude, double strLongitude){
            this.strLatitude=strLatitude;
            this.strLongitude=strLongitude;
        }
        String errorMessage = "";

        @Override
        protected void onPreExecute() {


        }

        @Override
        protected Address doInBackground(Void ... none) {
            Log.i("Started","start one");
            Locale.setDefault(new Locale("fa"));
            Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
            List<Address> addresses = null;

            double latitude = strLatitude;
            double longitude = strLongitude;

            try {
                addresses = geocoder.getFromLocation(latitude, longitude, 1);

            } catch (IOException ioException) {
                errorMessage = "Service Not Available";

            } catch (IllegalArgumentException illegalArgumentException) {
                errorMessage = "Invalid Latitude or Longitude Used";

            }


            if(addresses != null && addresses.size() > 0) {
                Log.i("Started", "start two");
                return addresses.get(0);

            }
            return null;
        }

        protected void onPostExecute(Address address) {
            Locale.setDefault(new Locale("fa"));
            Log.i("Started","start three");
            if(address == null) {

            }
            else {
                Log.i("Started","start four");
                String addressName = "";
                for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                    if(i==0)
                        addressName +=  address.getAddressLine(i);
                    else
                        addressName += "،" + address.getAddressLine(i);
                }
                Log.i("Started", String.valueOf(address.getMaxAddressLineIndex()));
            Locale.setDefault(new Locale("fa"));
                UIHelper.setTvText(getActivity(), R.id.google_header_address, addressName);
            }
        }
    }

    public  void fav_GetAddress(View view){
        final Dialog dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        dialog.setContentView(R.layout.alert_dialog_custom);
        dialog.getWindow().setBackgroundDrawableResource(R.drawable.draw_radius_cost_info);
        // set the custom dialog components - text, image and button


        TextView dialogButton = (TextView) dialog.findViewById(R.id.dialogOK);
        // if button is clicked, close the custom dialog
        dialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        LinearLayout imageView=(LinearLayout)view.findViewById(R.id.fav_GetAddress);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show();
            }
        });
// custom dialog

    }

1 个答案:

答案 0 :(得分:1)

更简单的方法是使用EventBus。这允许组件之间的发布 - 订阅式通信,而不需要组件彼此明确地注册(因此彼此了解)。它专门用于使用显式注册替换传统的Java进程内事件分发。要在Android中使用EventBus,请在您的gradle(应用级别)中添加:

compile 'org.greenrobot:eventbus:3.0.0'

现在您需要创建Event。事件只是从总线上的发送方发布的对象,并将被传递给订阅相同事件类型的任何接收方类。那就是它!因此,为此我们将创建一个样本Event类:

    public class HelloWorldEvent {
    private final String message;

    public HelloWorldEvent(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

现在,下一步是创建Sender。这允许您从整个Android应用程序的任何部分发布任何事件。因此,在您的情况下,您可以从Fragments,viewpager等发送。你就是这样做的:

EventBus.getDefault().post(new HelloWorldEvent("Hello EventBus!”);

因此,这会发送一个新的event,但是为了接收此信息,您需要有人接收它。因此,为了从任何活动中聆听,比如从您的活动课开始,首先您需要注册它:

EventBus.getDefault().register(this);

然后在该类中定义一个新方法:

// This method will be called when a HelloWorldEvent is posted
@Subscribe
public void onEvent(HelloWorldEvent event){
  // your implementation
  Toast.makeText(getActivity(), event.getMessage(), Toast.LENGTH_SHORT).show();
}

因此,无论何时发送Event,都会发生receiver。因此,您可以创建一个Event并为其添加多个侦听器。它会正常工作,如下图所示:

enter image description here

EventBus库的更多信息可在此处获取:

EventBus上有一个更简单的教程: