I am having a problem that whenever I switch between different tabs, the process lags for a second or two. How can I remove this lag? There is no such thing in oncreate function of the fragments. I am posting the code here.
This is the code for the activity that is calling the fragment Dashboardnew :
private void setupDrawerContent(final NavigationView navigationView) {
//revision: this don't works, use setOnChildClickListener() and setOnGroupClickListener() above instead
expandableList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
if(i==0) {
//Toast.makeText(getApplicationContext(),"View Tasks",Toast.LENGTH_LONG).show();
fab.setVisibility(View.VISIBLE);
if (filterApplied) {
persistentbottomSheet.setVisibility(View.VISIBLE);
persistentbottomSheet.bringToFront();
fab.bringToFront();
}
fragment = new DashboardNew();
if (fragment != null) {
manager.beginTransaction().replace(R.id.dashboard_frame, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
/* new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (fragment != null) {
manager.beginTransaction()
.replace(R.id.dashboard_frame, fragment)
.commit();
}
}
}, 300);*/
//drawer.closeDrawer(GravityCompat.START);
}
if(i==1) {
}
if(i==2) {
prefs.edit().remove("firstTime").apply();
Intent intent = new Intent(getApplication(), Login.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
return false;
}
});
expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long l) {
if (groupPosition == 1 && childPosition == 0) {
fabvisibility = false;
//so this code only executes if the 2nd child in the 2nd group is clicked
fragment=new AddUser();
if (fragment != null) {
manager.beginTransaction()
.replace(R.id.dashboard_frame, fragment,"AddUser")
//.add(fragment,"AddUser")
// .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
drawer.closeDrawer(GravityCompat.START);
}
if (groupPosition == 1 && childPosition == 1) {
//so this code only executes if the 2nd child in the 2nd group is clicked
fabvisibility = false;
fragment=new ViewUsers();
if (fragment != null) {
manager.beginTransaction()
.replace(R.id.dashboard_frame, fragment)
.commit();
drawer.closeDrawer(GravityCompat.START);
}
}
return false;
}
});
}
#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.
switch (item.getItemId()) {
case android.R.id.home:
drawer.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
}
The code for Dashboardnew fragment is :
initialize(rootview);
clicklisteners();
createViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
createTabIcons();
return rootview;
}
private void clicklisteners()
{
usualTasks.setOnClickListener(this);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("The Checklist");
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.toggleButton: {
if(usualTasks.isChecked()) {
Toast.makeText(getActivity(), "Toggle button is on", Toast.LENGTH_LONG).show();
showRoleDialog();
FragmentTransaction trans = getFragmentManager().beginTransaction();
trans.replace(R.id.base_pending, new UsualTasks());
WelcomeActivity.persistentbottomSheet.setVisibility(View.INVISIBLE);
//WelcomeActivity.fab.setVisibility(View.INVISIBLE);
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.commit();
}
else {
Toast.makeText(getActivity(), "Toggle button is Off", Toast.LENGTH_LONG).show();
FragmentTransaction trans = getFragmentManager().beginTransaction();
trans.replace(R.id.usual_pending, new PendingTasks());
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
if (WelcomeActivity.filterApplied == true) {
WelcomeActivity.persistentbottomSheet.setVisibility(View.VISIBLE);
WelcomeActivity.persistentbottomSheet.bringToFront();
WelcomeActivity.fab.setVisibility(View.VISIBLE);
}
if(UsualTasks.shown) {
UsualTasks.mSnackBar.dismiss();
}
trans.commit();
}
}
}
}
public void populateList(HashMap<Integer, String> myMap, List myList){
Set<Map.Entry<Integer, String>> setMap = myMap.entrySet();
Iterator<Map.Entry<Integer, String>> iteratorMap = setMap.iterator();
int item=0;
while(iteratorMap.hasNext()) {
Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>) iteratorMap.next();
myList.add(entry.getValue());
item++;
}
}
private void showRoleDialog() {
final Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.usualtask_dialog);
rolelist = new ArrayList<Map<Integer,String>>();
roles= new HashMap<Integer, String>();
roles.put(1, "Senior Manager");
roles.put(2, "Admin");
roles.put(3, "HR");
populateList(roles,rolelist);
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_single_choice, rolelist)
{
#Override
public View getView(int position, View convertView, ViewGroup parent){
// Get the current item from ListView
View view = super.getView(position,convertView,parent);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setTextColor(Color.parseColor("#353b41"));
return view;
}
};
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
selectRole= (ListView)dialog.findViewById(R.id.selectrole);
submitRole= (Button)dialog.findViewById(R.id.btsubmitrole);
selectRole.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
selectRole.setAdapter(arrayAdapter);
selectRole.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}
});
submitRole.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
private void createTabIcons() {
RelativeLayout tabOne = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.pending_tab, null);
TextView textTab=(TextView)tabOne.findViewById(R.id.tab);
ImageView imageTab=(ImageView) tabOne.findViewById(R.id.notifyimage);
//TextDrawable drawable = TextDrawable.builder().buildRound("999",Color.RED); // radius in px
TextDrawable drawable = TextDrawable.builder()
.buildRoundRect("999",Color.RED,18); // radius in px
imageTab.setImageDrawable(drawable);
textTab.setText("Pending");
tabLayout.getTabAt(1).setCustomView(tabOne);
RelativeLayout tabTwo = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.completed_tab, null);
TextView textTab1=(TextView)tabTwo.findViewById(R.id.pending_tab);
textTab1.setText("Completed");
tabLayout.getTabAt(0).setCustomView(tabTwo);
}
private void initialize(View rootview) {
toolbar = (Toolbar)rootview.findViewById(R.id.toolbar);
viewPager = (ViewPager)rootview.findViewById(R.id.viewpager);
tabLayout = (TabLayout)rootview.findViewById(R.id.tabs);
usualTasks=(ToggleButton)rootview.findViewById(R.id.toggleButton);
}
private void createViewPager(ViewPager viewPager) {
adapter = new DashboardNew.ViewPagerAdapter(getChildFragmentManager());
adapter.addFrag(new CompletedTasks(), "Completed");
adapter.addFrag(new PendingTasks(), "Pending");
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) {
if (position == 0)
return new CompletedTasks();
else
return new PendingTasks();
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
And here is the code for Completed tasks:
completedTaskList = (ListView) rootview.findViewById(R.id.completedlist);
BaseMenuActivity.filterState=false;
if(UsualTasks.shown) {
UsualTasks.mSnackBar.dismiss();
}
generateListdata();
return rootview;
}
private void generateListdata() {
completedTasks.add(new completedTasks("Call the Owner","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.access_dashboard));
completedTasks.add(new completedTasks("Check the safety of patients","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.safety_dashboard));
completedTasks.add(new completedTasks("Admin needs to do specific task","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.admin_dashboard));
completedTasks.add(new completedTasks("Get the specific work done","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.access_dashboard));
completedTasks.add(new completedTasks("Need to hire more resources","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.hr_dashboard));
completedTasks.add(new completedTasks("How are patients behaving?","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.patient_experience_dashboard));
completedTasks.add(new completedTasks("Need to adjust the audit report","Wembley GP","Daily",R.drawable.completed_tick,R.drawable.finance_dashboard));
//getListView().setDividerHeight(10);
ArrayAdapter<com.example.attech.checklist_attech.Model.completedTasks> adapter = new CompletedTaskAdapter(getContext(), 0,completedTasks);
completedTaskList.setAdapter(adapter);
completedTaskList.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position == 0) {}
if (position == 1) {}
if (position == 2) {
//Intent myIntent = new Intent(view.getContext(), ViewUser.class);
//startActivityForResult(myIntent, 0);
}
}
});
}
}
This is the code for pendingtasks:
initialize(rootview);
generateListdataAssigned();
generateListdata();
generateselectall();
clickListeners();
return rootview;
}
private void clickListeners() {
assignTask.setOnClickListener(this);
assignTaskbottom.setOnClickListener(this);
}
private void populateList(HashMap<Integer, String> myMap, List myList){
Set<Map.Entry<Integer, String>> setMap = myMap.entrySet();
Iterator<Map.Entry<Integer, String>> iteratorMap = setMap.iterator();
int item=0;
while(iteratorMap.hasNext()) {
Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>) iteratorMap.next();
myList.add(entry.getValue());
item++;
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.assignTaskPending: {
selected = !selected;
if (selected) {
Toast.makeText(getActivity(), "Assigned", Toast.LENGTH_LONG).show();
assignTask.setBackgroundResource(R.color.dark_grey);
Toast.makeText(getActivity(),""+WelcomeActivity.filterApplied,Toast.LENGTH_LONG).show();
pendingTaskListAssigned.setVisibility(View.VISIBLE);
WelcomeActivity.persistentbottomSheet.setVisibility(View.INVISIBLE);
selectAllListView.setVisibility(View.VISIBLE);
assignTaskbottom.setVisibility(View.VISIBLE);
pendingTaskList.setVisibility(View.INVISIBLE);
}
else {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(),""+WelcomeActivity.filterApplied,Toast.LENGTH_LONG).show();
pendingTaskListAssigned.setVisibility(View.INVISIBLE);
assignTaskbottom.setVisibility(View.INVISIBLE);
selectAllListView.setVisibility(View.INVISIBLE);
assignTask.setBackgroundResource(R.drawable.box_grey);
pendingTaskList.setVisibility(View.VISIBLE);
if (WelcomeActivity.filterApplied) {
WelcomeActivity.persistentbottomSheet.setVisibility(View.VISIBLE);
WelcomeActivity.persistentbottomSheet.bringToFront();
WelcomeActivity.fab.setVisibility(View.VISIBLE);
}
}
break;
}
case R.id.btassignTask: {
showAssignTaskDialog();
break;
}
}
}
private void initialize(View rootview) {
pendingTaskList = (ListView) rootview.findViewById(R.id.pendinglist);
pendingTaskListAssigned = (ListView) rootview.findViewById(R.id.pendinglistassigned);
assignTask = (Button) rootview.findViewById(R.id.assignTaskPending);
assignTaskbottom = (Button) rootview.findViewById(R.id.btassignTask);
selectAllListView= (ListView)rootview.findViewById(R.id.selectalllist);
}
private void generateListdataAssigned() {
pendingTasksAssigned.add(new pendingTasks("System Tasks","Wembley GP","Daily",R.drawable.pending_clock_icon, R.drawable.safety_dashboard));
pendingTasksAssigned.add(new pendingTasks("Call answer speed","Wembley GP","Daily",R.drawable.pending_clock_icon, R.drawable.access_dashboard));
pendingTasksAssigned.add(new pendingTasks("Appointment reasons","Wembley GP","Daily",R.drawable.pending_clock_icon, R.drawable.access_dashboard));
pendingTasksAssigned.add(new pendingTasks("Admin needs to do specific task","Wembley GP","Daily",R.drawable.pending_clock_icon, R.drawable.hr_dashboard));
ArrayAdapter<pendingTasks> adapter = new PendingAssignedAdapter(getContext(), 0, pendingTasksAssigned);
pendingTaskListAssigned.setAdapter(adapter);
pendingTaskListAssigned.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox checkBox=(CheckBox)view.findViewById(R.id.checkboxassigned);
checkBox.performClick();
if(checkBox.isChecked()){
countChecks = countChecks + 1;
}
else{
countChecks = countChecks - 1;
}
if(check == true){
selectAllListView.setItemChecked(0, false);
check = !check;
}
if(countChecks == pendingTaskListAssigned.getCount()){
selectAllListView.setItemChecked(0, true);
check = ! check;
}
}
});
}
//populating the arraylist, creating an adapter and setting it to a list view
private void generateListdata() {
pendingTasks.add(new pendingTasks("System Tasks", "Wembley GP", "Daily", R.drawable.pending_clock_icon, R.drawable.safety_dashboard));
pendingTasks.add(new pendingTasks("Call answer speed", "Wembley GP", "Daily", R.drawable.pending_clock_icon, R.drawable.access_dashboard));
pendingTasks.add(new pendingTasks("Appointment reasons", "Wembley GP", "Daily", R.drawable.pending_clock_icon, R.drawable.access_dashboard));
ArrayAdapter<pendingTasks> adapter = new PendingTaskAdapter(getContext(), 0, pendingTasks);
pendingTaskList.setAdapter(adapter);
pendingTaskList.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
showInputDialog();
if (position == 0) {}
if (position == 1) {
//Intent myIntent = new Intent(view.getContext(), AddUser.class);
//startActivityForResult(myIntent, 0);
}
if (position == 2) {
//Intent myIntent = new Intent(view.getContext(), ViewUser.class);
//startActivityForResult(myIntent, 0);
}
}
});
}
private void generateselectall() {
selectallList= new ArrayList<Map<Integer,String>>();
selectall= new HashMap<Integer, String>();
selectall.put(1, "Select All");
populateList(selectall,selectallList);
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(getContext(),
android.R.layout.simple_list_item_single_choice, selectallList)
{
#Override
public View getView(int position, View convertView, ViewGroup parent){
// Get the current item from ListView
View view = super.getView(position,convertView,parent);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setTextColor(Color.BLACK);
tv.setTextSize(13);
ViewGroup.LayoutParams params = view.getLayoutParams();
// Set the height of the Item View
params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
view.setLayoutParams(params);
view.setPadding(37,0,10,10);
return view;
}
};
selectAllListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
selectAllListView.setAdapter(arrayAdapter);
selectAllListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getContext(), "Hello", Toast.LENGTH_SHORT).show();
int firstListItem = pendingTaskListAssigned.getFirstVisiblePosition();
int lastVisibleItem = pendingTaskListAssigned.getFirstVisiblePosition() + pendingTaskListAssigned.getChildCount() - 1;
check = ! check;
for(int i=0; i < pendingTaskListAssigned.getCount(); i++){
if(i>lastVisibleItem || i<firstListItem){
View item = (View) pendingTaskListAssigned.getAdapter().getView(i, null, pendingTaskListAssigned);
CheckBox checkbox = (CheckBox)item.findViewById(R.id.checkboxassigned);
checkbox.setChecked(check);
}
else{
ViewGroup item = (ViewGroup)pendingTaskListAssigned.getChildAt(i - firstListItem);
CheckBox checkbox = (CheckBox)item.findViewById(R.id.checkboxassigned);
checkbox.setChecked(check);
}
}
if(check == true){
countChecks = pendingTaskListAssigned.getCount();
}
else{
countChecks = 0;
}
}
});
}
protected void showInputDialog() {
final Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.task_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
tbutton = (ToggleButton)dialog.findViewById(R.id.toggleButton);
toollamp= (ImageButton)dialog.findViewById(R.id.lamptool);
tooli= (ImageButton)dialog.findViewById(R.id.itool);
tooldetails= (TextView) dialog.findViewById(R.id.tooldetail);
submit=(Button)dialog.findViewById(R.id.btsubmit);
toollamp.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
tooldetails.setText("Target for staff 2 rings and answer.Check daily for 2x 5 mins");
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getActivity(), "Dismiss", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
tooli.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
tooldetails.setText("Check daily for 2x 5 mins");
}
});
tbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(tbutton.isChecked()) {
Toast.makeText(getActivity(), "Toggle button is on", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getActivity(), "Toggle button is Off", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
protected void showAssignTaskDialog() {
final Dialog dialog = new Dialog(getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.assign_task_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Close= (ImageButton)dialog.findViewById(R.id.close);
myself=(Button)dialog.findViewById(R.id.btmyself);
others=(Button)dialog.findViewById(R.id.btothers);
Close.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
myself.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Myself", Toast.LENGTH_LONG).show();
}
});
others.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Others", Toast.LENGTH_LONG).show();
Intent intent= new Intent(getContext(), AssignTasks.class);
startActivity(intent);
}
});
dialog.show();
}
}
For those who have this problem , please use cardviews and recyclerviews. The data was too much for list view. Used cardviews and recyclerviews instead , and the lag was gone.
First of all I cant get why you create fragments twice
You actually create fragments here
private void createViewPager(ViewPager viewPager) {
adapter = new DashboardNew.ViewPagerAdapter(getChildFragmentManager());
adapter.addFrag(new CompletedTasks(), "Completed");
adapter.addFrag(new PendingTasks(), "Pending");
viewPager.setAdapter(adapter);
}
And then you create them here. Again
#Override
public Fragment getItem(int position) {
if (position == 0)
return new CompletedTasks();
else
return new PendingTasks();
}
I guess right way is removing these lines
adapter.addFrag(new CompletedTasks(), "Completed");
adapter.addFrag(new PendingTasks(), "Pending");
In other case you will have big problems with screen rotation.
You can set offscreen limit (by default its 1 only), so fragments will be created only one time and will not be removed
viewPager.setOffscreenPageLimit(2);
Also I refuse to understand what these lines mean
completedTasks.add(new completedTasks(...);
Is it CompletedTasks fragment? What do you add and how?
There is no such thing in onCreate() function of the fragments.
But it is still lagging, right? I think the problem is with your layout which is too heavy because the only work you are doing in onCreateView() is setting your layout.
Please check if your images are of very high pixel density. This is a most common mistake. Android System takes time to convert those high pixel images in layout to lower pixel density which is suitable for your device which takes time and causes lag.
Other reason could be bad layout hierarchy.
you should extends your container activity from FragmentActivity
public class MainActivity extends FragmentActivity
{
}
this is very fast switch between fragment.
is better using tag in xml layout
and show , hide when click the tab or bottom tabs
//code example :
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.show(fm.findFragmentById(fragment))
.hide(fm.findFragmentById(activePage))
.commit();
Related
I made a navigation in my project, than I have activities, I would made menu from those activities into navigation. so I need to convert those activities into fragments.
This my first activity.java
public class ToDoList extends AppCompatActivity implements BatListener, OnItemClickListener, OnOutsideClickedListener {
private BatRecyclerView mRecyclerView;
private BatAdapter mAdapter;
private List<BatModel> mGoals;
private BatItemAnimator mAnimator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.to_do_list);
// Navigator
FoldingTabBar tabBar = (FoldingTabBar) findViewById(R.id.folding_tab_bar);
tabBar.setOnFoldingItemClickListener(new FoldingTabBar.OnFoldingItemSelectedListener() {
#Override
public boolean onFoldingItemSelected(#NotNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_profile:
Intent intent0 = new Intent(ToDoList.this, Home.class);
startActivity(intent0);
break;
case R.id.menu_todo:
break;
case R.id.menu_schedule:
Intent intent1 = new Intent(ToDoList.this, TimeTable.class);
startActivity(intent1);
break;
case R.id.menu_settings:
break;
}
return false;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
((TextView) findViewById(R.id.text_title)).setTypeface(TypefaceUtil.getAvenirTypeface(this));
mRecyclerView = (BatRecyclerView) findViewById(R.id.bat_recycler_view);
mAnimator = new BatItemAnimator();
mRecyclerView.getView().setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.getView().setAdapter(mAdapter = new BatAdapter(mGoals = new ArrayList<BatModel>() {{
}}, this, mAnimator).setOnItemClickListener(this).setOnOutsideClickListener(this));
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new BatCallback(this));
itemTouchHelper.attachToRecyclerView(mRecyclerView.getView());
mRecyclerView.getView().setItemAnimator(mAnimator);
mRecyclerView.setAddItemListener(this);
findViewById(R.id.root).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.revertAnimation();
}
});
}
#Override
public void add(String string) {
mGoals.add(0, new Goal(string));
mAdapter.notify(AnimationType.ADD, 0);
}
#Override
public void delete(int position) {
mGoals.remove(position);
mAdapter.notify(AnimationType.REMOVE, position);
}
#Override
public void move(int from, int to) {
if (from >= 0 && to >= 0) {
mAnimator.setPosition(to);
BatModel model = mGoals.get(from);
mGoals.remove(model);
mGoals.add(to, model);
mAdapter.notify(AnimationType.MOVE, from, to);
if (from == 0 || to == 0) {
mRecyclerView.getView().scrollToPosition(Math.min(from, to));
}
}
}
#Override
public void onClick(BatModel item, int position) {
Toast.makeText(this, item.getText(), Toast.LENGTH_SHORT).show();
}
#Override
public void onOutsideClicked() {
mRecyclerView.revertAnimation();
}
}
I tried to use this code, from Mr Abhi instruction, I just edited a little bit for removing the toolbar, and some I solved.
This is my fragment.java
public class ToDoListFragment extends Fragment implements BatListener, OnItemClickListener, OnOutsideClickedListener {
private BatRecyclerView mRecyclerView;
private BatAdapter mAdapter;
private List<BatModel> mGoals;
private BatItemAnimator mAnimator;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.todo_list_fragment, null);
return root;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
// you can add listener of elements here
/*Button mButton = (Button) view.findViewById(R.id.button);
mButton.setOnClickListener(this); */
((TextView) view.findViewById(R.id.tdl_date)).setTypeface(TypefaceUtil.getAvenirTypeface(getActivity()));
mRecyclerView = (BatRecyclerView) view.findViewById(R.id.tdl_bat_recyclerView);
mAnimator = new BatItemAnimator();
mRecyclerView.getView().setLayoutManager(new LinearLayoutManager(getActivity()));
mRecyclerView.getView().setAdapter(mAdapter = new BatAdapter(mGoals = new ArrayList<BatModel>() {{
}}, this, mAnimator).setOnItemClickListener(this).setOnOutsideClickListener(this));
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new BatCallback(this));
itemTouchHelper.attachToRecyclerView(mRecyclerView.getView());
mRecyclerView.getView().setItemAnimator(mAnimator);
mRecyclerView.setAddItemListener(this);
view.findViewById(R.id.root).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.revertAnimation();
}
});
}
#Override
public void add(String string) {
mGoals.add(0, new Goal(string));
mAdapter.notify(AnimationType.ADD, 0);
}
#Override
public void delete(int position) {
mGoals.remove(position);
mAdapter.notify(AnimationType.REMOVE, position);
}
#Override
public void move(int from, int to) {
if (from >= 0 && to >= 0) {
mAnimator.setPosition(to);
BatModel model = mGoals.get(from);
mGoals.remove(model);
mGoals.add(to, model);
mAdapter.notify(AnimationType.MOVE, from, to);
if (from == 0 || to == 0) {
mRecyclerView.getView().scrollToPosition(Math.min(from, to));
}
}
}
#Override
public void onClick(BatModel item, int position) {
Toast.makeText(getActivity(), item.getText(), Toast.LENGTH_SHORT).show();
}
#Override
public void onOutsideClicked() {
mRecyclerView.revertAnimation();
}
But it crushed when I started the app. the log showed that No view found for id 0x7f09004c (package:id/container) for fragment.
I hope you guys could help me as you teach me. Thanks for the second time.
To convert an Activity to a Fragment, you first have to extend Fragment. then you'll have to make some basic necessary changes in the code like:
1.onCreateView(LayoutInflater, ViewGroup, Bundle) instead of onCreate
2.findViewById() becomes getView().findViewById().
Your sample code:
public class ToDoList extends Fragment implements BatListener, OnItemClickListener, OnOutsideClickedListener {
private BatRecyclerView mRecyclerView;
private BatAdapter mAdapter;
private List<BatModel> mGoals;
private BatItemAnimator mAnimator;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.todo_list_fragment, null);
return root;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
// you can add listener of elements here
/*Button mButton = (Button) view.findViewById(R.id.button);
mButton.setOnClickListener(this); */
// Navigator
FoldingTabBar tabBar = (FoldingTabBar) view.findViewById(R.id.folding_tab_bar);
tabBar.setOnFoldingItemClickListener(new FoldingTabBar.OnFoldingItemSelectedListener() {
#Override
public boolean onFoldingItemSelected(#NotNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_profile:
Intent intent0 = new Intent(ToDoList.this, Home.class);
startActivity(intent0);
break;
case R.id.menu_todo:
break;
case R.id.menu_schedule:
Intent intent1 = new Intent(ToDoList.this, TimeTable.class);
startActivity(intent1);
break;
case R.id.menu_settings:
break;
}
return false;
}
});
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((TextView) view.findViewById(R.id.text_title)).setTypeface(TypefaceUtil.getAvenirTypeface(this));
mRecyclerView = (BatRecyclerView) view.findViewById(R.id.bat_recycler_view);
mAnimator = new BatItemAnimator();
mRecyclerView.getView().setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.getView().setAdapter(mAdapter = new BatAdapter(mGoals = new ArrayList<BatModel>() {{
}}, this, mAnimator).setOnItemClickListener(this).setOnOutsideClickListener(this));
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new BatCallback(this));
itemTouchHelper.attachToRecyclerView(mRecyclerView.getView());
mRecyclerView.getView().setItemAnimator(mAnimator);
mRecyclerView.setAddItemListener(this);
view.findViewById(R.id.root).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRecyclerView.revertAnimation();
}
});
}
#Override
public void add(String string) {
mGoals.add(0, new Goal(string));
mAdapter.notify(AnimationType.ADD, 0);
}
#Override
public void delete(int position) {
mGoals.remove(position);
mAdapter.notify(AnimationType.REMOVE, position);
}
#Override
public void move(int from, int to) {
if (from >= 0 && to >= 0) {
mAnimator.setPosition(to);
BatModel model = mGoals.get(from);
mGoals.remove(model);
mGoals.add(to, model);
mAdapter.notify(AnimationType.MOVE, from, to);
if (from == 0 || to == 0) {
mRecyclerView.getView().scrollToPosition(Math.min(from, to));
}
}
}
#Override
public void onClick(BatModel item, int position) {
Toast.makeText(this, item.getText(), Toast.LENGTH_SHORT).show();
}
#Override
public void onOutsideClicked() {
mRecyclerView.revertAnimation();
}
}
I haven't edited all code and further changes maybe required. Do the changes accordingly.
I have an app that displays my e-mail via microsoft graph api.
Everything but 1 things i working fine so far. When the list first loads in, all info is correctly displayed, but when i scroll down, then back up. The imageview of the attachement sits on the wrong rows. It just displays on rows without attachement. In the adapter i have an if clausule which says to only show the image in the row if the hasAttachement value is "true".. I really don't get why it is redrawin the image in the wrongs rows..
The method where i set the attachement is called:
setBijlage() in MessagesAdapter
EDIT: If i click the row in my app, that row displays correctly again (gains an icon if it has attachement, and deletes it if it doesn't)
MailActivity.java
public class MailActivity extends AppCompatActivityRest implements SwipeRefreshLayout.OnRefreshListener, MessagesAdapter.MessageAdapterListener {
private String currentFolder;
private String currentUser;
private List<Message> messages = new ArrayList<>();
private RecyclerView recyclerView;
private MessagesAdapter mAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private ActionModeCallback actionModeCallback;
private ActionMode actionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_mail);
super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
currentFolder = getString(R.string.inbox);
currentUser = getIntent().getStringExtra("USER_EMAIL");
setActionBarMail(currentFolder, currentUser);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
actionModeCallback = new ActionModeCallback();
// show loader and fetch messages
swipeRefreshLayout.post(
new Runnable() {
#Override
public void run() {
getAllMails(15);
}
}
);
}
#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_search) {
Toast.makeText(getApplicationContext(), "Search...", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void processResponse(OutlookObjectCall outlookObjectCall, JSONObject response) {
switch (outlookObjectCall) {
case READUSER: {
System.out.println("reading user");
} break;
case READMAIL: {
messages.clear();
JSONObject list = response;
try {
JSONArray mails = list.getJSONArray("value");
Type listType = new TypeToken<List<Message>>() {
}.getType();
messages = new Gson().fromJson(String.valueOf(mails), listType);
for (Message message : messages) {
message.setColor(getRandomMaterialColor("400"));
}
System.out.println(messages.get(2).getFrom().getEmailAddress().getName());
mAdapter = new MessagesAdapter(this, messages, this);
recyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
break;
case SENDMAIL: {
System.out.println("Just send a mail." );
}
}
}
#Override
public void onRefresh() {
// swipe refresh is performed, fetch the messages again
getAllMails(15);
}
#Override
public void onIconClicked(int position) {
if (actionMode == null) {
actionMode = startSupportActionMode(actionModeCallback);
}
toggleSelection(position);
}
#Override
public void onIconImportantClicked(int position) {
// Star icon is clicked,
// mark the message as important
Message message = messages.get(position);
message.setImportance("normal");
messages.set(position, message);
mAdapter.notifyDataSetChanged();
}
#Override
public void onMessageRowClicked(int position) {
// verify whether action mode is enabled or not
// if enabled, change the row state to activated
if (mAdapter.getSelectedItemCount() > 0) {
enableActionMode(position);
} else {
// read the message which removes bold from the row
Message message = messages.get(position);
message.setIsRead("true");
messages.set(position, message);
mAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Read: " + message.getBodyPreview(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRowLongClicked(int position) {
// long press is performed, enable action mode
enableActionMode(position);
}
private void enableActionMode(int position) {
if (actionMode == null) {
actionMode = startSupportActionMode(actionModeCallback);
}
toggleSelection(position);
}
private void toggleSelection(int position) {
mAdapter.toggleSelection(position);
int count = mAdapter.getSelectedItemCount();
if (count == 0) {
actionMode.finish();
} 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.menu_action_mode, menu);
// disable swipe refresh if action mode is enabled
swipeRefreshLayout.setEnabled(false);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
// delete all the selected messages
deleteMessages();
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mAdapter.clearSelections();
swipeRefreshLayout.setEnabled(true);
actionMode = null;
recyclerView.post(new Runnable() {
#Override
public void run() {
mAdapter.resetAnimationIndex();
// mAdapter.notifyDataSetChanged();
}
});
}
}
// deleting the messages from recycler view
private void deleteMessages() {
mAdapter.resetAnimationIndex();
List<Integer> selectedItemPositions =
mAdapter.getSelectedItems();
for (int i = selectedItemPositions.size() - 1; i >= 0; i--) {
mAdapter.removeData(selectedItemPositions.get(i));
}
mAdapter.notifyDataSetChanged();
}
private void setActionBarMail(String title, String subtitle) {
getSupportActionBar().setTitle(title);
getSupportActionBar().setSubtitle(subtitle);
}
private void getAllMails(int aantalMails) {
swipeRefreshLayout.setRefreshing(true);
try {
new GraphAPI().getRequest(OutlookObjectCall.READMAIL, this, "/inbox/messages?$top=" + aantalMails);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
private int getRandomMaterialColor(String typeColor) {
int returnColor = Color.GRAY;
int arrayId = getResources().getIdentifier("mdcolor_" + typeColor, "array", getPackageName());
if (arrayId != 0) {
TypedArray colors = getResources().obtainTypedArray(arrayId);
int index = (int) (Math.random() * colors.length());
returnColor = colors.getColor(index, Color.GRAY);
colors.recycle();
}
return returnColor;
}
MessagesAdapter.java
public class MessagesAdapter extends RecyclerView.Adapter<MessagesAdapter.MyViewHolder> {
private Context mContext;
private List<Message> messages;
private MessageAdapterListener listener;
private SparseBooleanArray selectedItems;
// array used to perform multiple animation at once
private SparseBooleanArray animationItemsIndex;
private boolean reverseAllAnimations = false;
// index is used to animate only the selected row
// dirty fix, find a better solution
private static int currentSelectedIndex = -1;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener {
public TextView from, subject, message, iconText, timestamp;
public ImageView iconImp, imgProfile, imgBijlage;
public LinearLayout messageContainer;
public RelativeLayout iconContainer, iconBack, iconFront;
public MyViewHolder(View view) {
super(view);
from = (TextView) view.findViewById(R.id.from);
subject = (TextView) view.findViewById(R.id.txt_primary);
message = (TextView) view.findViewById(R.id.txt_secondary);
iconText = (TextView) view.findViewById(R.id.icon_text);
timestamp = (TextView) view.findViewById(R.id.timestamp);
iconBack = (RelativeLayout) view.findViewById(R.id.icon_back);
iconFront = (RelativeLayout) view.findViewById(R.id.icon_front);
iconImp = (ImageView) view.findViewById(R.id.icon_star);
imgProfile = (ImageView) view.findViewById(R.id.icon_profile);
messageContainer = (LinearLayout) view.findViewById(R.id.message_container);
iconContainer = (RelativeLayout) view.findViewById(R.id.icon_container);
imgBijlage = (ImageView) view.findViewById(R.id.icon_attachement);
view.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View view) {
listener.onRowLongClicked(getAdapterPosition());
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return true;
}
}
public MessagesAdapter(Context mContext, List<Message> messages, MessageAdapterListener listener) {
this.mContext = mContext;
this.messages = messages;
this.listener = listener;
selectedItems = new SparseBooleanArray();
animationItemsIndex = new SparseBooleanArray();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
Message message = messages.get(position);
// displaying text view data
holder.from.setText(message.getFrom().getEmailAddress().getName());
holder.subject.setText(message.getSubject());
holder.message.setText(message.getBodyPreview());
System.out.println("EMAIL: " + position + " HAS ATTACHEMENT: " + message.getHasAttachments());
setBijlage(message, holder);
try {
setDate(message, holder);
} catch (ParseException e) {
e.printStackTrace();
}
// displaying the first letter of From in icon text
holder.iconText.setText(message.getFrom().getEmailAddress().getName().substring(0, 1));
// change the row state to activated
holder.itemView.setActivated(selectedItems.get(position, false));
// change the font style depending on message read status
applyReadStatus(holder, message);
// handle message star
applyImportant(holder, message);
// handle icon animation
applyIconAnimation(holder, position);
// display profile image
applyProfilePicture(holder, message);
// apply click events
applyClickEvents(holder, position);
}
private void setDate(Message message, MyViewHolder holder) throws ParseException {
String stringDate = message.getReceivedDateTime();
String COMPARE_FORMAT = "yyyy/MM/dd";
String OUTPUT_FORMAT_NOT_TODAY = "dd MMM";
String JSON_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat dateFormat = new SimpleDateFormat(COMPARE_FORMAT);
SimpleDateFormat formatter = new SimpleDateFormat(JSON_FORMAT);
SimpleDateFormat defaultFormat = new SimpleDateFormat(OUTPUT_FORMAT_NOT_TODAY);
//today date (check if today)
Date today = new Date();
String currentDate = dateFormat.format(today);
//hours (if today
Date date = formatter.parse(stringDate);
formatter.applyPattern(COMPARE_FORMAT);
String mailDate = formatter.format(date);
//dd/month (if not today)
boolean is24 = DateFormat.is24HourFormat(mContext);
if (mailDate.equals(currentDate)) {
if (is24) {
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm");
holder.timestamp.setText(outputFormat.format(date));
} else {
SimpleDateFormat outputFormat = new SimpleDateFormat("hh:mm a");
holder.timestamp.setText(outputFormat.format(date));
}
} else {
holder.timestamp.setText(defaultFormat.format(date));
}
}
private void setBijlage(Message message, MyViewHolder holder){
//set bijlage
if (message.getHasAttachments().toLowerCase().equals("true")){
holder.imgBijlage.setImageResource(R.drawable.ic_bijlage);
}
}
private void applyClickEvents(MyViewHolder holder, final int position) {
holder.iconContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onIconClicked(position);
}
});
holder.iconImp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onIconImportantClicked(position);
}
});
holder.messageContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onMessageRowClicked(position);
}
});
holder.messageContainer.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
listener.onRowLongClicked(position);
view.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return true;
}
});
}
private void applyProfilePicture(MyViewHolder holder, Message message) {
holder.imgProfile.setImageResource(R.drawable.bg_circle);
holder.imgProfile.setColorFilter(message.getColor());
holder.iconText.setVisibility(View.VISIBLE);
}
private void applyIconAnimation(MyViewHolder holder, int position) {
if (selectedItems.get(position, false)) {
holder.iconFront.setVisibility(View.GONE);
resetIconYAxis(holder.iconBack);
holder.iconBack.setVisibility(View.VISIBLE);
holder.iconBack.setAlpha(1);
if (currentSelectedIndex == position) {
FlipAnimator.flipView(mContext, holder.iconBack, holder.iconFront, true);
resetCurrentIndex();
}
} else {
holder.iconBack.setVisibility(View.GONE);
resetIconYAxis(holder.iconFront);
holder.iconFront.setVisibility(View.VISIBLE);
holder.iconFront.setAlpha(1);
if ((reverseAllAnimations && animationItemsIndex.get(position, false)) || currentSelectedIndex == position) {
FlipAnimator.flipView(mContext, holder.iconBack, holder.iconFront, false);
resetCurrentIndex();
}
}
}
// As the views will be reused, sometimes the icon appears as
// flipped because older view is reused. Reset the Y-axis to 0
private void resetIconYAxis(View view) {
if (view.getRotationY() != 0) {
view.setRotationY(0);
}
}
public void resetAnimationIndex() {
reverseAllAnimations = false;
animationItemsIndex.clear();
}
#Override
public long getItemId(int position) {
return messages.get(position).getAutoId();
}
private void applyImportant(MyViewHolder holder, Message message) {
if (message.getImportance().toLowerCase().equals("high")) {
holder.iconImp.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_star_black_24dp));
holder.iconImp.setColorFilter(ContextCompat.getColor(mContext, R.color.icon_tint_selected));
} else {
holder.iconImp.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_star_border_black_24dp));
holder.iconImp.setColorFilter(ContextCompat.getColor(mContext, R.color.icon_tint_normal));
}
}
private void applyReadStatus(MyViewHolder holder, Message message) {
if (message.getIsRead().toLowerCase().equals("true")) {
holder.from.setTypeface(null, Typeface.NORMAL);
holder.subject.setTypeface(null, Typeface.NORMAL);
holder.from.setTextColor(ContextCompat.getColor(mContext, R.color.subject));
holder.subject.setTextColor(ContextCompat.getColor(mContext, R.color.message));
} else {
holder.from.setTypeface(null, Typeface.BOLD);
holder.subject.setTypeface(null, Typeface.BOLD);
holder.from.setTextColor(ContextCompat.getColor(mContext, R.color.from));
holder.subject.setTextColor(ContextCompat.getColor(mContext, R.color.subject));
}
}
#Override
public int getItemCount() {
return messages.size();
}
public void toggleSelection(int pos) {
currentSelectedIndex = pos;
if (selectedItems.get(pos, false)) {
selectedItems.delete(pos);
animationItemsIndex.delete(pos);
} else {
selectedItems.put(pos, true);
animationItemsIndex.put(pos, true);
}
notifyItemChanged(pos);
}
public void clearSelections() {
reverseAllAnimations = true;
selectedItems.clear();
notifyDataSetChanged();
}
public int getSelectedItemCount() {
return selectedItems.size();
}
public List<Integer> getSelectedItems() {
List<Integer> items =
new ArrayList<>(selectedItems.size());
for (int i = 0; i < selectedItems.size(); i++) {
items.add(selectedItems.keyAt(i));
}
return items;
}
public void removeData(int position) {
messages.remove(position);
resetCurrentIndex();
}
private void resetCurrentIndex() {
currentSelectedIndex = -1;
}
public interface MessageAdapterListener {
void onIconClicked(int position);
void onIconImportantClicked(int position);
void onMessageRowClicked(int position);
void onRowLongClicked(int position);
}
}
Change setBijlage to this..
private void setBijlage(Message message, MyViewHolder holder){
//set bijlage
if (message.getHasAttachments().toLowerCase().equals("true")){
holder.imgBijlage.setVisibility(View.VISIBLE);
holder.imgBijlage.setImageResource(R.drawable.ic_bijlage);
}else{
holder.imgBijlage.setVisibility(View.GONE);
}
}
That's occours because the recyclerView reuses the references of the rows and in your case, some rows doesnt have any reference in holder.imgBijlage, causing missbehavior.
To solve this, put holder.imgBijlage.setImageResource(R.drawable.ic_bijlage); inside onBindViewHolder and change setBijlage to:
if (message.getHasAttachments().toLowerCase().equals("true")){
holder.imgBijlage.setVisibility(View.VISIBLE);
}else {
holder.imgBijlage.setVisibility(View.INVISIBLE);
}
Your icon will be hidden when there is no attachement
Hello am trying to delete an item from my listview am able to delete item from my db but my adapter is not getting updated I have attached the code below`
public class SavedPolygonFragment extends android.support.v4.app.Fragment implements RefreshListener {
private static String LOG_TAG = SavedPolygonFragment.class.getName();
private String message = "No message";
private ListView shapeList;
private TextView textView;
private Button startMainBtn;
private SavedShapeAdapter savedShapeAdapter;
private long shapeId;
private float scaleFactor;
private List<Shape> savedShapes = new ArrayList<>();
private StartDrawingListener startListener;
private DeleteShapesDialog deleteDialog;
public SavedPolygonFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
startListener = (StartDrawingListener) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_one, container, false);
savedShapes = getArguments().getParcelableArrayList("shapes");
AssetLog.verbose(LOG_TAG, "savedshapes.size " + savedShapes.size());
shapeList = (ListView) view.findViewById(R.id.shapeList);
textView = (TextView) view.findViewById(R.id.polygonTitle);
startMainBtn = (Button) view.findViewById(R.id.gotoMain);
startMainBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startListener.startMainReceived();
}
});
if (!savedShapes.isEmpty() && !savedShapes.equals(null) && savedShapes.size() != 0) {
textView.setText("Polygons");
shapeList.setVisibility(View.VISIBLE);
startMainBtn.setVisibility(View.GONE);
if (savedShapeAdapter != null) {
savedShapeAdapter.notifyDataSetChanged();
} else {
savedShapeAdapter = new SavedShapeAdapter(savedShapes, getActivity());
shapeList.setAdapter(savedShapeAdapter);
shapeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
MainActivity_.intent(getActivity())
.savedProjectId(ProjectShapesActivity.projId)
.scaleFactor(ProjectShapesActivity.scaleFactor)
.shapeId(((Shape) view.getTag()).getShapeId())
.lineId(-1)
.pointId(-1)
.start();
}
});
}
}
else{
shapeList.setVisibility(View.GONE);
startMainBtn.setVisibility(View.VISIBLE);
textView.setText("Sorry no shapes are saved");
}
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerForContextMenu(shapeList);
}
#Override
public void onRefreshPressed() {
}
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
shapeId = info.id;
menu.add(Menu.NONE, R.id.deleteShapes, Menu.NONE, "Delete");
menu.add(Menu.NONE, R.id.editShapes, Menu.NONE, "Edit");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.refresh:
return false;
case R.id.deleteShapes:
if(deleteDialog == null){
Bundle bundle = new Bundle();
bundle.putString("SHAPE", "SHAPE");
bundle.putLong("shapeId", shapeId);
deleteDialog = new DeleteShapesDialog();
deleteDialog.setArguments(bundle);
deleteDialog.show(getActivity().getFragmentManager().beginTransaction(), "showDeleteDialog");
}
return true;
case R.id.editShapes:
return true;
}
return super.onContextItemSelected(item);
}
public void onDataChanged(long shapeid) {
Shape shape;
for (int i = 0; i <savedShapes.size() ; i++) {
shape = savedShapes.get(i);
if(shape.getShapeId() == shapeid){
savedShapes.remove(i);
shapeList.removeViewAt(i);
shapeList.invalidate();
savedShapeAdapter.notifyDataSetChanged();
break;
}
}
}
}
`
Now when user selects yes from deleteDialog i wrote a callback to my activity and in the corresponding methods this is what I do
SavedPolygonFragment polygonFragment = new SavedPolygonFragment();
polygonFragment.onDataChanged(shapeId);
Can somebody show me whats wrong
/////EDIT 1
public void onDataChanged(long shapeid) {
savedShapeAdapter.removeItemById(shapeid);
}
and my adapter
public void removeItemById(long itemId){
for(int i =0; i< shapeList.size() ; i++){
if(shapeList.get(i).getShapeId() == itemId){
shapeList.remove(i);
}
}
notifyDataSetChanged();
}
am able to delete item from my db but my adapter is not getting
updated
Problem is caused by :
savedShapes.remove(i);
line.
Currently removing item from ArrayList which is in SavedPolygonFragment class, not from ArrayList which is used by Adapter to fill ListView.
Using current approach try this way will work by setting new Adapter every time:
if(shape.getShapeId() == shapeid){
savedShapes.remove(i);
savedShapeAdapter = new SavedShapeAdapter(savedShapes, getActivity());
shapeList.setAdapter(savedShapeAdapter);
savedShapeAdapter.notifyDataSetChanged();
break;
}
But this is not optimize solution to create and set new object of Adapter every-time when want to update ListView.
Right approach is create a method in SavedShapeAdapter class for removing item for ArrayList which is used by Adapter and then call it inside onDataChanged method:
public void deleteRowItem(int index){
this.savedShapes.remove(index);
this..notifyDataSetChanged();
}
Now call deleteRowItem when want to delete row item from ListView :
if(shape.getShapeId() == shapeid){
savedShapeAdapter.deleteRowItem(i);
break;
}
I am using a ViewPager in my application and I have three tabs in it; I am using ViewPager inside a fragment. Now my problem here is, I am getting data correctly while loading the application, but when I go next page and then back to ViewPager, the data is lost and tabs are not working. Please assist me. Below is my code:
import com.devpoint.rprtjobs.R;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.design.widget.TabLayout;
public class MainActivity extends Fragment {
// Declaring Your View and Variables
Toolbar toolbar;
ViewPager pager;
SwipeViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"OnGoing","UpComing","Expired"};
int Numboftabs =3;
private View rootView;
#SuppressWarnings("deprecation")
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
rootView = inflater.inflate(R.layout.activity_main,
container, false);
adapter = new SwipeViewPagerAdapter(getActivity().getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
pager.setOffscreenPageLimit(3);
pager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
if(position ==0)
{
SwipeViewPagerAdapter.Pagename = "ListOnGoing";
}
else if(position ==1)
{
SwipeViewPagerAdapter.Pagename = "ListUpComing";
}
else if(position ==2)
{
SwipeViewPagerAdapter.Pagename = "ListExpired";
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return rootView;
}
}
Here is my adapter:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by Edwin on 15/02/2015.
*/
public class SwipeViewPagerAdapter extends FragmentPagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
public static String Pagename="ListOnGoing";
// Build a Constructor and assign the passed Values to appropriate values in the class
public SwipeViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
//Pagename = "ListOnGoing";
ListOnGoing mListOnGoing = new ListOnGoing();
return mListOnGoing;
case 1:
//Pagename = "ListUpComing";
ListUpComing mListUpComing = new ListUpComing();
return mListUpComing;
case 2:
//Pagename = "ListExpired";
ListExpaire mListExpaire = new ListExpaire();
return mListExpaire;
default:
return null;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
And here is one of my fragments:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
#SuppressLint("ShowToast")
public class ListOnGoing extends Fragment implements OnItemClickListener {
Boolean isInternetPresent = false;
ConnectionDetector connectdetector;
public static ListView swipelisview;
Activity activity;
public static ProductListAdapter productListAdapter;
SharedPreference sharedPreference;
String LoggedIn;
boolean fragmentAlreadyLoaded = false;
#SuppressWarnings("deprecation")
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.listener = (FragmentActivity) activity;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
try {
super.onViewCreated(view, savedInstanceState);
swipelisview = (ListView) rootView.findViewById(R.id.list);
View emptyView = rootView.findViewById(R.id.emptyView);
swipelisview.setEmptyView(emptyView);
if (savedInstanceState == null && !fragmentAlreadyLoaded) {
fragmentAlreadyLoaded = true;
repoObject = SplashScreen.getRepo();
session = new SessionManager(getActivity());
HashMap<String, String> Radious = session.getRadiousName();
Radiosname = Radious.get(SessionManager.KEY_RadiousName);
//LoadActivity.Status="";
GPlaces = new GetAllGooglePlaces();
GPlaces.GetOpportunityList("", Radiosname, getActivity());
DisPlayOppList();
}
productListAdapter = new ProductListAdapter(getActivity(),
GetAllGooglePlaces.ArrayListOngoing);
swipelisview.setAdapter(productListAdapter);
productListAdapter.notifyDataSetChanged();
session = new SessionManager(getActivity());
HashMap<String, String> Radious = session.getRadiousName();
Radiosname = Radious.get(SessionManager.KEY_RadiousName);
searchedit = (EditText) rootView.findViewById(R.id.searchbox);
Button searchbtn = (Button) rootView.findViewById(R.id.searchbtn);
searchedit = (EditText) rootView.findViewById(R.id.searchbox);
clearbtn = (Button) rootView.findViewById(R.id.clearbtn);
searchedit.addTextChangedListener(watch);
clearbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
LoadActivity.Status="";
searchedit.setText("");
GPlaces.GetOpportunityList("", Radiosname, getActivity());
DisPlayOppList();
}
});
searchbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
multipleCat = "";
GetAllGooglePlaces.ArrayListOngoing = new CopyOnWriteArrayList<>();
SearchText = searchedit.getText()
.toString();
LoadActivity.Status = "Search";
if (LoadActivity.isOnline) {
GPlaces.GetOpportunityList(SearchText, Radiosname, getActivity());
DisPlayOppList();
}
else {
List<OpportunityTable> alloffers = repoObject.roffertable
.getAlloffersbySearchKeyword(SearchText);
if (alloffers != null) {
GPlaces.FillArrayListOffline(alloffers,"OnGoing");
}
}
}
});
}
});
HashMap<String, String> user = session.getLogin();
LoggedIn = user.get(SessionManager.KEY_Login);
if (LoggedIn == null) {
LoggedIn = "";
}
connectdetector = new ConnectionDetector(getActivity());
try {
// Check if Internet present
isInternetPresent = connectdetector.isConnectingToInternet();
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
footerlayout = (LinearLayout) rootView.findViewById(R.id.footerlayout);
footerlayout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
swipelisview.requestDisallowInterceptTouchEvent(true);
return true;
}
});
swipelisview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,
final int position, long id) {
InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(swipelisview.getWindowToken(), 0);
try {
final DetailsViewpagerFragment mDetailsViewpagerFragment = new DetailsViewpagerFragment();
String url;
if (LoadActivity.isOnline) {
progresdialog = new ProgressDialog(getActivity());
progresdialog.setMessage(Html
.fromHtml("<b>Search</b><br/>Loading Details..."));
progresdialog.setIndeterminate(false);
progresdialog.setCancelable(false);
progresdialog.show();
ListDetails product = GetAllGooglePlaces.ArrayListOngoing
.get(position);
OpportunityID = product.getOfferID();
url = LoadActivity.BaseUri + "SaveUserViewedOpportunities";
JsonObjectRequest jsObjRequest;
jsObjRequest = new JsonObjectRequest(
Request.Method.POST, url,
getSaveViewUserParams(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pagename = "Userplaceslist";
mDetailsViewpagerFragment
.setClickList(position);
FragmentManager fragment = getFragmentManager();
fragment.beginTransaction()
.replace(R.id.frame_container,
mDetailsViewpagerFragment)
.commit();
LoadActivity.CURRENTFRAGMENT = EnumModuleTags.SinglePlaceActivity;
ModuleFragmentBackStackingClass
.AddtoStack(
mDetailsViewpagerFragment,
EnumModuleTags.SinglePlaceActivity,
getString(R.string.mainfrgment_rprt));
LoadActivity.updateActionbarMenu();
progresdialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(
VolleyError error) {
Toast.makeText(getActivity(), "False",
Toast.LENGTH_LONG).show();
progresdialog.dismiss();
}
});
AppController.getInstance().addToRequestQueue(
jsObjRequest);
} else {
mDetailsViewpagerFragment.setClickList(position);
FragmentManager fragment = getFragmentManager();
fragment.beginTransaction()
.replace(R.id.frame_container,
mDetailsViewpagerFragment).commit();
LoadActivity.CURRENTFRAGMENT = EnumModuleTags.SinglePlaceActivity;
ModuleFragmentBackStackingClass.AddtoStack(
mDetailsViewpagerFragment,
EnumModuleTags.SinglePlaceActivity,
getString(R.string.mainfrgment_rprt));
}
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
private JSONObject getSaveViewUserParams() {
JSONObject params = new JSONObject();
HashMap<String, String> UserId = session.getUserID();
String UserIdVal = UserId.get(SessionManager.KEY_UserID);
if (!(UserIdVal == null)) {
UserIdVal = UserId.get(SessionManager.KEY_UserID);
} else {
UserIdVal = "0";
}
try {
params.put("UserId", UserIdVal);
params.put("OpportunityID", OpportunityID);
params.put("UserViewedID", 0);
params.put("Shortlisted", true);
params.put("KeyValue", null);
} catch (JSONException e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
return params;
}
});
// Click The FavoritesItem on LongPress
swipelisview.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
InputMethodManager imm;
imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(swipelisview.getWindowToken(), 0);
try {
ImageView button;
button = (ImageView) view
.findViewById(R.id.fav_checkbox);
String tag = button.getTag().toString();
if (tag.equals(getString(R.string.grey_favcolor))) {
sharedPreference.addFavorite(activity,
GetAllGooglePlaces.ArrayListOngoing.get(position));
button.setTag(getString(R.string.red_favcolor));
button.setImageResource(R.drawable.checked);
} else if (tag.equals(getString(R.string.red_favcolor))){
sharedPreference.removeFavorite(activity,
GetAllGooglePlaces.ArrayListOngoing.get(position));
button.setTag(getString(R.string.grey_favcolor));
button.setImageResource(R.drawable.unchecked);
}
return true;
} catch (NotFoundException e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
Toast.makeText(getActivity(), e.getMessage(),
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return true;
}
});
// Code placed here will be executed even when the fragment comes from
// backstack
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
// String APIkey ="AIzaSyCAekTB0o1MuSYvUb-8HTZxhlJHE8yBUfI";
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
//setRetainInstance(true);
} catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
#SuppressWarnings("static-access")
#SuppressLint({ "CutPasteId", "ClickableViewAccessibility" })
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
//setRetainInstance(true);
try
{
Tracker t = ((Analytics) getActivity().getApplication()).getTracker(
TrackerName.APP_TRACKER);
t.setScreenName("UserPlaces Listview");
t.send(new HitBuilders.AppViewBuilder().build());
}
catch(Exception e)
{
Toast.makeText(getActivity().getApplication(), "Error"+e.getMessage(), 1).show();
}
rootView = inflater.inflate(R.layout.user_places_listview, container,
false);
swipelisview = (ListView) rootView.findViewById(R.id.list);
View emptyView = rootView.findViewById(R.id.emptyView);
swipelisview.setEmptyView(emptyView);
return rootView;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rootView;
}
TextWatcher watch = new TextWatcher(){
#Override
public void afterTextChanged(Editable arg0) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void onTextChanged(CharSequence s, int a, int b, int c) {
if(c == 0){
clearbtn.setVisibility(View.GONE);
}
else {
clearbtn.setVisibility(View.VISIBLE);
}
}};
protected void LoadSearchPlaces(String searchparam) {
try {
if (LoadActivity.isOnline) {
JsonArrayRequest movieReq = new JsonArrayRequest("http://192.168.2.10/RPRT.WebApi/api/RPRT/" + "SearchPlaces/"+searchparam,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
List<HashMap<String, String>> aList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
JSONObject json_data;
try {
json_data = response.getJSONObject(i);
HashMap<String, String> hm = new HashMap<>();
hm.put("Address", json_data.getString("Address"));
hm.put("City", json_data.getString("City"));
hm.put("Latitude", json_data.getString("Latitude"));
hm.put("Longitude", json_data.getString("Longitude"));
aList.add(hm);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String[] from = { "Address"} ;
int[] to = { R.id.tv };
SimpleAdapter adapterId = new SimpleAdapter(getActivity(), aList,
R.layout.user_places_dropdown_listitem, from, to);
//final AutoCompleteTextView autoCompView = (AutoCompleteTextView) rootView.findViewById(R.id.autoCompleteTextView);
autoCompView.setAdapter(adapterId);
autoCompView.setThreshold(1);
// Pname.setThreshold(1);
autoCompView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#SuppressWarnings("unchecked")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> hm = (HashMap<String, String>) parent
.getAdapter().getItem(position);
autoCompView.setText(hm.get("Address"));
SplashScreen.nwLocation.setLatitude(Double.parseDouble(hm.get("Latitude")));
SplashScreen.nwLocation.setLongitude(Double.parseDouble(hm.get("Longitude")));
HashMap<String, String> Radious = session.getRadiousName();
final String Radiosname;
Radiosname = Radious.get(SessionManager.KEY_RadiousName);
multipleCat="";
ProgressDialog progresdialog = new ProgressDialog(getActivity());
progresdialog.setMessage(Html
.fromHtml("<b>Search</b><br/>Loading Details..."));
progresdialog.setIndeterminate(false);
progresdialog.setCancelable(false);
//progresdialog.show();
LoadActivity.Status="";
GPlaces.GetOpportunityList(SearchText, Radiosname, getActivity());
DisPlayOppList();
searchdialog.cancel();
}
});
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(
VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(movieReq);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void DisPlayOppList() {
try {
pdialog = new ProgressDialog(getActivity());
pdialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Details..."));
pdialog.setIndeterminate(false);
pdialog.setCancelable(false);
if(LoadActivity.Status.equals("Slidemenulist"))
{
int CategoryId = 0;
switch (CopyOfListOnGoing.multipleCat) {
case "Books":
CategoryId = 1;
break;
case "BeautyandFashion":
CategoryId = 2;
break;
case "Electronic":
CategoryId = 3;
break;
case "Food":
CategoryId = 4;
break;
case "HomeService":
CategoryId = 5;
break;
case "Jobs":
CategoryId = 6;
break;
case "RealEstate":
CategoryId = 7;
break;
case "Vehicles":
CategoryId = 8;
break;
}
List<OpportunityTable> alloffers = repoObject.roffertable
.getAllCatOpp(CategoryId , Radiosname);
if (alloffers != null) {
GPlaces.FillArrayListOffline(alloffers,"OnGoing");
}
} else {
List<OpportunityTable> alloffers = repoObject.roffertable
.getAlloffers(Integer.parseInt(Radiosname));
if (alloffers != null) {
GPlaces.FillArrayListOffline(alloffers,"OnGoing");
}
}
}
catch (Exception e) {
e.printStackTrace();
PostLogcatErrors ple = new PostLogcatErrors();
ple.PostLogcatErorrs(e);
}
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
multipleCat = "";
DisPlayOppList();
}
/* #Override
public void onResume() {
Log.e("DEBUG", "onResume of Userplace ListView");
super.onResume();
}*/
#Override
public void onPause() {
Log.e("DEBUG", "OnPause of Userplace ListView");
super.onPause();
}
}
And the remaining fragments look the same. Please help me.
After a little research, I found the solution to my problem.
I was originally calling getactivity().getSupportFragmentmanager(). However, the correct code is getChildFragmentManager()
In you adapter extend FragmentStatePagerAdapter instead of FragmentPagerAdapter it will solve your problem. Let me know if you have any problem.
Reason (quoting from javadoc)
/**
The [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
[android.support.v4.app.FragmentStatePagerAdapter].
*/
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setOffscreenPageLimit(2);// no of fragments
public float getPageWidth(int position)
{
if (position == 0 || position == 2)
{
return 0.8f;
}
return 1f;
}
I think your problem has already being solved let this be a help to others.I had this same issue and I solved it by extending the adapter class with FragmentStatePagerAdapter instead of FragmentPagerAdapter. This worked for me perfectly hope it works for you guys as well...
I would like to ask how can I detect when I try to back to another fragment.
So I have this code:
fragmentManager.replace(R.id.fragment_searched_data_xml, fragment).addToBackStack(null).commit();
that lets me back on that fragment. Now the question is:
when I press the back button from the current fragment so I can go back to initial fragment can I detect it??
public static class FragmentMainClass extends Fragment {
int i;
public FragmentMainClass() {
}
public FragmentMainClass(int i) {
this.i = i;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(
R.layout.fragment_searched_data, container, false);
TextView sn = (TextView) rootView.findViewById(R.id.stop_name);
TextView sc = (TextView) rootView.findViewById(R.id.stop_code);
String prefix = getArguments().getString("bussStopName");
if (sn != null && sc != null) {
if (prefix.contains("/")) {
if (prefix.contains("/ ")) {
sn.setText(prefix.replace("\"", "").split("/ ")[0] + "\n" + prefix.replace("\"", "").split("/ ")[1]);
sc.setText(getArguments().getString("bussStopCode"));
} else {
sn.setText(prefix.replace("\"", "").split("/")[0] + "\n" + prefix.replace("\"", "").split("/")[1]);
sc.setText(getArguments().getString("bussStopCode"));
}
} else {
sn.setPadding(20, 40, 0, 0);
sn.setText(prefix.replace("\"", ""));
sc.setText(getArguments().getString("bussStopCode"));
}
}
final LinearLayout child = (LinearLayout) rootView
.findViewById(R.id.search_result_data_box);
LayoutParams params = (LayoutParams) child.getLayoutParams();
//child.setVisibility(View.GONE);
// params.height = 0;
widthListView = container.getWidth();
rootView.setTranslationX(-container.getWidth());
rootView.animate().setStartDelay(300).translationX(0)
.withEndAction(new Runnable() {
#Override
public void run() {
conreq = new ConnnectionRequest("97", getArguments().getString("bussStopCode"));
//expand(child);
initializeResultList(rootView);
// rootView.setVisibility(View.INVISIBLE);
}
});
return rootView;
}
public static void expand(final View v) {
final int targtetHeight = v.getMeasuredHeight();
v.getLayoutParams().height = 0;
v.setVisibility(View.VISIBLE);
Animation a = new Animation() {
#Override
protected void applyTransformation(float interpolatedTime,
Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1 ? LayoutParams.WRAP_CONTENT
: (int) (targtetHeight * interpolatedTime);
v.requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
a.setDuration((int) (targtetHeight / v.getContext().getResources()
.getDisplayMetrics().density));
v.startAnimation(a);
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
}
public void initializeResultList(View v) {
result_list = (ListView) v.findViewById(R.id.list_view_results);
//(PullToRefreshListView) v.findViewById(R.id.list_view_results);;
final ResultDataCustomAdapter customAdapter = new ResultDataCustomAdapter(getActivity(), R.layout.pull_refresh_list_item, conreq.getCollectedData().getBusRouteSetData());
//prlv.prepareForRefresh();
((PullToRefreshListView) result_list).setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
result_list.setAdapter(customAdapter);
result_list.setVisibility(View.VISIBLE);
result_list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> av, final View view,
final int i, long i2) {
view.animate().setDuration(500).translationX(widthListView).alpha(0).
withEndAction(new Runnable() {
#Override
public void run() {
//setResult(Activity.RESULT_OK,new Intent().putExtra("bussStopCode", data.get(i).getStopCode()).putExtra("bussStopName", data.get(i).getStopName()));
////int get 1
//data.remove(i);
int temporaryInteger = i;
//customAdapter.notifyDataSetChanged();
//view.setTranslationX(0);
Log.d("data",conreq.getCollectedData().getBusRouteSetData().get(temporaryInteger - 1).getRouteHeading());
Bundle bundle = new Bundle();
bundle.putString("busdestination", conreq.getCollectedData().getBusRouteSetData().get(temporaryInteger-1).getRouteHeading());
bundle.putString("busnumber", conreq.getCollectedData().getBusRouteSetData().get(temporaryInteger-1).getRouteNo());
Fragment fragment = new FragmentNextTripForStop();
fragment.setArguments(bundle);
FragmentTransaction fragmentManager = getFragmentManager().beginTransaction();
fragmentManager.setCustomAnimations(R.anim.left_right_anim_x_left,R.anim.left_right_anim_x_right);
fragmentManager.replace(R.id.fragment_searched_data_xml, fragment).addToBackStack(null).commit();
result_list.setVisibility(View.GONE);
// finish();
//overridePendingTransition(R.anim.right_left_anim_x_left,R.anim.right_left_anim_x_right);
}
});
}});
}
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
;
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
// Call onRefreshComplete when the list has been refreshed.
((PullToRefreshListView) result_list).onRefreshComplete();
super.onPostExecute(result);
}
}
}
While Adding your fragment into host layout add fragment into stack
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.home_fragment, fragment)
.addToBackStack(fragment.getTag())
.commit();
In your onBackPressed()
if (getSupportFragmentManager().getBackStackEntryCount() >= 0) {
getSupportFragmentManager().popBackStack();
}else{
super.onBackPressed();
}