Android 中切换选项卡片段之间的延迟
Lag between switching tab fragment in Android
我遇到一个问题,每当我在不同的选项卡之间切换时,该过程都会滞后一两秒钟。我怎样才能消除这种滞后?片段的 oncreate 函数中没有这样的东西。我在这里发布代码。
这是调用片段 Dashboardnew 的 activity 的代码:
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);
}
}
Dashboardnew 片段的代码是:
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);
}
}
}
这里是已完成任务的代码:
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);
}
}
});
}
}
这是待处理任务的代码:
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();
}
}
首先我不明白你为什么创建两次片段
你实际上在这里创建了片段
private void createViewPager(ViewPager viewPager) {
adapter = new DashboardNew.ViewPagerAdapter(getChildFragmentManager());
adapter.addFrag(new CompletedTasks(), "Completed");
adapter.addFrag(new PendingTasks(), "Pending");
viewPager.setAdapter(adapter);
}
然后在此处创建它们。再次
@Override
public Fragment getItem(int position) {
if (position == 0)
return new CompletedTasks();
else
return new PendingTasks();
}
我想正确的方法是删除这些行
adapter.addFrag(new CompletedTasks(), "Completed");
adapter.addFrag(new PendingTasks(), "Pending");
在其他情况下,屏幕旋转会有很大问题。
您可以设置离屏限制(默认只有 1 个),这样片段只会创建一次,不会被删除
viewPager.setOffscreenPageLimit(2);
我也拒绝理解这些行的意思
completedTasks.add(new completedTasks(...);
是CompletedTasks片段吗?你添加什么以及如何添加?
There is no such thing in onCreate() function of the fragments.
但它仍然落后,对吧?我认为问题在于您的布局太重,因为您在 onCreateView() 中所做的唯一工作就是设置布局。
请检查您的图片是否具有很高的像素密度。这是最常见的错误。 Android 系统需要时间将布局中的那些高像素图像转换为适合您的设备的较低像素密度,这需要时间并导致延迟。
其他原因可能是布局层次结构不正确。
有此问题的朋友,请使用cardviews和recyclerviews。列表视图的数据太多。改为使用 cardviews 和 recyclerviews,延迟消失了。
您应该从 FragmentActivity
扩展您的容器 activity
public class MainActivity extends FragmentActivity
{
}
this is very fast switch between fragment.
最好在 xml 布局中使用标签
并显示,单击选项卡或底部选项卡时隐藏
//代码示例:
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.show(fm.findFragmentById(fragment))
.hide(fm.findFragmentById(activePage))
.commit();
我遇到一个问题,每当我在不同的选项卡之间切换时,该过程都会滞后一两秒钟。我怎样才能消除这种滞后?片段的 oncreate 函数中没有这样的东西。我在这里发布代码。
这是调用片段 Dashboardnew 的 activity 的代码:
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);
}
}
Dashboardnew 片段的代码是:
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);
}
}
}
这里是已完成任务的代码:
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);
}
}
});
}
}
这是待处理任务的代码:
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();
}
}
首先我不明白你为什么创建两次片段
你实际上在这里创建了片段
private void createViewPager(ViewPager viewPager) {
adapter = new DashboardNew.ViewPagerAdapter(getChildFragmentManager());
adapter.addFrag(new CompletedTasks(), "Completed");
adapter.addFrag(new PendingTasks(), "Pending");
viewPager.setAdapter(adapter);
}
然后在此处创建它们。再次
@Override
public Fragment getItem(int position) {
if (position == 0)
return new CompletedTasks();
else
return new PendingTasks();
}
我想正确的方法是删除这些行
adapter.addFrag(new CompletedTasks(), "Completed");
adapter.addFrag(new PendingTasks(), "Pending");
在其他情况下,屏幕旋转会有很大问题。
您可以设置离屏限制(默认只有 1 个),这样片段只会创建一次,不会被删除
viewPager.setOffscreenPageLimit(2);
我也拒绝理解这些行的意思
completedTasks.add(new completedTasks(...);
是CompletedTasks片段吗?你添加什么以及如何添加?
There is no such thing in onCreate() function of the fragments.
但它仍然落后,对吧?我认为问题在于您的布局太重,因为您在 onCreateView() 中所做的唯一工作就是设置布局。
请检查您的图片是否具有很高的像素密度。这是最常见的错误。 Android 系统需要时间将布局中的那些高像素图像转换为适合您的设备的较低像素密度,这需要时间并导致延迟。 其他原因可能是布局层次结构不正确。
有此问题的朋友,请使用cardviews和recyclerviews。列表视图的数据太多。改为使用 cardviews 和 recyclerviews,延迟消失了。
您应该从 FragmentActivity
扩展您的容器 activitypublic class MainActivity extends FragmentActivity
{
}
this is very fast switch between fragment.
最好在 xml 布局中使用标签 并显示,单击选项卡或底部选项卡时隐藏
//代码示例:
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.show(fm.findFragmentById(fragment))
.hide(fm.findFragmentById(activePage))
.commit();