When I Change The Page Orientation Come At The Beginning Of Page
I am using barteksc-AndroidPdfViewer. I am using this code package com.github.barteksc.sample; import android.content.ActivityNotFoundException; import android.content.Intent; im
Solution 1:
When you change orientation Android will by default reload the activity and this is why you are losing the current page.
There are 2 solutions one is the best practice and the other might work depending on the case.
Solution 1:
Save the last known page on onSaveInstanceState
and then get the page back on onCreate
protectedvoidonSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("current_page", pageNumber);
}
publicvoidonCreate(Bundle savedInstanceState) {
if (savedInstanceState != null){
pageNumber = savedInstanceState.getInt("current_page");
}
}
Solution 2:
Set the android:configChanges="orientation|screenSize"
atribbute in your Manifest file. This will retain the state of the screen exactly like it was before the orientation change.
Also please have a read on the activity lifecycle: https://developer.android.com/guide/components/activities/activity-lifecycle.html
Solution 2:
@EActivity(R.layout.activity_pdf_app_bar_main)@OptionsMenu(R.menu.options)publicclassPDFActivityextendsAppCompatActivityimplementsOnPageChangeListener, OnLoadCompleteListener
{
privatestaticfinalStringTAG= PDFActivity.class.getSimpleName();
privatefinalstaticintREQUEST_CODE=42;
publicstaticfinalintPERMISSION_CODE=42042;
publicstaticfinalStringSAMPLE_FILE="myPDF.pdf";
publicstaticfinalStringREAD_EXTERNAL_STORAGE="android.permission.READ_EXTERNAL_STORAGE";
privateintmCurrentPage=0;
privatefinalstaticStringKEY_CURRENT_PAGE="current_page";
private ProgressDialog progressDialog;
@ViewById
PDFView pdfView;
@NonConfigurationInstance
Uri uri;
@NonConfigurationInstance
String pdfFileName;
@OptionsItem(R.id.pickFile)voidpickFile()
{
intpermissionCheck= ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, newString[]{READ_EXTERNAL_STORAGE}, PERMISSION_CODE);
return;
}
launchPicker();
}
voidlaunchPicker()
{
Intentintent=newIntent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
try
{
startActivityForResult(intent, REQUEST_CODE);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(this, R.string.toast_pick_file_error, Toast.LENGTH_SHORT).show();
}
}
@AfterViewsvoidafterViews()
{
pdfView.setBackgroundColor(Color.WHITE);
if (uri != null)
{
displayFromUri(uri);
}
else
{
displayFromAsset(SAMPLE_FILE);
}
setTitle(pdfFileName);
Toolbartoolbar= (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
privatevoiddisplayFromAsset(String assetFileName)
{
pdfFileName = assetFileName;
pdfView.fromAsset(SAMPLE_FILE)
.defaultPage(mCurrentPage)
.enableSwipe(true)
.swipeHorizontal(false)
.enableDoubletap(true)
.password(null)
.enableAntialiasing(true)
.onPageChange(this)
.enableAnnotationRendering(true)
.onPageScroll(newOnPageScrollListener() {
@OverridepublicvoidonPageScrolled(int page, float positionOffset) {
Log.d(TAG, "onPageScrolled: page " + page + " positionOffset " + positionOffset);
}
})
.onRender(newOnRenderListener()
{
@OverridepublicvoidonInitiallyRendered(int nbPages, float pageWidth, float pageHeight)
{
pdfView.fitToWidth(mCurrentPage);
}
})
.onLoad(newOnLoadCompleteListener() {
@OverridepublicvoidloadComplete(int nbPages) {
Log.d(TAG, "loadComplete: totalPages " + nbPages);
}
})
.onError(newOnErrorListener() {
@OverridepublicvoidonError(Throwable t) {
Log.d(TAG, " onError");
}
})
.scrollHandle(newDefaultScrollHandle(this))
.spacing(2)
.load();
}
privatevoiddisplayFromUri(Uri uri)
{
pdfFileName = getFileName(uri);
pdfView.fromUri(uri)
.defaultPage(mCurrentPage)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(newDefaultScrollHandle(this))
.load();
}
@OnActivityResult(REQUEST_CODE)publicvoidonResult(int resultCode, Intent intent)
{
if (resultCode == RESULT_OK)
{
uri = intent.getData();
displayFromUri(uri);
}
}
@OverridepublicvoidonPageChanged(int page, int pageCount)
{
mCurrentPage = page;
setTitle(String.format("%s %s / %s", "Page Number", page + 1, pageCount));
}
public String getFileName(Uri uri)
{
Stringresult=null;
if (uri.getScheme().equals("content"))
{
Cursorcursor= getContentResolver().query(uri, null, null, null, null);
try
{
if (cursor != null && cursor.moveToFirst())
{
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
if (result == null)
{
result = uri.getLastPathSegment();
}
return result;
}
@OverridepublicvoidloadComplete(int nbPages)
{
if (mCurrentPage >= 0)
{
pdfView.jumpTo(mCurrentPage);
}
PdfDocument.Metameta= pdfView.getDocumentMeta();
Log.e(TAG, "title = " + meta.getTitle());
Log.e(TAG, "author = " + meta.getAuthor());
Log.e(TAG, "subject = " + meta.getSubject());
Log.e(TAG, "keywords = " + meta.getKeywords());
Log.e(TAG, "creator = " + meta.getCreator());
Log.e(TAG, "producer = " + meta.getProducer());
Log.e(TAG, "creationDate = " + meta.getCreationDate());
Log.e(TAG, "modDate = " + meta.getModDate());
Log.d(TAG, "totalPages " + nbPages);
printBookmarksTree(pdfView.getTableOfContents(), "-");
}
publicvoidprintBookmarksTree(List<PdfDocument.Bookmark> tree, String sep)
{
for (PdfDocument.Bookmark b : tree)
{
Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren())
{
printBookmarksTree(b.getChildren(), sep + "-");
}
}
}
@OverridepublicvoidonRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNullint[] grantResults)
{
if (requestCode == PERMISSION_CODE)
{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
launchPicker();
}
}
}
@OverridepublicbooleanonOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == android.R.id.home)
{
finish();
}
returnsuper.onOptionsItemSelected(item);
}
@OverrideprotectedvoidonCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
{
mCurrentPage = savedInstanceState.getInt(KEY_CURRENT_PAGE);
}
else
{
mCurrentPage = -1;
}
}
@OverrideprotectedvoidonRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
mCurrentPage = savedInstanceState.getInt(KEY_CURRENT_PAGE);
}
@OverridepublicvoidonSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(KEY_CURRENT_PAGE, mCurrentPage);
}
}
Post a Comment for "When I Change The Page Orientation Come At The Beginning Of Page"