2017-05-29 114 views
0

的開頭我正在使用barteksc-AndroidPdfViewer。我正在使用此代碼當我更改頁面方向時,出現在頁面

package com.github.barteksc.sample; 

import android.content.ActivityNotFoundException; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.database.Cursor; 
import android.net.Uri; 
import android.provider.OpenableColumns; 
import android.support.annotation.NonNull; 
import android.support.v4.app.ActivityCompat; 
import android.support.v4.content.ContextCompat; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.widget.Toast; 

import com.github.barteksc.pdfviewer.PDFView; 
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener; 
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener; 
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle; 
import com.shockwave.pdfium.PdfDocument; 

import org.androidannotations.annotations.AfterViews; 
import org.androidannotations.annotations.EActivity; 
import org.androidannotations.annotations.NonConfigurationInstance; 
import org.androidannotations.annotations.OnActivityResult; 
import org.androidannotations.annotations.OptionsItem; 
import org.androidannotations.annotations.OptionsMenu; 
import org.androidannotations.annotations.ViewById; 

import java.util.List; 

@EActivity(R.layout.activity_main) 
@OptionsMenu(R.menu.options) 
public class PDFViewActivity extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener { 

    private static final String TAG = PDFViewActivity.class.getSimpleName(); 

    private final static int REQUEST_CODE = 42; 
    public static final int PERMISSION_CODE = 42042; 

    public static final String SAMPLE_FILE = "sample.pdf"; 
    public static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE"; 

    @ViewById 
    PDFView pdfView; 

    @NonConfigurationInstance 
    Uri uri; 

    @NonConfigurationInstance 
    Integer pageNumber = 0; 

    String pdfFileName; 

    @OptionsItem(R.id.pickFile) 
    void pickFile() { 
     int permissionCheck = ContextCompat.checkSelfPermission(this, 
       READ_EXTERNAL_STORAGE); 

     if (permissionCheck != PackageManager.PERMISSION_GRANTED) { 
      ActivityCompat.requestPermissions(
        this, 
        new String[]{READ_EXTERNAL_STORAGE}, 
        PERMISSION_CODE 
      ); 

      return; 
     } 

     launchPicker(); 
    } 

    void launchPicker() { 
     Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
     intent.setType("application/pdf"); 
     try { 
      startActivityForResult(intent, REQUEST_CODE); 
     } catch (ActivityNotFoundException e) { 
      //alert user that file manager not working 
      Toast.makeText(this, R.string.toast_pick_file_error, Toast.LENGTH_SHORT).show(); 
     } 
    } 

    @AfterViews 
    void afterViews() { 
     if (uri != null) { 
      displayFromUri(uri); 
     } else { 
      displayFromAsset(SAMPLE_FILE); 
     } 
     setTitle(pdfFileName); 
    } 

    private void displayFromAsset(String assetFileName) { 
     pdfFileName = assetFileName; 

     pdfView.fromAsset(SAMPLE_FILE) 
       .defaultPage(pageNumber) 
       .onPageChange(this) 
       .enableAnnotationRendering(true) 
       .onLoad(this) 
       .scrollHandle(new DefaultScrollHandle(this)) 
       .load(); 
    } 

    private void displayFromUri(Uri uri) { 
     pdfFileName = getFileName(uri); 

     pdfView.fromUri(uri) 
       .defaultPage(pageNumber) 
       .onPageChange(this) 
       .enableAnnotationRendering(true) 
       .onLoad(this) 
       .scrollHandle(new DefaultScrollHandle(this)) 
       .load(); 
    } 

    @OnActivityResult(REQUEST_CODE) 
    public void onResult(int resultCode, Intent intent) { 
     if (resultCode == RESULT_OK) { 
      uri = intent.getData(); 
      displayFromUri(uri); 
     } 
    } 

    @Override 
    public void onPageChanged(int page, int pageCount) { 
     pageNumber = page; 
     setTitle(String.format("%s %s/%s", pdfFileName, page + 1, pageCount)); 
    } 

    public String getFileName(Uri uri) { 
     String result = null; 
     if (uri.getScheme().equals("content")) { 
      Cursor cursor = 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; 
    } 

    @Override 
    public void loadComplete(int nbPages) { 
     PdfDocument.Meta meta = 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()); 

     printBookmarksTree(pdfView.getTableOfContents(), "-"); 

    } 

    public void printBookmarksTree(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 + "-"); 
      } 
     } 
    } 

    /** 
    * Listener for response to user permission request 
    * 
    * @param requestCode Check that permission request code matches 
    * @param permissions Permissions that requested 
    * @param grantResults Whether permissions granted 
    */ 
    @Override 
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], 
              @NonNull int[] grantResults) { 
     if (requestCode == PERMISSION_CODE) { 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
       launchPicker(); 
      } 
     } 
    } 

} 

更改頁面的方向。但是,如果我必須假設縱向模式和頁碼15在頁面方向改變時我們開始了橫向頁面。

enter image description here enter image description here

請幫我這件事。

+0

檢查這個答案。也許它可以幫助你:https://stackoverflow.com/questions/5726657/how-to-detect-orientation-change-in-layout-in-android – JCoder

+0

@Ahmer關於這個問題的任何消息? – Akis

+0

@Akis仍然沒有,它不能實現我試了很多次,但未能實現 –

回答

1

當你改變方向時,默認情況下Android會重新加載活動,這就是爲什麼你會丟失當前頁面。

有兩種解決方案,一種是最佳實踐,另一種解決方案可能取決於具體情況。

解決方案1:

節省onSaveInstanceState最後已知的頁面,然後獲取頁面回onCreate

protected void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putInt("current_page", pageNumber); 
} 

public void onCreate(Bundle savedInstanceState) { 
    if (savedInstanceState != null){ 
    pageNumber = savedInstanceState.getInt("current_page"); 
    } 
} 

解決方案2:

設置在清單文件中android:configChanges="orientation|screenSize" atribbute。這將保持屏幕的狀態與方向更改之前的狀態完全相同。

還請大家對活動的生命週期讀:https://developer.android.com/guide/components/activities/activity-lifecycle.html

+0

'android:configChanges =「orientation | screenSize」'很好,但它不能'pdfView.fitToWidth();'如果可能請把這個方法放在上面的代碼中,它會很容易爲我實現。 –

+0

@AhmerAfzal你應該去解決方案1或添加一個onOrientationChange事件,並在方向改變時調用pdfView.fitToWidth()。 – Akis

0
@EActivity(R.layout.activity_pdf_app_bar_main) 
@OptionsMenu(R.menu.options) 
public class PDFActivity extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener 
{ 
    private static final String TAG = PDFActivity.class.getSimpleName(); 
    private final static int REQUEST_CODE = 42; 
    public static final int PERMISSION_CODE = 42042; 
    public static final String SAMPLE_FILE = "myPDF.pdf"; 
    public static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE"; 
    private int mCurrentPage = 0; 
    private final static String KEY_CURRENT_PAGE = "current_page"; 
    private ProgressDialog progressDialog; 
    @ViewById 
    PDFView pdfView; 
    @NonConfigurationInstance 
    Uri uri; 
    @NonConfigurationInstance 
    String pdfFileName; 
    @OptionsItem(R.id.pickFile) 
    void pickFile() 
    { 
     int permissionCheck = ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE); 
     if (permissionCheck != PackageManager.PERMISSION_GRANTED) 
     { 
      ActivityCompat.requestPermissions(this, new String[]{READ_EXTERNAL_STORAGE}, PERMISSION_CODE); 
      return; 
     } 
     launchPicker(); 
    } 
    void launchPicker() 
    { 
     Intent intent = new Intent(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(); 
     } 
    } 
    @AfterViews 
    void afterViews() 
    { 
     pdfView.setBackgroundColor(Color.WHITE); 
     if (uri != null) 
     { 
      displayFromUri(uri); 
     } 
     else 
     { 
      displayFromAsset(SAMPLE_FILE); 
     } 
     setTitle(pdfFileName); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     if (getSupportActionBar() != null) 
     { 
      getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
      getSupportActionBar().setDisplayShowHomeEnabled(true); 
     } 
    } 

    private void displayFromAsset(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(new OnPageScrollListener() { 
        @Override 
        public void onPageScrolled(int page, float positionOffset) { 
         Log.d(TAG, "onPageScrolled: page " + page + " positionOffset " + positionOffset); 
        } 
       }) 
       .onRender(new OnRenderListener() 
       { 
        @Override 
        public void onInitiallyRendered(int nbPages, float pageWidth, float pageHeight) 
        { 
         pdfView.fitToWidth(mCurrentPage); 
        } 
       }) 
       .onLoad(new OnLoadCompleteListener() { 
        @Override 
        public void loadComplete(int nbPages) { 
         Log.d(TAG, "loadComplete: totalPages " + nbPages); 
        } 
       }) 
       .onError(new OnErrorListener() { 
        @Override 
        public void onError(Throwable t) { 
         Log.d(TAG, " onError"); 
        } 
       }) 
       .scrollHandle(new DefaultScrollHandle(this)) 
       .spacing(2) 
       .load(); 
    } 
    private void displayFromUri(Uri uri) 
    { 
     pdfFileName = getFileName(uri); 
     pdfView.fromUri(uri) 
       .defaultPage(mCurrentPage) 
       .onPageChange(this) 
       .enableAnnotationRendering(true) 
       .onLoad(this) 
       .scrollHandle(new DefaultScrollHandle(this)) 
       .load(); 
    } 
    @OnActivityResult(REQUEST_CODE) 
    public void onResult(int resultCode, Intent intent) 
    { 
     if (resultCode == RESULT_OK) 
     { 
      uri = intent.getData(); 
      displayFromUri(uri); 
     } 
    } 
    @Override 
    public void onPageChanged(int page, int pageCount) 
    { 
     mCurrentPage = page; 
     setTitle(String.format("%s %s/%s", "Page Number", page + 1, pageCount)); 
    } 
    public String getFileName(Uri uri) 
    { 
     String result = null; 
     if (uri.getScheme().equals("content")) 
     { 
      Cursor cursor = 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; 
    } 
    @Override 
    public void loadComplete(int nbPages) 
    { 
     if (mCurrentPage >= 0) 
     { 
      pdfView.jumpTo(mCurrentPage); 
     } 
     PdfDocument.Meta meta = 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(), "-"); 
    } 
    public void printBookmarksTree(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 + "-"); 
      } 
     } 
    } 
    @Override 
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) 
    { 
     if (requestCode == PERMISSION_CODE) 
     { 
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
      { 
       launchPicker(); 
      } 
     } 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) 
    { 
     if (item.getItemId() == android.R.id.home) 
     { 
      finish(); 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    @Override 
    protected void onCreate(@Nullable Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     if (savedInstanceState != null) 
     { 
      mCurrentPage = savedInstanceState.getInt(KEY_CURRENT_PAGE); 
     } 
     else 
     { 
      mCurrentPage = -1; 
     } 
    } 

    @Override 
    protected void onRestoreInstanceState(Bundle savedInstanceState) 
    { 
     super.onRestoreInstanceState(savedInstanceState); 
     mCurrentPage = savedInstanceState.getInt(KEY_CURRENT_PAGE); 
    } 

    @Override 
    public void onSaveInstanceState(Bundle outState) 
    { 
     super.onSaveInstanceState(outState); 
     outState.putInt(KEY_CURRENT_PAGE, mCurrentPage); 
    } 
} 
相關問題