Set the current page of both the ViewPager and indicator.
44 | * 45 | *This must be used if you need to set the page before 46 | * the views are drawn on screen (e.g., default start page).
47 | * 48 | * @param item 49 | */ 50 | void setCurrentItem(int item); 51 | 52 | /** 53 | * Set a page change listener which will receive forwarded events. 54 | * 55 | * @param listener 56 | */ 57 | void setOnPageChangeListener(ViewPager.OnPageChangeListener listener); 58 | 59 | /** 60 | * Notify the indicator that the fragment list has changed. 61 | */ 62 | void notifyDataSetChanged(); 63 | } 64 | -------------------------------------------------------------------------------- /app/src/main/java/me/li2/update_replace_fragment_in_viewpager/ContainerFragment.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Created by WeiYi Li 3 | * 2015-08-07 4 | * weiyi.just2@gmail.com 5 | * li2.me 6 | */ 7 | package me.li2.update_replace_fragment_in_viewpager; 8 | 9 | import java.text.SimpleDateFormat; 10 | import java.util.Date; 11 | import java.util.Locale; 12 | 13 | import android.app.Activity; 14 | import android.os.Bundle; 15 | import android.support.v4.app.Fragment; 16 | import android.support.v4.app.FragmentManager; 17 | import android.support.v4.app.FragmentTransaction; 18 | import android.util.Log; 19 | import android.view.LayoutInflater; 20 | import android.view.View; 21 | import android.view.ViewGroup; 22 | import android.widget.FrameLayout; 23 | 24 | public class ContainerFragment extends Fragment { 25 | 26 | private static final String TAG = "Fragment4"; 27 | private static final String EXTRA_FRAGMENT_TO_SHOW = "me.li2.update_replace_fragment_in_viewpager.extra_fragment_to_show"; 28 | private static final String EXTRA_DATE = "me.li2.update_replace_fragment_in_viewpager.extra_date"; 29 | private static final String EXTRA_CONTENT = "me.li2.update_replace_fragment_in_viewpager.extra_content"; 30 | 31 | private int mFragmentToShow; 32 | private Date mDate; 33 | private String mContent; 34 | private int mFragmentContainerId; 35 | 36 | public static ContainerFragment newInstance(int fragmentToShow, Date date, String content) { 37 | Log.d(TAG, String.format("newInstance(fragmentToShow=%d, Date=%s, Content=%s", fragmentToShow, formatDate(date), content)); 38 | Bundle args = new Bundle(); 39 | args.putInt(EXTRA_FRAGMENT_TO_SHOW, fragmentToShow); 40 | args.putLong(EXTRA_DATE, date.getTime()); 41 | args.putString(EXTRA_CONTENT, content); 42 | 43 | ContainerFragment fragment = new ContainerFragment(); 44 | fragment.setArguments(args); 45 | return fragment; 46 | } 47 | 48 | @Override 49 | public void onCreate(Bundle savedInstanceState) { 50 | Log.d(TAG, "onCreate()"); 51 | super.onCreate(savedInstanceState); 52 | mFragmentToShow = getArguments().getInt(EXTRA_FRAGMENT_TO_SHOW); 53 | mDate = new Date(getArguments().getLong(EXTRA_DATE)); 54 | mContent = getArguments().getString(EXTRA_CONTENT); 55 | } 56 | 57 | @Override 58 | public void onDestroy() { 59 | super.onDestroy(); 60 | Log.d(TAG, "onDestroy()"); 61 | } 62 | 63 | @Override 64 | public void onAttach(Activity activity) { 65 | super.onAttach(activity); 66 | Log.d(TAG, "onAttach()"); 67 | } 68 | 69 | @Override 70 | public void onDetach() { 71 | super.onDetach(); 72 | Log.d(TAG, "onDetach()"); 73 | } 74 | 75 | @Override 76 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 77 | Log.d(TAG, "onCreateView()"); 78 | View view = inflater.inflate(R.layout.fragment_container, container, false); 79 | // To avoid overlapping, every fragment in the container in ViewPager should has an unique ID. http://stackoverflow.com/a/26079878/2722270 80 | FrameLayout fragmentContainer = (FrameLayout) view.findViewById(R.id.fragmentContainer); 81 | int fragmentContainerId = R.id.fragmentContainer0; 82 | mFragmentContainerId = fragmentContainerId; 83 | fragmentContainer.setId(fragmentContainerId); 84 | 85 | FragmentManager fm = getFragmentManager(); 86 | FragmentTransaction ft = fm.beginTransaction(); 87 | Fragment oldFragment = fm.findFragmentById(fragmentContainerId); 88 | Fragment newFragment; 89 | if (oldFragment != null) { 90 | ft.remove(oldFragment); 91 | } 92 | if (mFragmentToShow == 0) { 93 | newFragment = Page0Fragment.newInstance(mDate); 94 | } else { 95 | newFragment = Page1Fragment.newInstance(mContent); 96 | } 97 | ft.add(fragmentContainerId, newFragment); 98 | ft.commit(); 99 | Log.d(TAG, "add fragment " + newFragment.getClass().getSimpleName()); 100 | 101 | return view; 102 | } 103 | 104 | @Override 105 | public void onDestroyView() { 106 | super.onDestroyView(); 107 | Log.d(TAG, "onDestroyView()"); 108 | } 109 | 110 | // To replace fragment in ViewPager, we implement a fragment with a framelayout, we call it as ContainerFragment, 111 | // We pass a variable "fragmentToShow" to nofity the ContainerFragment, 112 | // depending on "fragmentToShow", the ContainerFragment decide whether replace old fragment with new fragment, or 113 | // update old fragment. 114 | public void updateData(int fragmentToShow, Date date, String content) { 115 | Log.d(TAG, String.format("updateData(fragmentToShow=%d, Date=%s, Content=%s", fragmentToShow, formatDate(date), content)); 116 | mDate = date; 117 | mContent = content; 118 | 119 | FragmentManager fm = getFragmentManager(); 120 | FragmentTransaction ft = fm.beginTransaction(); 121 | if (mFragmentToShow != fragmentToShow) { 122 | Log.d(TAG, "replace fragment"); 123 | mFragmentToShow = fragmentToShow; 124 | if (mFragmentToShow == 0) { 125 | ft.replace(mFragmentContainerId, Page0Fragment.newInstance(mDate)); 126 | } else { 127 | ft.replace(mFragmentContainerId, Page1Fragment.newInstance(mContent)); 128 | } 129 | ft.commit(); 130 | } else { 131 | Fragment oldFragment = fm.findFragmentById(mFragmentContainerId); 132 | if (oldFragment != null) { 133 | Log.d(TAG, "update fragment: " + oldFragment.getClass().getSimpleName()); 134 | if (oldFragment instanceof Page0Fragment) { 135 | ((Page0Fragment) oldFragment).updateDate(mDate); 136 | } else if (oldFragment instanceof Page1Fragment) { 137 | ((Page1Fragment) oldFragment).updateContent(mContent); 138 | } 139 | } 140 | } 141 | } 142 | 143 | private static String formatDate(Date date) { 144 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US); 145 | return sdf.format(date); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /app/src/main/java/me/li2/update_replace_fragment_in_viewpager/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Created by WeiYi Li 3 | * 2015-08-07 4 | * weiyi.just2@gmail.com 5 | * li2.me 6 | */ 7 | package me.li2.update_replace_fragment_in_viewpager; 8 | 9 | import java.io.BufferedReader; 10 | import java.io.IOException; 11 | import java.io.InputStreamReader; 12 | import java.util.Date; 13 | 14 | import android.os.Bundle; 15 | import android.support.v4.app.Fragment; 16 | import android.support.v4.app.FragmentActivity; 17 | import android.support.v4.app.FragmentPagerAdapter; 18 | import android.support.v4.view.ViewPager; 19 | import android.support.v4.view.ViewPager.OnPageChangeListener; 20 | import android.text.Editable; 21 | import android.text.TextWatcher; 22 | import android.util.Log; 23 | import android.view.View; 24 | import android.view.View.OnClickListener; 25 | import android.widget.Button; 26 | import android.widget.CheckBox; 27 | import android.widget.CompoundButton; 28 | import android.widget.CompoundButton.OnCheckedChangeListener; 29 | import android.widget.EditText; 30 | import android.widget.Switch; 31 | import android.widget.TextView; 32 | 33 | import com.viewpagerindicator.CirclePageIndicator; 34 | 35 | public class MainActivity extends FragmentActivity implements OnClickListener { 36 | 37 | private static final String TAG = "Adapter"; 38 | private static final int PAGE_COUNT = 5; 39 | private static final int LOG_COLLECT_INTERVAL = 500; // ms 40 | private ViewPager mViewPager; 41 | private Button mDayPlusButton; 42 | private Button mDayMinusButton; 43 | private EditText mEditorText; 44 | private CheckBox mCheckBox; 45 | private Switch mSwitch; 46 | private TextView mLogView; 47 | 48 | private Date mDate; 49 | private String mContent; 50 | private boolean mChecked; 51 | private int mFragmentToShow; 52 | private boolean mShouldExitLogThread; 53 | 54 | @Override 55 | protected void onCreate(Bundle savedInstanceState) { 56 | super.onCreate(savedInstanceState); 57 | setContentView(R.layout.activity_main); 58 | 59 | mViewPager = (ViewPager) findViewById(R.id.main_viewpPager); 60 | mViewPager.setAdapter(mViewPagerAdapter); 61 | mViewPager.setOnPageChangeListener(mPageChangeListener); 62 | 63 | CirclePageIndicator indicator = (CirclePageIndicator) findViewById(R.id.main_viewPager_indicator); 64 | indicator.setViewPager(mViewPager); 65 | indicator.setOnPageChangeListener(mPageChangeListener); 66 | 67 | mDayPlusButton = (Button) findViewById(R.id.main_dayPlusButton); 68 | mDayMinusButton = (Button) findViewById(R.id.main_dayMinusButton); 69 | mDayPlusButton.setOnClickListener(this); 70 | mDayMinusButton.setOnClickListener(this); 71 | mEditorText = (EditText) findViewById(R.id.main_editContent); 72 | mEditorText.addTextChangedListener(mTextWatcher); 73 | mCheckBox = (CheckBox) findViewById(R.id.main_checkbox); 74 | mCheckBox.setOnCheckedChangeListener(mPage2CheckedChangeListener); 75 | mSwitch = (Switch) findViewById(R.id.main_switch); 76 | mSwitch.setOnCheckedChangeListener(mPage3CheckedChangeListener); 77 | mLogView = (TextView) findViewById(R.id.main_logView); 78 | 79 | mDate = new Date(); 80 | mContent = "Hello World, I'm li2."; 81 | mChecked = true; 82 | mFragmentToShow = 0; 83 | } 84 | 85 | @Override 86 | protected void onResume() { 87 | super.onResume(); 88 | mShouldExitLogThread = false; 89 | startCollectLogcatThread(); 90 | } 91 | 92 | @Override 93 | protected void onPause() { 94 | super.onPause(); 95 | mShouldExitLogThread = true; 96 | } 97 | 98 | private FragmentPagerAdapter mViewPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) { 99 | @Override 100 | public int getCount() { 101 | return PAGE_COUNT; 102 | } 103 | 104 | // Return the Fragment associated with a specified position. 105 | @Override 106 | public Fragment getItem(int position) { 107 | Log.d(TAG, "getItem(" + position + ")"); 108 | if (position == 0) { 109 | return Page0Fragment.newInstance(mDate); 110 | } else if (position == 1) { 111 | return Page1Fragment.newInstance(mContent); 112 | } else if (position == 2) { 113 | return Page2Fragment.newInstance(mChecked); 114 | } else if (position == 3) { 115 | // return Page3Fragment.newInstance(); 116 | return getFragment(3); 117 | } else if (position == 4) { 118 | return ContainerFragment.newInstance(0, mDate, mContent); 119 | } 120 | 121 | return null; 122 | } 123 | 124 | private Fragment getFragment(int pageValue) { 125 | SimpleBackPage page = SimpleBackPage.getPageValue(pageValue); 126 | Fragment fragment; 127 | try { 128 | fragment = (Fragment) page.getCls().newInstance(); 129 | return fragment; 130 | } catch (InstantiationException e) { 131 | e.printStackTrace(); 132 | } catch (IllegalAccessException e) { 133 | e.printStackTrace(); 134 | } 135 | return null; 136 | } 137 | 138 | // Remove a page for the given position. The adapter is responsible for removing the view from its container. 139 | @Override 140 | public void destroyItem(android.view.ViewGroup container, int position, Object object) { 141 | super.destroyItem(container, position, object); 142 | Log.d(TAG, "destroyItem(" + position + ")"); 143 | }; 144 | 145 | @Override 146 | // To update fragment in ViewPager, we should override getItemPosition() method, 147 | // in this method, we call the fragment's public updating method. 148 | public int getItemPosition(Object object) { 149 | Log.d(TAG, "getItemPosition(" + object.getClass().getSimpleName() + ")"); 150 | if (object instanceof Page0Fragment) { 151 | ((Page0Fragment) object).updateDate(mDate); 152 | } else if (object instanceof Page1Fragment) { 153 | ((Page1Fragment) object).updateContent(mContent); 154 | } else if (object instanceof Page2Fragment) { 155 | ((Page2Fragment) object).updateCheckedStatus(mChecked); 156 | } else if (object instanceof ContainerFragment) { 157 | ((ContainerFragment) object).updateData(mFragmentToShow, mDate, mContent); 158 | } 159 | return super.getItemPosition(object); 160 | }; 161 | }; 162 | 163 | 164 | private ViewPager.OnPageChangeListener mPageChangeListener = new OnPageChangeListener() { 165 | @Override 166 | public void onPageSelected(int position) { 167 | Log.d(TAG, "\nonPageSelected(" + position + ")"); 168 | // notifyViewPagerDataSetChanged(); 169 | } 170 | 171 | @Override 172 | public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {} 173 | 174 | @Override 175 | public void onPageScrollStateChanged(int state) {} 176 | }; 177 | 178 | 179 | /** 180 | * To update fragment in ViewPager, we should call PagerAdapter.notifyDataSetChanged() when data changed. 181 | * we should also override FragmentPagerAdapter.getItemPosition(), and 182 | * implement a public method for updating fragment. 183 | * Refer to [Update Fragment from ViewPager](http://stackoverflow.com/a/18088509/2722270) 184 | */ 185 | private void notifyViewPagerDataSetChanged() { 186 | Log.d(TAG, "\nnotifyDataSetChanged()"); 187 | mViewPagerAdapter.notifyDataSetChanged(); 188 | } 189 | 190 | 191 | @Override 192 | // page 0 data changed 193 | public void onClick(View v) { 194 | int id = v.getId(); 195 | if (id == R.id.main_dayPlusButton) { 196 | mDate = new Date((mDate.getTime() + 24*3600*1000)); 197 | notifyViewPagerDataSetChanged(); 198 | } else if (id == R.id.main_dayMinusButton) { 199 | mDate = new Date((mDate.getTime() - 24*3600*1000)); 200 | notifyViewPagerDataSetChanged(); 201 | } 202 | } 203 | 204 | // page 1 data changed 205 | private TextWatcher mTextWatcher = new TextWatcher() { 206 | @Override 207 | public void onTextChanged(CharSequence s, int start, int before, int count) {} 208 | 209 | @Override 210 | public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 211 | 212 | @Override 213 | public void afterTextChanged(Editable s) { 214 | mContent = s.toString(); 215 | notifyViewPagerDataSetChanged(); 216 | } 217 | }; 218 | 219 | // page 2 data changed 220 | private OnCheckedChangeListener mPage2CheckedChangeListener = new OnCheckedChangeListener() { 221 | @Override 222 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 223 | mChecked = isChecked; 224 | notifyViewPagerDataSetChanged(); 225 | } 226 | }; 227 | 228 | // page 3 data changed 229 | private OnCheckedChangeListener mPage3CheckedChangeListener = new OnCheckedChangeListener() { 230 | @Override 231 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 232 | mFragmentToShow = (isChecked) ? 1 : 0; 233 | notifyViewPagerDataSetChanged(); 234 | } 235 | }; 236 | 237 | 238 | // Collect all logcat of this app then display in scroll textview, 239 | // to show the detail of PagerAdapter method and Fragment life cycle 240 | // when user scroll or change page. 241 | private void startCollectLogcatThread() { 242 | clearLogcat(); 243 | new Thread(new Runnable() { 244 | @Override 245 | public void run() { 246 | while(!mShouldExitLogThread) { 247 | collectLogcat(); 248 | try { 249 | Thread.sleep(LOG_COLLECT_INTERVAL); 250 | } catch (InterruptedException e) { 251 | e.printStackTrace(); 252 | } 253 | } 254 | } 255 | }).start();; 256 | } 257 | 258 | private void clearLogcat() { 259 | String cmd = "logcat -c"; 260 | try { 261 | Runtime.getRuntime().exec(cmd); 262 | } catch (IOException e) { 263 | e.printStackTrace(); 264 | } 265 | } 266 | 267 | // Colllect logcat and display in TextView 268 | // http://tanxiaoya105.blog.163.com/blog/static/2103280192012101392053176 269 | // [logcat with mutiple tags at one time](http://stackoverflow.com/a/16995884/2722270) 270 | private void collectLogcat() { 271 | try { 272 | String cmd = "logcat -d Adapter:D Fragment0:D Fragment1:D Fragment2:D Fragment3:D Fragment4:D *:S"; 273 | Process process = Runtime.getRuntime().exec(cmd); 274 | BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); 275 | StringBuilder log = new StringBuilder(); 276 | String line = ""; 277 | while ((line = bufferedReader.readLine()) != null) { 278 | log.append(line + "\n"); 279 | } 280 | updateLogView(log.toString()); 281 | } catch (IOException e) { 282 | e.printStackTrace(); 283 | } 284 | } 285 | 286 | private void updateLogView(final String log) { 287 | runOnUiThread(new Runnable() { 288 | @Override 289 | public void run() { 290 | mLogView.setText(log); 291 | } 292 | }); 293 | } 294 | } 295 | -------------------------------------------------------------------------------- /app/src/main/java/me/li2/update_replace_fragment_in_viewpager/Page0Fragment.java: -------------------------------------------------------------------------------- 1 | package me.li2.update_replace_fragment_in_viewpager; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | import java.util.Locale; 6 | 7 | import android.app.Activity; 8 | import android.os.Bundle; 9 | import android.support.v4.app.Fragment; 10 | import android.util.Log; 11 | import android.view.LayoutInflater; 12 | import android.view.View; 13 | import android.view.ViewGroup; 14 | import android.widget.TextView; 15 | 16 | public class Page0Fragment extends Fragment { 17 | 18 | private static final String TAG = "Fragment0"; 19 | private static final String EXTRA_DATE = "me.li2.update_replace_fragment_in_viewpager.extra_date"; 20 | private Date mDate; 21 | private TextView mTextView; 22 | 23 | public static Page0Fragment newInstance(Date date) { 24 | Log.d(TAG, "newInstance(" + formatDate(date) + ")"); 25 | Bundle args = new Bundle(); 26 | args.putLong(EXTRA_DATE, date.getTime()); 27 | 28 | Page0Fragment fragment = new Page0Fragment(); 29 | fragment.setArguments(args); 30 | return fragment; 31 | } 32 | 33 | @Override 34 | public void onCreate(Bundle savedInstanceState) { 35 | Log.d(TAG, "onCreate()"); 36 | super.onCreate(savedInstanceState); 37 | mDate = new Date(getArguments().getLong(EXTRA_DATE)); 38 | } 39 | 40 | @Override 41 | public void onDestroy() { 42 | super.onDestroy(); 43 | Log.d(TAG, "onDestroy()"); 44 | } 45 | 46 | @Override 47 | public void onAttach(Activity activity) { 48 | super.onAttach(activity); 49 | Log.d(TAG, "onAttach()"); 50 | } 51 | 52 | @Override 53 | public void onDetach() { 54 | super.onDetach(); 55 | Log.d(TAG, "onDetach()"); 56 | } 57 | 58 | @Override 59 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 60 | Log.d(TAG, "onCreateView()"); 61 | View view = inflater.inflate(R.layout.fragment_page0, container, false); 62 | mTextView = (TextView) view.findViewById(R.id.page0_date); 63 | mTextView.setText(mDate.toString()); 64 | return view; 65 | } 66 | 67 | @Override 68 | public void onDestroyView() { 69 | super.onDestroyView(); 70 | Log.d(TAG, "onDestroyView()"); 71 | } 72 | 73 | // To update fragment in ViewPager, we should implement a public method for the fragment, 74 | // and do updating stuff in this method. 75 | public void updateDate(Date date) { 76 | Log.d(TAG, "updateDate(" + formatDate(date) + ")"); 77 | mDate = date; 78 | mTextView.setText(mDate.toString()); 79 | } 80 | 81 | private static String formatDate(Date date) { 82 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US); 83 | return sdf.format(date); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /app/src/main/java/me/li2/update_replace_fragment_in_viewpager/Page1Fragment.java: -------------------------------------------------------------------------------- 1 | package me.li2.update_replace_fragment_in_viewpager; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.support.v4.app.Fragment; 6 | import android.util.Log; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import android.widget.TextView; 11 | 12 | public class Page1Fragment extends Fragment { 13 | 14 | private static final String TAG = "Fragment1"; 15 | private static final String EXTRA_CONTENT = "me.li2.update_replace_fragment_in_viewpager.extra_content"; 16 | private String mContent; 17 | private TextView mTextView; 18 | 19 | public static Page1Fragment newInstance(String content) { 20 | Log.d(TAG, "newInstance(" + content + ")"); 21 | Bundle args = new Bundle(); 22 | args.putString(EXTRA_CONTENT, content); 23 | 24 | Page1Fragment fragment = new Page1Fragment(); 25 | fragment.setArguments(args); 26 | return fragment; 27 | } 28 | 29 | @Override 30 | public void onCreate(Bundle savedInstanceState) { 31 | Log.d(TAG, "onCreate()"); 32 | super.onCreate(savedInstanceState); 33 | mContent = getArguments().getString(EXTRA_CONTENT); 34 | } 35 | 36 | @Override 37 | public void onDestroy() { 38 | super.onDestroy(); 39 | Log.d(TAG, "onDestroy()"); 40 | } 41 | 42 | @Override 43 | public void onAttach(Activity activity) { 44 | super.onAttach(activity); 45 | Log.d(TAG, "onAttach()"); 46 | } 47 | 48 | @Override 49 | public void onDetach() { 50 | super.onDetach(); 51 | Log.d(TAG, "onDetach()"); 52 | } 53 | 54 | @Override 55 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 56 | Log.d(TAG, "onCreateView()"); 57 | View view = inflater.inflate(R.layout.fragment_page1, container, false); 58 | mTextView = (TextView) view.findViewById(R.id.page1_content); 59 | mTextView.setText(mContent); 60 | return view; 61 | } 62 | 63 | @Override 64 | public void onDestroyView() { 65 | super.onDestroyView(); 66 | Log.d(TAG, "onDestroyView()"); 67 | } 68 | 69 | // To update fragment in ViewPager, we should implement a public method for the fragment, 70 | // and do updating stuff in this method. 71 | public void updateContent(String content) { 72 | Log.d(TAG, "updateContent(" + content + ")"); 73 | mContent = content; 74 | mTextView.setText(mContent); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /app/src/main/java/me/li2/update_replace_fragment_in_viewpager/Page2Fragment.java: -------------------------------------------------------------------------------- 1 | package me.li2.update_replace_fragment_in_viewpager; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.support.v4.app.Fragment; 6 | import android.util.Log; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | import android.widget.CheckBox; 11 | 12 | public class Page2Fragment extends Fragment { 13 | 14 | private static final String TAG = "Fragment2"; 15 | private static final String EXTRA_CHECKED = "me.li2.update_replace_fragment_in_viewpager.extra_checked"; 16 | private boolean mChecked; 17 | private CheckBox mCheckBox; 18 | 19 | public static Page2Fragment newInstance(boolean checked) { 20 | Log.d(TAG, "newInstance(" + checked + ")"); 21 | Bundle args = new Bundle(); 22 | args.putBoolean(EXTRA_CHECKED, checked); 23 | 24 | Page2Fragment fragment = new Page2Fragment(); 25 | fragment.setArguments(args); 26 | return fragment; 27 | } 28 | 29 | @Override 30 | public void onCreate(Bundle savedInstanceState) { 31 | Log.d(TAG, "onCreate()"); 32 | super.onCreate(savedInstanceState); 33 | mChecked = getArguments().getBoolean(EXTRA_CHECKED); 34 | } 35 | 36 | @Override 37 | public void onDestroy() { 38 | super.onDestroy(); 39 | Log.d(TAG, "onDestroy()"); 40 | } 41 | 42 | @Override 43 | public void onAttach(Activity activity) { 44 | super.onAttach(activity); 45 | Log.d(TAG, "onAttach()"); 46 | } 47 | 48 | @Override 49 | public void onDetach() { 50 | super.onDetach(); 51 | Log.d(TAG, "onDetach()"); 52 | } 53 | 54 | @Override 55 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 56 | Log.d(TAG, "onCreateView()"); 57 | View view = inflater.inflate(R.layout.fragment_page2, container, false); 58 | mCheckBox = (CheckBox) view.findViewById(R.id.page2_selected); 59 | mCheckBox.setChecked(mChecked); 60 | return view; 61 | } 62 | 63 | @Override 64 | public void onDestroyView() { 65 | super.onDestroyView(); 66 | Log.d(TAG, "onDestroyView()"); 67 | } 68 | 69 | // To update fragment in ViewPager, we should implement a public method for the fragment, 70 | // and do updating stuff in this method. 71 | public void updateCheckedStatus(boolean checked) { 72 | Log.d(TAG, "updateCheckedStatus(" + checked + ")"); 73 | mChecked = checked; 74 | mCheckBox.setChecked(mChecked); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /app/src/main/java/me/li2/update_replace_fragment_in_viewpager/Page3Fragment.java: -------------------------------------------------------------------------------- 1 | package me.li2.update_replace_fragment_in_viewpager; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.support.v4.app.Fragment; 6 | import android.util.Log; 7 | import android.view.LayoutInflater; 8 | import android.view.View; 9 | import android.view.ViewGroup; 10 | 11 | public class Page3Fragment extends Fragment { 12 | 13 | private static final String TAG = "Fragment3"; 14 | 15 | public Page3Fragment() { 16 | super(); 17 | } 18 | 19 | public static Page3Fragment newInstance() { 20 | Log.d(TAG, "newInstance()"); 21 | return new Page3Fragment(); 22 | } 23 | 24 | @Override 25 | public void onCreate(Bundle savedInstanceState) { 26 | Log.d(TAG, "onCreate()"); 27 | super.onCreate(savedInstanceState); 28 | } 29 | 30 | @Override 31 | public void onDestroy() { 32 | super.onDestroy(); 33 | Log.d(TAG, "onDestroy()"); 34 | } 35 | 36 | @Override 37 | public void onAttach(Activity activity) { 38 | super.onAttach(activity); 39 | Log.d(TAG, "onAttach()"); 40 | } 41 | 42 | @Override 43 | public void onDetach() { 44 | super.onDetach(); 45 | Log.d(TAG, "onDetach()"); 46 | } 47 | 48 | @Override 49 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 50 | Log.d(TAG, "onCreateView()"); 51 | return inflater.inflate(R.layout.fragment_page3, container, false); 52 | } 53 | 54 | @Override 55 | public void onDestroyView() { 56 | super.onDestroyView(); 57 | Log.d(TAG, "onDestroyView()"); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /app/src/main/java/me/li2/update_replace_fragment_in_viewpager/SimpleBackPage.java: -------------------------------------------------------------------------------- 1 | package me.li2.update_replace_fragment_in_viewpager; 2 | 3 | 4 | public enum SimpleBackPage { 5 | 6 | PAGE3(3, R.string.page1_title, Page3Fragment.class); 7 | 8 | private int values; 9 | private int title; 10 | private Class> cls; 11 | 12 | private SimpleBackPage(int values, int title, Class> cls) { 13 | this.values = values; 14 | this.title = title; 15 | this.cls = cls; 16 | } 17 | 18 | public int getValues() { 19 | return values; 20 | } 21 | 22 | public void setValues(int values) { 23 | this.values = values; 24 | } 25 | 26 | public Class> getCls() { 27 | return cls; 28 | } 29 | 30 | public void setCls(Class> cls) { 31 | this.cls = cls; 32 | } 33 | 34 | public int getTitle() { 35 | return title; 36 | } 37 | 38 | public void setTitle(int title) { 39 | this.title = title; 40 | } 41 | 42 | public static SimpleBackPage getPageValue(int val) { 43 | for (SimpleBackPage p : values()) { 44 | if (p.getValues() == val) { 45 | return p; 46 | } 47 | } 48 | return null; 49 | } 50 | } 51 | 52 | /* 53 | 54 | 求问Fragment fragment = (Fragment) page.getCls().newInstance(); 55 | http://segmentfault.com/q/1010000003967198/a-1020000003967414 56 | 57 | ## 根据问题追加的代码Update 58 | 59 | SimpleBackPage是enum类型,意图是**通过数字获取对应的Fragment类**: 60 | 61 | ```java 62 | SimpleBackPage page = SimpleBackPage.getPageValue(pageValue); 63 | // 如果pageValue=1,getCls返回的就是FeedBackFragment.class 64 | // 如果pageVaule=2,getCls返回的就是AboutFrament.class 65 | page.getCls(); 66 | 67 | public enum SimpleBackPage { 68 | FEEDBACK(1, R.string.setting_about, FeedBackFragment.class), 69 | ABOUT(2, R.string.setting_about, AboutFrament.class); 70 | 71 | private SimpleBackPage(int values, int title, Class> cls) { 72 | this.values = values; 73 | this.title = title; 74 | this.cls = cls; 75 | } 76 | public Class> getCls() { 77 | return cls; 78 | } 79 | ``` 80 | ------ 81 | 82 | ## 当拿到Fragment类后 83 | 84 | `Fragment.class.newInstance()` 通过调用该类的无参数构造器,创建并返回该类的一个实例。 85 | 从结果上看等价于:`new Fragment();` 86 | 87 | > Returns a new instance of the class represented by this Class, created by invoking the default (that is, zero-argument) constructor. If there is no such constructor, or if the creation fails (either because of a lack of available memory or because an exception is thrown by the constructor), an InstantiationException is thrown. If the default constructor exists but is not accessible from the context where this method is invoked, an IllegalAccessException is thrown. 88 | 89 | 感觉上`Fragment.class.newInstance()`不如`new Fragment()`清楚明了。而且你还要为其添加try/catch `exception type IllegalAccessException`. 90 | 91 | */ 92 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/li2/update-and-replace-fragment-in-viewpager/944d6cf509690e104db24d4ed9aa5caad1c5708d/app/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/li2/update-and-replace-fragment-in-viewpager/944d6cf509690e104db24d4ed9aa5caad1c5708d/app/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/li2/update-and-replace-fragment-in-viewpager/944d6cf509690e104db24d4ed9aa5caad1c5708d/app/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/li2/update-and-replace-fragment-in-viewpager/944d6cf509690e104db24d4ed9aa5caad1c5708d/app/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 |