我创建了一个简单的ViewPager TabLayout,在3个标签中显示3个片段。现在,如果用户打开另一个活动并进行一些更改,并返回到包含ViewPager的活动,则第三个片段应替换为新片段。我不希望用户再看到旧的第3个片段。
当用户从另一个活动回到ViewPager活动时,会调用onResume()
方法,我们可以知道是否要替换第三个碎片。
这是ViewPager的适配器:
public class TabsPagerAdapterMain extends FragmentPagerAdapter {
int mNumOfTabs;
public TabsPagerAdapterMain(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
YourStoryFragment yourStoryTab = new YourStoryFragment();
return yourStoryTab;
case 1:
BrowseStoriesFragment browseStoriesTab = new BrowseStoriesFragment();
return browseStoriesTab;
case 2:
ParseObject collegeObject;
ParseUser user = ParseUser.getCurrentUser();
collegeObject = user.getParseObject("college");
if (collegeObject == null) {
CollegeSelectFragment collegeSelectFragment = new CollegeSelectFragment();
return collegeSelectFragment;
} else {
YourCollegeFragment yourCollegeTab = new YourCollegeFragment();
return yourCollegeTab;
}
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
包含ViewPager的活动:
public class XXXXXXMainTabbed extends AppCompatActivity {
ViewPager viewPager;
public Student xxxxxMainStudent;
private boolean brandNewAccount = false;
private CharSequence mTitle;
private long firstTime = 0;
public int yourStoryFragmentMenuId = 0;
Fragment globalFragmentThatIsOpen;
static TextView actionTitle;
Spinner browse_spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xxxxxx_main_tabbed);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setIcon(R.drawable.actionbar_space_between_icon_and_title);
actionTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
actionTitle.setTypeface(TypeFaceController.titleFace(getApplicationContext()));
browse_spinner = (Spinner) toolbar.findViewById(R.id.browse_spinner);
browse_spinner.setVisibility(View.GONE);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText(" Story").setIcon(R.drawable.browse_tab));
tabLayout.addTab(tabLayout.newTab().setText(" Browse").setIcon(R.drawable.browse_tab));
tabLayout.addTab(tabLayout.newTab().setText(" College").setIcon(R.drawable.colleges_tab));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
setTitle("Your Story");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent inte = new Intent(getApplicationContext(), WriteStory.class);
startActivity(inte);
}
});
viewPager = (ViewPager) findViewById(R.id.pager);
final TabsPagerAdapterMain adapter = new TabsPagerAdapterMain
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setOffscreenPageLimit (4);
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
setTitle("Your Story");
browse_spinner.setVisibility(View.GONE);
break;
case 1:
setTitle("Browse");
browse_spinner.setVisibility(View.VISIBLE);
break;
case 2:
setTitle("Your College");
browse_spinner.setVisibility(View.GONE);
break;
default:
setTitle("XXXXXX");
browse_spinner.setVisibility(View.GONE);
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
// Grab the bundle information
Intent intentFromPrevious = getIntent();
Bundle extras = intentFromPrevious.getExtras();
saveInPreferenceBoolean("LoggedIn",true);
if (extras != null) {
brandNewAccount = extras.getBoolean("brandNewAccount");
xxxxxxMainStudent = (Student) intentFromPrevious.getParcelableExtra("studentObject");
} else {
}
if (brandNewAccount == true) {
Intent inte = new Intent(getApplicationContext(), WriteStory.class);
brandNewAccount = false;
startActivity(inte);
}
saveInPreference("firstName", "");
saveInPreference("lastName", "");
saveInPreference("countryFrom", "");
saveInPreference("collegeExists", "");
saveInPreference("username", "");
saveInPreference("email", "");
saveInPreference("password", "");
saveInPreference("dateOfBirth", "");
saveInPreference("collegeId", "");
saveInPreference("courseId", "");
saveInPreference("facebookAccount", "");
//updating app version in the user table
updateUserAppVersion();
}
@Override
protected void onResume() {
super.onResume();
Log.e("xxxxxxMainTabbed", "The onResume() event");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.home_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
Log.e("postCounter", "" + xxxxxxMainStudent.getPostCount());
if (isItYourStory() == true) {
YourStoryFragment obj = new YourStoryFragment();
if (obj.canEditItem == false) {
obj.menuTitle = "EDIT";
} else {
if (xxxxxxMainStudent.getPostCount() == 0) {
obj.menuTitle = "EDIT";
}
else {
obj.menuTitle = "DONE";
}
}
}
return super.onPrepareOptionsMenu(menu);
}
public Student getStudentDataFromMain() {
return this.xxxxxxMainStudent;
}
public void displayView(int pos) {
}
private void updateUserAppVersion(){
String appVersionName = getAppVersionName();
ParseUser user = ParseUser.getCurrentUser();
user.put("appVersion", appVersionName);
user.saveInBackground(new SaveCallback() {
public void done(com.parse.ParseException e) {
if (e == null) {
// Save was successful!
Log.e("appVersion", "saved successfully");
} else {
// Save failed. Inspect e for details.
Log.e("appVersion", "saved successfully");
}
}
});
}
public String getAppVersionName() {
PackageInfo pInfo = null;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String version = pInfo.versionName;
return version;
}
public boolean isItYourStory() {
if (viewPager.getCurrentItem() == 0) {
return true;
}
return false;
}
// method to save variable in preference
public void saveInPreference(String name, String content) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(name, content);
editor.commit();
}
// getting content from preferences
public String getFromPreference(String variable_name) {
String preference_return;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preference_return = preferences.getString(variable_name, "");
return preference_return;
}
// method to save variable in preference
public void saveInPreferenceBoolean(String name, boolean content){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(name, content);
editor.commit();
}
// getting content from preferences
public boolean getFromPreferenceBoolean(String variable_name){
boolean preference_return;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preference_return = preferences.getBoolean(variable_name, false);
return preference_return;
}
public void setTitle(String title) {
actionTitle.setText(title);
}
}
在调用活动onResume()
时,如何在第3个标签页设置 YourCollegeFragment ?
答案 0 :(得分:2)
您可能希望更改片段中膨胀的布局,而不是替换片段本身。在片段内部,根据您的条件对布局进行膨胀,并相应地增加视图。这是我试过的示例代码。
public class DemoFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview;
if (your condition is true) {
// layout_one will be the layout for your CollegeSelectFragment
rootview = inflater.inflate(R.layout.layout_one, container, false);
} else {
// layout_one will be the layout for your YourCollegeFragment
rootview = inflater.inflate(R.layout.layout_two, container, false);
}
setupViews(rootview);
return rootview;
}
private void setupViews(View v) {
if (your condition is true -- same as above check) {
// find and set view that are in the layout_one.xml
TextView bigText = (TextView) v.findViewById(R.id.bigText);
bigText.setText("set from code");
} else {
// find and set view that are in the layout_two.xml
TextView bigText2 = (TextView) v.findViewById(R.id.bigText2);
bigText2.setText("big text 2 set from code");
}
}
}
答案 1 :(得分:1)
您可以创建一个变量来表示各种情况,并根据该标志,您可以创建所需片段的实例。
在您的适配器中创建一个标记
int conditionFlag;
现在创建一个公共方法来更新此标志。
public void updateFlag(int flag){
this.flag = flag;
}
在你的活动中,在类级别和onResume()方法上创建适配器对象,根据你的条件更新标志,如
adapter.updateFlag(flag);
adapter.notifyDataSetchanged();
如果notifyDataSetChanged()不起作用,您可以按照这些解决方案
答案 2 :(得分:0)
我在阅读@ kaaloraat的建议后解决了这个问题。我创建了一个片段作为根片段工作,这个片段负责根据条件显示特定片段。
以下是Root Fragment类:
public class RootCollegeFragment extends Fragment {
private static final String TAG = "RootFragment";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
/* Inflate the layout for this fragment */
View view = inflater.inflate(R.layout.root_fragment_college, container, false);
ParseObject collegeObject;
ParseUser user = ParseUser.getCurrentUser();
collegeObject = user.getParseObject("college");
if (collegeObject == null) {
CollegeSelectFragment collegeSelectFragment= new CollegeSelectFragment();
this.getFragmentManager().beginTransaction()
.replace(R.id.root_frame, collegeSelectFragment,null)
.addToBackStack(null)
.commit();
} else {
YourCollegeFragment yourCollegeFragment= new YourCollegeFragment();
this.getFragmentManager().beginTransaction()
.replace(R.id.root_frame, yourCollegeFragment,null)
.addToBackStack(null)
.commit();
}
return view;
}
@Override
public void onResume() {
Log.e("RootCollegeFragment", "onResume of RootCollegeFragment");
ParseObject collegeObject;
ParseUser user = ParseUser.getCurrentUser();
collegeObject = user.getParseObject("college");
if (collegeObject == null) {
CollegeSelectFragment collegeSelectFragment= new CollegeSelectFragment();
this.getFragmentManager().beginTransaction()
.replace(R.id.root_frame, collegeSelectFragment,null)
.addToBackStack(null)
.commit();
} else {
YourCollegeFragment yourCollegeFragment= new YourCollegeFragment();
this.getFragmentManager().beginTransaction()
.replace(R.id.root_frame, yourCollegeFragment,null)
.addToBackStack(null)
.commit();
}
super.onResume();
}
}
我让适配器只调用根片段,而根片段又决定片段打开。
适配器代码:
public class TabsPagerAdapterMain extends FragmentPagerAdapter {
int mNumOfTabs;
public TabsPagerAdapterMain(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
YourStoryFragment yourStoryTab = new YourStoryFragment();
return yourStoryTab;
case 1:
BrowseStoriesFragment browseStoriesTab = new BrowseStoriesFragment();
return browseStoriesTab;
case 2:
RootCollegeFragment rootCollegeFragment = new RootCollegeFragment();
return rootCollegeFragment;
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
多数民众赞成!简单干净!
P.S。:This也很有用