I have a viewpager which has five tab and control the tab with tablayout. the problem that i have is that the title doesn't change when want to go from one activity to another activity. the thing that i do is that i changed the textview title in tablayout in onTabSelected in the activity but in both on select tab and in on reselect tab method but sometimes it doesn't change anymore.
another thing that makes the point is the map which i use the address of the map in my main activity title. i changed the address using setOnCameraChangeListener method and the problem with this case is that it run several time even when i am in another fragment and because i used it's address in my main activity title it change it.
at he also changed the title in both onViewCreate and onCreateView in each fragment but it doesn't work fine.
this is what everything that i did:
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));
}
and this is what everything that i do in the first tab which have product address that i use it in my title and also show the current location on the map.
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
}
An easier approach would be to use an EventBus
. Which allows publish-subscribe-style communication between components without requiring the components to explicitly register with one another (and thus be aware of each other). It is designed exclusively to replace traditional Java in-process event distribution using explicit registration. In order to use EventBus
in Android, inside your gradle(app level) add:
compile 'org.greenrobot:eventbus:3.0.0'
Now you'll need to create an Event
. An event is just an object that is posted from the sender on the bus and will be delivered to any receiver class subscribing to the same event type. That's it!. So for this purpose we'll create a sample Event
class:
public class HelloWorldEvent {
private final String message;
public HelloWorldEvent(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
Now the next step is to create a Sender
. Which allows you to post any event from any part of your whole Android application. So in your case you can send from Fragments, viewpager,etc . This is how you do it:
EventBus.getDefault().post(new HelloWorldEvent("Hello EventBus!”);
So this sends a new event
, however in order to receive this, you'll need someone to receive it. So in order to listen from any activity, say from your activity class, at first you'll need to register it:
EventBus.getDefault().register(this);
Then inside that class define a new method :
// 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();
}
So, what happens is whenever an Event
is sent, it will be received by the receiver
. So You can create one Event
and add multiple listeners to it. And it will work fine, as shown in the below image:
More info on the EventBus
library is available here:
A simpler tutorial on EventBus
is available here:
来源:https://stackoverflow.com/questions/41952254/how-to-control-modify-the-activity-textview-from-viewpager-fragment