how to not load all tab in FragmentStatePagerAdapter - android

i have a Page adapter that i called in activity,
it have 3 tabs , each tabs call a web service to full fill the ListView. besides, i have a sharedpreference to in every tabs.
the problem is, when i access the page from index, it took me a long time and in the log cat said that "I/Choreographer: Skipped 633 frames! The application may be doing too much work on its main thread."
I assume its because they load the 3 tab at the same time, so the it make the process more hard. is there any way to do load tabs only whenever i clicked that tab ?
page adapter class
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
private Context context;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
MyRequest myReq = new MyRequest();
return myReq;
case 1:
ListApproval myApp = new ListApproval();
return myApp;
case 2:
ListApprovalHistory myAppHis = new ListApprovalHistory();
return myAppHis;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
List Activity :
public class Workflow extends AppCompatActivity{
private static String URLService;
private static final String ARG_SECTION_NUMBER = "section_number";
private static String userId;
private static String DirectSuperiorName;
private static String rowsPerPage;
private static SharedPreferences pref;
boolean _areLecturesLoaded = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workflow_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("My Request"));
tabLayout.addTab(tabLayout.newTab().setText("My Approval"));
tabLayout.addTab(tabLayout.newTab().setText("My Approval History"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setOffscreenPageLimit(0);
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) {
}
});
URLService = getString(R.string.URLService);
getSuperior();
//GET SESSION USERID
pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
userId = pref.getString("userId", "");
rowsPerPage = pref.getString("rowsPerPage","");
DirectSuperiorName = pref.getString("DirectSuperiorName","");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_workflow, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Intent intent = new Intent(this, Index.class);
startActivity(intent);
return true;
case 0:
getSuperior();
if(DirectSuperiorName != "") {
SharedPreferences.Editor editor = pref.edit();
editor.putString("PageType", "NewRequest");
editor.commit();
Intent i = new Intent(Workflow.this, WorkflowActivity.class);
startActivity(i);
}
else
{
AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
builder2.setMessage("Cannot create new request, Please set DirectSuperior !")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder2.create();
builder2.show();
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.add(Menu.NONE,0,0,"Create New").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
/*if(DirectSuperiorName != ""){
menu.add(Menu.NONE,0,0,"Create New").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
}
else{
menu.clear();
}*/
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onBackPressed() {
Intent i = new Intent(this, Index.class);
startActivity(i);
super.onBackPressed();
}
}
this is my fragment child code:
public class ListApproval extends android.support.v4.app.Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private static String userId;
private static String rowsPerPage;
private SwipeRefreshLayout swipeContainer;
private List<ListApprovalItem> mItems;
private ListApprovalItem item;
private static SharedPreferences pref;
private Handler mHandler;
private static String URLService;
private String Enc_Pass="";
private boolean isDataLoaded;
// TODO: Rename and change types of parameters
public static ListApproval newInstance(int sectionNumber) {
ListApproval fragment = new ListApproval();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public ListApproval() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list_approval, container, false);
setHasOptionsMenu(true);
this.mHandler = new Handler();
this.mHandler.postDelayed(getData,500);
URLService = getString(R.string.URLService);
Enc_Pass = getString(R.string.password_encryption);
//GET SESSION USERID
pref = getActivity().getApplicationContext().getSharedPreferences("MyPref", getActivity().MODE_PRIVATE);
userId = pref.getString("userId", "");
rowsPerPage = pref.getString("rowsPerPage","");
final ListView lv = (ListView) view.findViewById(R.id.lvApproval);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
new BigProccess(getActivity(), ProgressDialog.STYLE_SPINNER).execute();
item = new ListApprovalItem();
item = mItems.get(position);
SharedPreferences.Editor editor = pref.edit();
editor.putString("PermitID", item.permitid);
editor.putString("PageType", "MyApproval");
editor.putString("LeaveType", item.tipe);
editor.commit();
Intent i = new Intent(getActivity(), WorkflowActivity.class);
getActivity().startActivity(i);
}
});
getApprovalList(); // i call my api here , when oncreateview start
if (mItems==null)
{
/* Toast.makeText(getActivity().getApplicationContext(), "Internet connection appears to be offline",
Toast.LENGTH_LONG).show();*/
}
else
{
lv.setAdapter(new ListApprovalAdapter(getActivity(), mItems));
}
swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getApprovalList();
if (mItems==null)
{
/* Toast.makeText(getActivity().getApplicationContext(), "Internet connection appears to be offline",
Toast.LENGTH_LONG).show();*/
}
else
{
lv.setAdapter(new ListApprovalAdapter(getActivity(), mItems));
}
swipeContainer.setRefreshing(false);
}
});
return view;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == 0) {
/* SharedPreferences.Editor editor = pref.edit();
editor.putString("PageType", "ApprovalHistory");
editor.commit();
Fragment newFragment = ListApprovalReimbursementHistory.newInstance(6);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.flApproval, newFragment).commit();*/
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
// getActivity().getMenuInflater().inflate(R.menu.index, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
// menu.clear();
// menu.add(Menu.NONE,0,0,"History").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
super.onPrepareOptionsMenu(menu);
}
private final Runnable getData = new Runnable() {
#Override
public void run() {
getApprovalList();
}
};
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
//getListView().setDivider(null);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
}
i am not sure where is the problem,
can you guys help me ?
any help would be appreciate

One way is to override setUserVisibleHint method of Fragment -
Adding piece of code how you should do that,
public class ListApproval extends android.support.v4.app.Fragment {
private boolean isDataLoaded;
public static ListApproval newInstance(int sectionNumber) {
ListApproval fragment = new ListApproval();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list_approval, container, false);
setHasOptionsMenu(true);
// Do your UI related stuffs here...
return view;
}
/*
* Set a hint to the system about whether this fragment's UI is currently visible to the user.
*/
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// isDataLoaded is to prevent multiple calls
if (isVisibleToUser && !isDataLoaded ) {
loadData(); // Make an api call to bind data into your list
isDataLoaded = true;
}
}
}
More about setUserVisibleHint() Click here

Related

How to display only one fragment tab in Android

I have different fragments in my MainActivity. In each fragment I implemented some features.
Now I am trying to implemented tabs for one fragments, what I'm looking for is about hide tab layout in remaining fragments.
activity.xml:
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.genworks.oppm.MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/activity_search_view_check"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include layout="#layout/toolbar"/>
<include layout="#layout/search_toolbar"
android:visibility="gone"/>
</RelativeLayout>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabIndicatorColor="#color/White"
app:tabTextColor="#color/White"
android:background="#drawable/button_background"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:tabGravity="fill"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
Fragment fragment;
int CAMERA_PIC_REQUEST=20;
Menu search_menu;
MenuItem item_search;
ExpandableListView expListView;
TabLayout tabLayout;
private ProgressDialog progressDialog = null;
TextView user,firstname,lastname,mobile,role,report_to;
String user_name;
ImageView profile;
private ArrayList<Records> records;
private ArrayList<Records> recordsList=new ArrayList<>();
ViewPager viewPager;
TextView mTitle;
private RecyclerView recyclerView;
static final int REQUEST_TAKE_PHOTO = 1;
static final int REQUEST_GALLERY_PHOTO = 2;
File mPhotoFile;
FileCompressor mCompressor;
private RecyclerView.Adapter mAdapter;
String sessionId,username,first_name,last_name,mobile_no,role_id,reportto;
MenuItem refreshMenuItem;
ExpandableListView expandableList;
ExpandableListAdapterMenu mMenuAdapter;
List <ExpandedMenuModel> listDataHeader;
private final Handler handler = new Handler ( );
HashMap <ExpandedMenuModel, List <String>> listDataChild;
private RecyclerView.LayoutManager layoutManager;
private boolean ismenutoggle;
private Toolbar searchtollbar,toolbar;
boolean needLogin = false;
LinearLayout dashboard,taskmenu,account,contact,opportunity,logout,documents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sessionId = getIntent().getStringExtra("sessionId");
username = getIntent().getStringExtra("username");
PreferenceUtils.getUsername(this);
PreferenceUtils.getPassword(this);
first_name = getIntent().getStringExtra("firstname");
last_name = getIntent().getStringExtra("lastname");
mobile_no = getIntent().getStringExtra("mobile");
role_id = getIntent().getStringExtra("role");
reportto = getIntent().getStringExtra("reportto");
dashboard=findViewById(R.id.dashboard);
taskmenu=findViewById(R.id.taskmenu);
contact=findViewById(R.id.contactmenu);
opportunity=findViewById(R.id.opportunitymenu);
account=findViewById(R.id.accountmenu);
logout=findViewById(R.id.logout);
// user = (TextView) findViewById(R.id.username);
profile=findViewById(R.id.profile);
mCompressor = new FileCompressor(this);
firstname = (TextView) findViewById(R.id.firstname);
lastname = (TextView) findViewById(R.id.lastname);
mobile=findViewById(R.id.mobile);
role=findViewById(R.id.role);
report_to=findViewById(R.id.report_to);
firstname.setText(first_name);
lastname.setText(last_name);
mobile.setText(mobile_no);
role.setText(role_id);
report_to.setText(reportto);
// user.setText(username);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// getSupportActionBar().setTitle("DASHBOARD");
final ActionBar ab = getSupportActionBar();
ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ab.setCustomView(R.layout.toolbar_spinner);
if (ab != null) {
ab.setDisplayShowTitleEnabled(false);
mTitle = (TextView) findViewById(R.id.toolbar_title);
mTitle.setText("DASHBOARD");
mTitle.setGravity(Gravity.CENTER_HORIZONTAL);
// Typeface typeface = Typeface.createFromAsset(getApplicationContext ().getAssets (), "fonts/astype - Secca Light.otf");
// mTitle.setTypeface (typeface);
}
ab.setHomeAsUpIndicator(R.drawable.menu);
ab.setDisplayHomeAsUpEnabled(true);
//ab.setTitle ("HOME");
setSearchtollbar();
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
fragment = new DashboardFragement();
loadFragment(fragment);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
if (navigationView != null) {
setupDrawerContent (navigationView);
}
// TextView dashboard=findViewById(R.id.menu_dashboard);
dashboard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Dashboard");
fragment = new DashboardFragement();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
// TextView task=findViewById(R.id.menu_task);
taskmenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Task List");
fragment = new TaskFragement();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Account List");
fragment = new AccountFragement();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Contact List");
fragment = new ContactFragment();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
// TextView opportunity=findViewById(R.id.menu_opportunity);
opportunity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Opportunity List");
fragment = new SalesStageFragment();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
// TextView logout=findViewById(R.id.menu_logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences("login", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
finish();
drawerLayout.closeDrawer(GravityCompat.START);
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
initBottomNavigationItems();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TaskFragement(), "All");
adapter.addFragment(new AccountFragement(), "Incomplete");
adapter.addFragment(new ContactFragment(), "Scheduled");
adapter.addFragment(new ContactFragment(), "Today");
adapter.addFragment(new ContactFragment(), "Weekwise");
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);
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Gallery",
"Cancel"};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
MainActivity.this.requestStoragePermission(true);
} else if (items[item].equals("Choose from Gallery")) {
MainActivity.this.requestStoragePermission(false);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void initBottomNavigationItems() {
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.account:
mTitle.setText("ACCOUNT LIST");
fragment = new AccountFragement();
loadFragment(fragment);
return true;
case R.id.task:
mTitle.setText("TASK LIST");
fragment = new TaskFragement();
loadFragment(fragment);
return true;
case R.id.contact:
mTitle.setText("CONTACT LIST");
fragment = new ContactFragment();
loadFragment(fragment);
return true;
case R.id.opportunity:
mTitle.setText("OPPORTUNITY LIST");
fragment = new SalesStageFragment();
loadFragment(fragment);
return true;
}
return false;
}
});
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
menu.findItem(R.id.search).setVisible(false);
return true;
}
private void setupDrawerContent(NavigationView navigationView) {
//revision: this don't works, use setOnChildClickListener() and setOnGroupClickListener() above instead
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if(menuItem.isChecked ()){
drawerLayout.openDrawer (GravityCompat.START);}
else {
drawerLayout.closeDrawer (GravityCompat.START);
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(ismenutoggle==true) {
drawerLayout.openDrawer (GravityCompat.START);
ismenutoggle=false;
}
else{
drawerLayout.closeDrawer (GravityCompat.START);
ismenutoggle=true;
}
return true;
}
return super.onOptionsItemSelected(item);
}
private AdapterView.OnItemClickListener mDrawerItemClickedListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
}
};
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
finish();
}
}
private DrawerLayout.DrawerListener mDrawerListener = new DrawerLayout.DrawerListener () {
#Override
public void onDrawerStateChanged(int status) {
}
#Override
public void onDrawerSlide(View view, float slideArg) {
}
#Override
public void onDrawerOpened(View view) {
drawerLayout.openDrawer (view);
}
#Override
public void onDrawerClosed(View view) {
drawerLayout.closeDrawer (view);
}
};
public void setSearchtollbar()
{
searchtollbar = (Toolbar) findViewById(R.id.searchtoolbar);
if (searchtollbar != null) {
searchtollbar.inflateMenu(R.menu.menu_search);
search_menu=searchtollbar.getMenu();
searchtollbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar,1,true,false);
else
searchtollbar.setVisibility(View.GONE);
}
});
item_search = search_menu.findItem(R.id.action_filter_search);
MenuItemCompat.setOnActionExpandListener(item_search, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
circleReveal(R.id.searchtoolbar,1,true,false);
}
else
searchtollbar.setVisibility(View.GONE);
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true;
}
});
initSearchView();
} else
Log.d("toolbar", "setSearchtollbar: NULL");
}
public void initSearchView()
{
final SearchView searchView = (SearchView) search_menu.findItem(R.id.action_filter_search).getActionView();
// Enable/Disable Submit button in the keyboard
searchView.setSubmitButtonEnabled(false);
// Change search close button image
ImageView closeButton = searchView.findViewById(R.id.search_close_btn);
closeButton.setImageResource(R.drawable.ic_close_black_24dp);
// closeButton.setImageResource(ContextCompat.getDrawable(getApplication(), R.drawable.ic_close_black_24dp));
// set hint and the text colors
EditText txtSearch = ((EditText) searchView.findViewById(R.id.search_src_text));
txtSearch.setHint("Search..");
txtSearch.setHintTextColor(Color.DKGRAY);
txtSearch.setTextColor(getResources().getColor(R.color.colorPrimary));
// set the cursor
AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(R.id.search_src_text);
try {
Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
mCursorDrawableRes.setAccessible(true);
mCursorDrawableRes.set(searchTextView, R.drawable.search_cursor); //This sets the cursor resource ID to 0 or #null which will make it visible on white background
} catch (Exception e) {
e.printStackTrace();
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
callSearch(query);
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
callSearch(newText);
return true;
}
public void callSearch(String query) {
Log.i("query", "" + query);
}
});
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void circleReveal(int viewID, int posFromRight, boolean containsOverflow, final boolean isShow)
{
final View myView = findViewById(viewID);
int width=myView.getWidth();
if(posFromRight>0)
width-=(posFromRight*getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material))-(getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)/ 2);
if(containsOverflow)
width-=getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_overflow_material);
int cx=width;
int cy=myView.getHeight()/2;
Animator anim;
if(isShow)
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0,(float)width);
else
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, (float)width, 0);
anim.setDuration((long)220);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
if(!isShow)
{
super.onAnimationEnd(animation);
myView.setVisibility(View.INVISIBLE);
}
}
});
// make the view visible and start the animation
if(isShow)
myView.setVisibility(View.VISIBLE);
// start the animation
anim.start();
}
public void setActionBarTitle(String title) {
mTitle.setText(title);
}
}
I think you are asking if we can create two tabs and when the user presses any of the tab, same fragment should appear instead of multiple fragments. If that is your question, may be i can help.
You will have to create one class that extends FragmentStateAdapter , then you should create a single class that extends Fragment instead of having multiple classes and a layout.
Create ClassFragmentPagerAdapter like this:
public class ClassFragmentPagerAdapter extends FragmentStateAdapter {
public ClassFragmentPagerAdapter (#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
if (position == 0) {
return new ClassFragment ();
}
return new ClassFragment ();
}
#Override
public int getItemCount() {
return 2;
}
Then after that create the other ClassFragment that extends Fragment:
public class ClassFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.layout_name, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
//do stuff here
}
Hope it helps! Happy coding:)

How to pass data from RecyclerView onItemClick to Activity TabLayout

I have a problem pass or intent data from (activity) to (Fragment) containing 3 (TabLayout ).
How can I transfer data to a specific (TabLayout) of the third that I own.
by RecyclerView onItemClick.
This is code of RecyclerView onItemClick.I was send it From first activity to secand activity like this As follows..
Pass data first activity
public static final String EXTRA_FROM = "FROMPL";
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this,
com.example.myapplication.Fragmant.StatusFragment.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_FROM, clickedItem.getCreator());
startActivity(detailIntent);
}
secand activity get data
Intent i = getIntent();
final String FROMPL = i.getStringExtra("FROMPL");
textfrom.setText(FROMPL);
But now like that not work.I don’t know how I can pass it to a specific (TabLayout)to work as Fragment in (MainActivityFargmain).
I want each (TabLayout) in (MainActivityFargmain) has specific data.
So Anyone have a solution for that؟
all my code
public class MainActivityFargmain extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
PageAdapter pageAdapter;
TabItem tabChats;
TabItem tabStatus;
TabItem tabCalls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_m);
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(getResources().getString(R.string.app_name));
setSupportActionBar(toolbar);
tabLayout = findViewById(R.id.tablayout);
tabChats = findViewById(R.id.tabChats);
tabStatus = findViewById(R.id.tabStatus);
tabCalls = findViewById(R.id.tabCalls);
viewPager = findViewById(R.id.viewPager);
pageAdapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pageAdapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 1) {
toolbar.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorAccent));
tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorAccent));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorAccent));
}
} else if (tab.getPosition() == 2) {
toolbar.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
android.R.color.darker_gray));
tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
android.R.color.darker_gray));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MainActivityFargmain.this,
android.R.color.darker_gray));
}
} else {
toolbar.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorPrimary));
tabLayout.setBackgroundColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorPrimary));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MainActivityFargmain.this,
R.color.colorPrimaryDark));
}
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
}
public class PageAdapter extends FragmentPagerAdapter {
private int numOfTabs;
PageAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChatFragment();
case 1:
return new StatusFragment();
case 2:
return new CallFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
public class StatusFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_status, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_status, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_status) {
Toast.makeText(getActivity(), "Clicked on " + item.getTitle(), Toast.LENGTH_SHORT)
.show();
}
return true;
}
}
public class ChatFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_chat, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_chats, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_chat) {
Toast.makeText(getActivity(), "Clicked on " + item.getTitle(), Toast.LENGTH_SHORT)
.show();
}
return true;
}
}
You are passing the data to fragment from first activity and you are fetching data from second activity.
But in a proper scenario you should pass the data to second activity. Then after you can fetch it.
public static final String EXTRA_FROM = "FROMPL";
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(this,
MainActivityFargmain.class);
ExampleItem clickedItem = mExampleList.get(position);
detailIntent.putExtra(EXTRA_FROM, clickedItem.getCreator());
startActivity(detailIntent);
}
Fetch the data in MainActivityFragmain using below code.
Intent i = getIntent();
final String FROMPL = i.getStringExtra("FROMPL");
pageAdapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount(),FROMPL);
viewPager.setAdapter(pageAdapter);
Update your Pager adapter class like below.
public class PageAdapter extends FragmentPagerAdapter {
private int numOfTabs;
private String FROMPL;
PageAdapter(FragmentManager fm, int numOfTabs, String FROMPL) {
super(fm);
this.numOfTabs = numOfTabs;
this.FROMPL = FROMPL;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ChatFragment();
case 1:
StatusFragment statusFragment = new StatusFragment();
Bundle bundle=new Bundle();
bundle.putString("FROMPL", FROMPL);
statusFragment.setArguments(bundle);
return statusFragment;
case 2:
return new CallFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}

SearchView in ActionBar with more fragment on android

I need Add SearchBar in ActionBar handle with more Fragments like whatsApp
when Search in Tab chats get data and when Search in Tab Status get another data
How do This?This is My Code there is 3 tabs i need every tab there is SearchView
This Activity which there is on Fragments
public class ActivityForIncludeFragments extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_for_include_fragments);
ViewPager viewPager = (ViewPager)findViewById(R.id.viewPager);
CategoryAdapter adapter = new CategoryAdapter(this,getSupportFragmentManager());
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
invalidateOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem menuItemAddData = menu.findItem(R.id.add_data);
MenuItem menuItemActionSearch = menu.findItem(R.id.action_search);
menuItemAddData.setVisible(false);
menuItemActionSearch.setVisible(false);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.add_stocking_warehouse:
Intent intent = new Intent(ActivityForIncludeFragments.this,StockingWarehouse.class);
startActivity(intent);
break;
case R.id.add_reportes:
Intent intentReport = new Intent(ActivityForIncludeFragments.this,TableDaliyMovmentes.class);
startActivity(intentReport);
break;
}
return super.onOptionsItemSelected(item);
}
}
and This Fragment there is the data
public class AddPremissionFragment extends Fragment implements
LoaderManager.LoaderCallbacks<ArrayList<ItemsStore>>
,SearchView.OnQueryTextListener {
public AddPremissionFragment() {
// Required empty public constructor
}
public static final String ID_PERMISSION = "id";
public static final String NAME_PERMISION = "namePErmission";
public static final String NOTES_PERMISSION = "notes";
public static final String DIALOG_PERMISSION = "dialogPermission";
FloatingActionButton fab_add_permission;
ListView mListView;
public static AdapterAddPermission adapterAddPermission;
TaskDbHelper dbHelper;
ArrayList<ItemsStore> itemsPermissions = new ArrayList<ItemsStore>();
private ProgressBar progressBarPermission;
//Identifier for the category dataloader;
public static final int PERMISSION_LOADER = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_add_premission, container, false);
TextView namePremission = (TextView)view.findViewById(R.id.ETTypeStore);
dbHelper = new TaskDbHelper(getActivity());
mListView = (ListView) view.findViewById(R.id.listViewAddPermission);
progressBarPermission =(ProgressBar)view.findViewById(R.id.progressBarPermission);
adapterAddPermission = new AdapterAddPermission(getContext(), itemsPermissions);
View emptyView = view.findViewById(R.id.empty_view_permission);
mListView.setEmptyView(emptyView);
mListView.setAdapter(adapterAddPermission);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Toast.makeText(getContext(), "Click :"+ position, Toast.LENGTH_SHORT).show();
ItemsStore itemSPermision = itemsPermissions.get(position);
Bundle bundle = new Bundle();
bundle.putInt(ID_PERMISSION, itemSPermision.getId());
bundle.putString(NAME_PERMISION, itemSPermision.getNamePermission());
bundle.putString(NOTES_PERMISSION, itemSPermision.getNotes());
// startActivity(intent);
// long id = cursor.getLong(cursor.getColumnIndex(TaskContract.TaskEntry._ID));
EditPermissionFragment f = new EditPermissionFragment();
f.setArguments(bundle);
f.show(getFragmentManager(),DIALOG_PERMISSION);}});
// namePremission.setText("Name Permission");
fab_add_permission = (FloatingActionButton)view.findViewById(R.id.fab_add_permission);
fab_add_permission.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new EditPermissionFragment().show(getFragmentManager(),DIALOG_PERMISSION);
}
});
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Kick off the loader
getActivity().getSupportLoaderManager().initLoader(PERMISSION_LOADER, null, this);
}
#Override
public Loader<ArrayList<ItemsStore>> onCreateLoader(int id, Bundle args) {
return new LoaderPErmission(getContext().getApplicationContext(),itemsPermissions,dbHelper);
}
#Override
public void onLoadFinished(Loader<ArrayList<ItemsStore>> loader, ArrayList<ItemsStore> data) {
progressBarPermission.setVisibility(View.GONE);
mListView.setVisibility(View.VISIBLE);
adapterAddPermission.swapData(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<ItemsStore>> loader) {
adapterAddPermission.swapData(Collections.<ItemsStore>emptyList());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
searchView.setOnQueryTextListener(this);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
itemsPermissions = dbHelper.getAllItemsPermissionBySearch(newText);
if (itemsPermissions !=null){
adapterAddPermission.setFilter(itemsPermissions);
// getSupportLoaderManager().restartLoader(Daily_LOADER,null,this);
}
return false;
}
}
Please check which fragment is visible using this
Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment != null && fragment.isVisible()) {
if (fragment instanceof ChatFragment) {
....
}
else { }
}

Adapter is multiplying with the same data android

I have a SwitchTabActivty with 4 items. In my case, I use the second item to get some data from the web through a recyclerview. The problem is that when I press the fourth item (it contains a button that's starting an activity) and I go back to my second tab , my recycler view is multiplied with the same data again.
Switchtabactivity :
public class SwitchTabActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private boolean pressToExit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.weather_tab);
tabLayout.getTabAt(1).setIcon(R.drawable.events);
tabLayout.getTabAt(2).setIcon(R.drawable.details_tab);
tabLayout.getTabAt(3).setIcon(R.drawable.settings_tab);
setColorTab(tabLayout);
}
private void setColorTab(TabLayout tab) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
tab.setTabTextColors(getResources().getColorStateList(R.color.tab_colors, null));
} else {
tab.setTabTextColors(getResources().getColorStateList(R.color.tab_colors));
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onBackPressed() {
if (!pressToExit) {
Toast.makeText(this, "Press back again to exit.", Toast.LENGTH_SHORT).show();
pressToExit = true;
} else {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
#Override
public void onResume() {
super.onResume();
pressToExit = false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_switch_tab, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return WeatherFragment.newInstance(position);
case 1:
return EventFragment.newInstance(position);
case 2:
return OwnEventFragment.newInstance(position);
case 3:
return SettingsFragment.newInstance(position);
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Weather";
case 1:
return "Events";
case 2:
return "My Events";
case 3:
return "Settings";
}
return null;
}
}
EventFragment :
public class EventFragment extends Fragment implements EventResponse {
private String latitude, longitude;
private static final String ARG_SECTION_NUMBER = "section_number";
private RecyclerView eventList;
private EventAdapter adapter;
private TextView ifNullEvents;
private final ArrayList<EventData> eventsData = new ArrayList<>();
private UserDataBase db;
private List<String> latLonList;
private ProgressBar progressBar;
public EventFragment() {
}
public static EventFragment newInstance(int sectionNumber) {
EventFragment fragment = new EventFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.event_fragment, container, false);
initView(rootView);
db = new UserDataBase(getContext());
checkLocationChanged();
latLonList = db.getLatLon();
latitude = latLonList.get(0);
longitude = latLonList.get(1);
String EVENT_BRITE_URL_PARSE = "MY_URL";
String EVENT_BRITE_TOKEN = "MY_TOKEN";
new EventBriteApi(this, getContext()).execute(EVENT_BRITE_URL_PARSE + EVENT_BRITE_TOKEN);
setupRecyclerView();
setLocationMessage();
return rootView;
}
private void initView(View view) {
eventList = (RecyclerView) view.findViewById(R.id.event_recycler_view);
ifNullEvents = (TextView) view.findViewById(R.id.text_null_location);
progressBar = (ProgressBar) view.findViewById(R.id.progress_bar_event);
}
private void checkLocationChanged() {
if (WePrefs.isLocationChanged) {
eventsData.clear();
ifNullEvents.setText(getResources().getString(R.string.waiting_for_data));
ifNullEvents.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
WePrefs.setIsLocationChanged(false);
} else {
progressBar.setVisibility(View.GONE);
ifNullEvents.setVisibility(View.GONE);
}
if (WePrefs.isNullEventLocation) {
ifNullEvents.setText(getResources().getString(R.string.no_events_found));
ifNullEvents.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.INVISIBLE);
WePrefs.setIsNullEventLocation(false);
}
}
private void setupRecyclerView() {
eventList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
eventList.setLayoutManager(linearLayoutManager);
adapter = new EventAdapter(getActivity(), eventsData);
adapter.setHasStableIds(true);
eventList.setAdapter(adapter);
}
#Override
public void onResume() {
checkLocationChanged();
setLocationMessage();
super.onResume();
}
private void setLocationMessage() {
if (eventsData.isEmpty()) {
ifNullEvents.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
} else {
ifNullEvents.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
}
progressBar.setVisibility(View.GONE);
}
#Override
public void getArray(ArrayList<EventData> data) {
eventsData.clear();
eventsData.addAll(new ArrayList<>(new LinkedHashSet<>(data)));
}
}
Adapter :
ublic class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventHolder> {
ArrayList<EventData> data;
Context context;
public EventAdapter(Context context, ArrayList<EventData> events) {
this.context = context;
data = events;
}
#Override
public EventHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RelativeLayout layout = (RelativeLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.single_event_view, parent, false);
return new EventAdapter.EventHolder(layout);
}
#Override
public void onBindViewHolder(EventHolder holder, int position) {
holder.eventName.setText(data.get(position).getEventName());
if (data.get(position).getEventImageUrl() != null) {
Picasso.with(context).load(data.get(position).getEventImageUrl()).into(holder.eventPic);
} else {
holder.eventPic.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.no_image));
}
}
#Override
public int getItemCount() {
return data.size();
}
public class EventHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView eventName;
ImageView eventPic;
RelativeLayout layout;
public EventHolder(View itemView) {
super(itemView);
eventName = (TextView) itemView.findViewById(R.id.event_name);
eventPic = (ImageView) itemView.findViewById(R.id.event_image);
layout = (RelativeLayout) itemView.findViewById(R.id.event_layout);
layout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
//context.startActivity(new Intent(context, WebViewActivity.class));
}
}
}
Those are some of my java classes that I use for this kind of thing.
Anyway, another problem is that, when I change the location ( to receive my events) I must go to another tab and after that to come back to see my events list ( I think it needs to recreate the view ) so , because of that I called onResume, but it does not help.

how to stop 2nd tab toast getting displayed automatically in 1st tab activity

Hi am newbee to android and I am facing problem with tab activity
can any one help ...
I have attached screenshot
Issue faced - when i open my app by default 1st tab is displayed but the toast from 2nd tab "2nd tab selected... " is displayed in 1st tab why this is happening ??
1st tab is home_fragment.java
2tab vehicle.java and toast from this vehicle fragment is displayed in home fragment
and 3rd is displayed in 2nd tab fragment
main activity.java
public class MainActivity extends AppCompatActivity {
private static Button button;
private static EditText editText;
private static TextView textView;
static DatabaseHelper databaseHelper;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private int []tabicon={R.drawable.home,R.drawable.people,R.drawable.messege};
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
setupViewPager(mViewPager);/* new line*/
// DatabaseHelper databaseHelper=new DatabaseHelper(getBaseContext(),null,null,1);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setSelectedTabIndicatorHeight(10);
tabLayout.getTabAt(0).setIcon(R.drawable.home);
tabLayout.getTabAt(1).setIcon(R.drawable.people);
tabLayout.getTabAt(2).setIcon(R.drawable.messege);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(ViewPager viewPager)
{
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Home_fragment(),"home");
adapter.addFragment(new vehicle(),"vehicle");
adapter.addFragment(new Message(),"Message");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter
{
private final List<Fragment> mfragmentList=new ArrayList<>();
private final List<String>mfragmenttitlelist= new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mfragmentList.get(position);
}
#Override
public int getCount() {
return mfragmentList.size();
}
public void addFragment(Fragment fragment,String s)
{
mfragmentList.add(fragment);
mfragmenttitlelist.add(s);
}
#Override
public CharSequence getPageTitle(int position) {
return mfragmenttitlelist.get(position);
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("Do you want to Exit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//if user pressed "yes", then he is allowed to exit from application
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//if user select "No", just cancel this dialog and continue with app
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container, false);
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "home";
case 1:
return "vehicle";
case 2:
return "Message";
}
return null;
}
}
}
Home_fragment.java
public class Home_fragment extends Fragment
{
private EditText editText;
private Button button;
private TextView textView;
static DatabaseHelper databaseHelper;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//return super.onCreateView(inflater, container, savedInstanceState);
View view=inflater.inflate(R.layout.fragment_home,container,false);
editText=(EditText) view.findViewById(R.id.search);
button=(Button)view.findViewById(R.id.search_btn);
textView=(TextView)view.findViewById(R.id.search_result);
databaseHelper=new DatabaseHelper(getContext(),null,null,1);
databaseHelper.getReadableDatabase();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String string;
if (editText.getText().toString().isEmpty())
{
Toast.makeText(getActivity(), "Please enter bike number", Toast.LENGTH_SHORT).show();
}
else {
try {
string = databaseHelper.searchName(editText.getText().toString());
textView.setText(string);
} catch (SQLiteException e)
{
e.printStackTrace();
Toast.makeText(getActivity(), "Please enter name", Toast.LENGTH_SHORT).show();
}
}
// return true;
}
});
return view;
}
}
vehical.java 2nd fragment
public class vehicle extends Fragment
{
private ListView listView;
private TextView textView;
private ArrayAdapter<String> listadapter;
// DatabaseHelper databaseHelper=new DatabaseHelper(getBaseContext(),null,null,1);
// databaseHelper.getWritableDatabase();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//return super.onCreateView(inflater, container, savedInstanceState);
View view=inflater.inflate(R.layout.fragment_vehical,container,false);
listView=(ListView) view.findViewById(R.id.list_view);
textView=(TextView)view.findViewById(R.id.total_count);
final DatabaseHelper databaseHelper=new DatabaseHelper(getContext(),null,null,1);
//databaseHelper.getReadableDatabase();
final ArrayList<String> arrayList=databaseHelper.readNames();
final ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_list_item_2,android.R.id.text1,arrayList);
arrayAdapter.notifyDataSetChanged();
listView.setAdapter(arrayAdapter);
textView.setText("Total customer "+String.valueOf(listView.getCount()));
Toast.makeText(getActivity(), "2nd tab selected", Toast.LENGTH_SHORT).show();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
listView.getItemAtPosition(position);
Toast.makeText(getActivity(), "Name selected: "+arrayList.get(position), Toast.LENGTH_SHORT).show();
//databaseHelper.upDate(arrayList.get(position));
// arrayList.get(position)=databaseHelper.upDate(arrayAdapter);
// Intent intent=new Intent(getActivity(),Add_customer.class);
// startActivity(intent);
//String name=parent.getSelectedItem();
}
});
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(),Add_customer.class);
startActivity(intent);
Snackbar.make(view, "Customer form", Snackbar.LENGTH_LONG)
.setAction("Action", new Add_customer()).show();
}
});
// StringBuffer stringBuffer=databaseHelper.getData(); //get data from database in databasehelper.java
//
// ArrayList<StringBuffer> cust_list= new ArrayList<>(stringBuffer);
// cust_list.addAll(Arrays.asList(stringBuffer));
// listadapter=new ArrayAdapter<String>(vehicle.this,R.layout.fragment_vehical,cust_list);
return view;
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
you could use above method within your fragment that is within your ViewPager Adapter
if(isVisibleToUser){
//dosomething when the fragment is visible
}else{
//dosomething else
}
original post
This is because the fragment is called when ViewPager has finish its setup, i.e adding the fragments from its adapter and displaying the fragments.
So you need to do the Toasting if only the fragment is visible.
if you use support library for fragments, then you can use getUserVisibleHint() or override setUserVisibleHint() to check for fragment visibility.
You can do the following:
public class MyFragment extends Fragment {
...
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Do toasting here.
} else {
}
}
...
}
For more about ViewPager and Fragment visibility, check this: How to determine when Fragment becomes visible in ViewPager
Add isVisible at start, if it's not visible to user, it will return
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//return super.onCreateView(inflater, container, savedInstanceState);
if(!isVisible) {
return
}
...
}

Categories

Resources