How to set action mode over toolbar in android - android

I have created only tool bar in my fragment.I have implemented the action mode for multiple deleting the list view.But the action mode will open above the toolbar(i.e)action bar.How to display that action mode over the toolbar.I have tried <item name="windowActionModeOverlay">true</item> in my theme but it does not works.`
public class Event_notification extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
List<String> myList;
private List<FeedItem> feedsList= new ArrayList<FeedItem>();
ListView listView;
TextView emptyview;
String message;
EventNotification_adapter adapter;
String userID,userid_share;
CheckBox check;
ArrayList<String> list = new ArrayList<String>();
String EventStatus,date;
Dialog dialog;
public static ActionMode mActionMode;
ActionBar action;
private JSONObject EventJsonObject;
protected static final String TAG = "NOTIFICATION";
ProgressWheel pw;
ResetPasswordActivity obj = new ResetPasswordActivity();
Constants constants=new Constants();
private SwipeRefreshLayout swipeRefreshLayout;
public static final String MY_PREFS_NAME = "MyPrefsFile";
public Event_notification() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment Event_notification.
*/
// TODO: Rename and change types and number of parameters
#Override
public void onCreate(Bundle savedInstanceState) {
// getActivity().getWindow().requestFeature(Window.FEATURE_ACTION_MODE_OVERLAY);
super.onCreate(savedInstanceState);
// getActivity().getActionBar().hide();
SharedPreferences prefs1 = getContext().getSharedPreferences(MY_PREFS_NAME, getContext().MODE_PRIVATE);
userID= prefs1.getString("userid", null);
System.out.println("userid" + userID);
// actionBar.hide();
// setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
System.out.println("Notification Fragment");
View v=inflater.inflate(R.layout.fragment_event_notification, container, false);
//return inflater.inflate(R.layout.row_eventnotification, container, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), "arial.ttf");
fontChanger.replaceFonts((ViewGroup) v);
emptyview=(TextView)v.findViewById(R.id.empty_view);
listView=(ListView)v.findViewById(R.id.recycler_view);
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
check=(CheckBox)v.findViewById(R.id.check1);
pw = (ProgressWheel) v.findViewById(R.id.pw_spinner);
obj.styleRandom(pw, getContext());
getnotification();
adapter=new EventNotification_adapter(getContext(),feedsList,Event_notification.this);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
adapter.removeSelection();
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
mActionMode = mode;
mActionMode.getMenuInflater().inflate(R.menu.multiple_delete, menu);
return true;
}
#Override
public boolean onActionItemClicked(final ActionMode mode,
final MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.selectAll:
final int checkedCount = feedsList.size();
// If item is already selected or checked then remove or
// unchecked and again select all
for (int i = 0; i < checkedCount; i++) {
listView.setItemChecked(i, true);
// listviewadapter.toggleSelection(i);
}
mode.setTitle(checkedCount + " Selected");
return true;
case R.id.unselect:
mode.finish();
return false;
case R.id.delete:
// Add dialog for confirmation to delete selected item
// record.
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(getContext(), R.style.AppCompatAlertDialogStyle);
builder.setMessage("Do you want to delete selected record(s)?");
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
SparseBooleanArray selected = adapter
.getSelectedIds();
for (int i = (selected.size()); i >= 0; i--) {
if (selected.valueAt(i)) {
// String selecteditem=Integer.parseInt(selected.keyAt(i));
//
FeedItem movie = feedsList.get(selected.keyAt(i));
list.add(movie.getMessageid());
System.out.println("EVENT ID____"+list);
int selecteditem = selected.keyAt(i);
// String selecteditem1=Integer.toString(item.getItemId());
int selecteditem1=item.getItemId();
EventDelete();
dialog.dismiss();
// Remove selected items following the ids
adapter.remove(selecteditem);
System.out.println("FEEDLIST SIZE+++"+feedsList.size());
if(feedsList.size()==0){
emptyview.setVisibility(View.VISIBLE);
}
else{
emptyview.setVisibility(View.GONE);
}
}
}
// Close CAB
mode.finish();
selected.clear();
}
});
AlertDialog alert = builder.create();
//alert.setIcon(R.drawable.questionicon);// dialog Icon
alert.setTitle("Confirmation"); // dialog Title
alert.show();
return true;
default:
mode.finish();
return false;
}
}
`

try this.
android.view.ActionMode mMode = toolbar.startActionMode(new Callback() {
#Override
public boolean onPrepareActionMode(
ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(
ActionMode mode) {
}
#Override
public boolean onCreateActionMode(
ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(
ActionMode mode, MenuItem item) {
return false;
}
});
if you want to Fininsh Action mode
if (mMode != null) {
mMode.finish();
}
And don't forget to add following in your main Theme under styles.xml
<item name="android:windowActionModeOverlay">true</item>
You are good to go.

Related

How is to implement action mode in fragment in androidx?

I have to implement action mode in fragment, but its gets nullpointer exception in action mode. I have tried so much but not gets any results, Please help me I am new in android. I have also tried startActionMode but not impact. I have wasted my time & searched lot of code not found any solution. Please help me
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
private ActionModeCallback actionModeCallback;
private ActionMode actionMode;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
galleryViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
final Button btnLoad = root.findViewById(R.id.load);
btnLoad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
enableActionMode(1, true );
}
});
return root;
}
public void enableActionMode(int position, boolean bool) {
int count = 4;
if(actionMode == null) {
actionMode = ((AppCompatActivity)getActivity()).startSupportActionMode(actionModeCallback);
}
if (count == 0) {
actionMode.finish();
actionMode = null;
} else {
actionMode.setTitle(String.valueOf(count));
actionMode.invalidate();
}
}
private class ActionModeCallback implements ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.actionbar_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// getSupportActionBar().hide();
menu.findItem(R.id.action_delete).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Log.d("API123", ""+item.getItemId());
switch (item.getItemId()) {
case R.id.action_delete:
// delete all the selected rows
//mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
//clear selections
mode.finish();
actionMode = null;
}
}
}
This is mycode, null pointer in actionmode. please help me i wasting my time. searching lot of, no result found

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 { }
}

how to not load all tab in FragmentStatePagerAdapter

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

Unable to restore RecyclerView's position/state

Whenever I move from DetailsActivity to MainActivity the RecyclerView is reset and list is always shown from the top position.
Full source code can be seen here. The code is still largely a work in progress.
MainActivityFragment is as follows.
public class MainActivityFragment extends Fragment {
private ArrayList<Movie> mMovieArrayList = new ArrayList<Movie>();
private static final String PAGE = "1";
private RecyclerView mRecyclerView;
private SharedPreferences mSettings;
private SharedPreferences.Editor mEditor;
private static final String LOG = MainActivityFragment.class.getSimpleName();
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movie_list, container, false);
// Set column size to 2 for default and portrait
// and 3 for landscape orientations
int column = Integer.parseInt(getString(R.string.grid_portrait));
if (getResources().getConfiguration().orientation == 1) {
column = Integer.parseInt(getString(R.string.grid_portrait));
} else if (getResources().getConfiguration().orientation == 2) {
column = Integer.parseInt(getString(R.string.grid_landscape));
}
if (getActivity().findViewById(R.id.movie_detail_container) != null) {
column = Integer.parseInt("2");
}
mSettings = PreferenceManager.getDefaultSharedPreferences(getActivity());
mEditor = mSettings.edit();
mEditor.apply();
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), column));
mRecyclerView.setAdapter(new MovieAdapter(getActivity(), mMovieArrayList));
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onStart() {
super.onStart();
updateMovieList();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main_fragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.popularity:
mEditor.putString(getResources().getString(R.string.perf_sort),
getResources().getString(R.string.url_popularity));
mEditor.apply();
updateMovieList();
item.setChecked(true);
Log.d(LOG, "onOptionsItemSelected: popularity");
return true;
case R.id.rating:
mEditor.putString(getResources().getString(R.string.perf_sort),
getResources().getString(R.string.url_top_rated));
mEditor.apply();
updateMovieList();
item.setChecked(true);
Log.d(LOG, "onOptionsItemSelected: rating");
return true;
case R.id.favorite:
mEditor.putString(getResources().getString(R.string.perf_sort),
getResources().getString(R.string.url_favorite));
mEditor.apply();
updateMovieList();
item.setChecked(true);
Log.d(LOG, "onOptionsItemSelected: favorite");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
String sortBy = mSettings.getString(getResources().getString(R.string.perf_sort),
getResources().getString(R.string.url_popularity));
if (sortBy.equals(getResources().getString(R.string.url_popularity))) {
menu.findItem(R.id.popularity).setChecked(true);
} else if (sortBy.equals(getResources().getString(R.string.url_top_rated))) {
menu.findItem(R.id.rating).setChecked(true);
} else if (sortBy.equals(getResources().getString(R.string.url_favorite))) {
menu.findItem(R.id.favorite).setChecked(true);
}
}
private void updateMovieList() {
mMovieArrayList = new ArrayList<>();
String sortBy = mSettings.getString(getResources().getString(R.string.perf_sort),
getResources().getString(R.string.url_popularity));
if (sortBy.equals(getResources().getString(R.string.url_popularity)) ||
sortBy.equals(getResources().getString(R.string.url_top_rated))) {
try {
mMovieArrayList =
new FetchMoviesTask().execute(sortBy, PAGE).get();
} catch (ExecutionException | InterruptedException ei) {
ei.printStackTrace();
}
} else if (sortBy.equals(getResources().getString(R.string.url_favorite))) {
ContentResolver resolver = getActivity().getContentResolver();
Cursor cursor =
resolver.query(MovieContract.MovieEntry.CONTENT_URI,
null,
null,
null,
null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String title = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.TITLE));
String movie_id = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.MOVIE_ID));
String poster = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.POSTER));
String backdrop = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.BACKDROP));
String overview = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.OVERVIEW));
String vote_average = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.VOTE_AVERAGE));
String release_date = cursor.getString(cursor.getColumnIndex(MovieContract.MovieEntry.DATE));
Movie movie = new Movie(title, release_date, poster,
vote_average, overview, backdrop, movie_id);
mMovieArrayList.add(movie);
} while (cursor.moveToNext());
}
}
if (cursor != null)
cursor.close();
}
mRecyclerView.setAdapter(new MovieAdapter(getActivity(), mMovieArrayList));
mRecyclerView.getAdapter().notifyDataSetChanged();
}
}
MainActivity is as follows.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#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;
}
// if (id == android.R.id.home) {
// onBackPressed();
// return true;
// }
return super.onOptionsItemSelected(item);
}
}
I have tried setting saving up RecyclerView's state like shown in this post.
I have also tried saving the mArrayList in onSaveInstanceState and restoring it in onActivityCreated or onViewCreated like in this post.
Both of these have not worked for me. As soon as I return back from the DetailsActivity to MainActivity the position is gone.
Thanks.
You're calling a method to update movies list in onStart callback of fragment life cycle. Which means when your main activity is shown back, you're resetting your list. You shouldn't.
You set a new instance of adapter at the end of update list method. That redraws the entire list. You should rethink your life cycles. Call update movie list only in onCreate or onCreateView and always check if adapter opject is null and only then use setAdapter method on recycler view. If adapter is not null, just call notifyDataSetChanged or whatever is needed to update your items.
Maybe this could help. Eventhough it will scroll all the way to the selected item each time.

ListView mark selected list entries onItemLongClick in Contextual ActionBar

I've implemented a ListView in the sense of a master detail view:onItemClick() calls new Activity with details according to the list item.
onItemLongClick calls ActionMode.Callback to provide the selection of multiple list items. I already solved the problem to avoid calling onItemClick() when an item should be selected by returning true in onItemLongClick().
The problem is the selection is made/is visualized after I clicked an item and returned from the activity.
Please not the standard listSelector. I'm not sure if this is the correct way/solution. I tried to implement a custom listSelector but it did not work properly.
Any suggestions?
XML of the ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ResultFragment" >
<!-- standard list_selector_background -->
<ListView
android:id="#+id/fragment_ergebnis_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:choiceMode="multipleChoice"
android:divider="#color/gray_3"
android:dividerHeight="1dp"
android:listSelector="#android:drawable/list_selector_background"
android:saveEnabled="true" >
</ListView>
</LinearLayout>
Code of the Fragment
public class ResultPOJOFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener {
private Activity mActivity;
private ActionModeCallback mActionModeCallback;
private ActionMode mActionMode;
private ListView mListView;
private ResultAdapter mAdapter;
private ResultDAO mResultDAO;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mActivity = getActivity();
mResultDAO = new ResultDAO(mActivity);
View fragmentView = inflater.inflate(R.layout.fragment_result, container, false);
mAdapter = new ResultAdapter(mActivity);
mListView = (ListView) fragmentView.findViewById(R.id.fragment_result_listView);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener((OnItemClickListener) this);
mListView.setOnItemLongClickListener((OnItemLongClickListener) this);
mActionModeCallback = new ActionModeCallback();
return fragmentView;
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ResultPOJO result = new ResultPOJO();
result = mAdapter.getItem(position);
/* Show activity with details */
Intent resultDetailsIntent = new Intent(getActivity(), ResultPOJODetailsActivity.class);
if (resultDetailsIntent != null) {
resultDetailsIntent.putExtra(AppConstants.TAG_RESULT, result);
startActivity(resultDetailsIntent);
}
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (mActionMode != null) {
/* true: to avoid calling onItemClick() */
return true;
} else {
mActionMode = mActivity.startActionMode(mActionModeCallback);
view.setSelected(true);
}
mActionMode = mActivity.startActionMode(new ActionModeCallback());
return true;
}
private void selectAllEntries() {
for (int i = 0; i < mListView.getChildCount(); i++) {
mListView.setItemChecked(i, true);
}
}
private void deselectAllEntries() {
for (int i = 0; i < mListView.getChildCount(); i++) {
mListView.setItemChecked(i, false);
}
}
private void refreshView() {
mAdapter.notifyDataSetChanged();
}
private class ActionModeCallback implements ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.result_fragment_cab, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_cab_result_fragment_select_all:
selectAllEntries();
break;
case R.id.menu_item_cab_result_fragment_deselect_all:
deselectAllEntries();
break;
default:
break;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
}
}

Categories

Resources