我有一個由3個選項卡的tablayout組成的活動。每個選項卡都是一個片段,它們都包含一個pdf視圖來查看不同的pdf文件。如何從異步類訪問片段的視圖?
我已經爲Pdf Viewer寫了一個類。我需要在衆多片段中調用該類來打開該片段中的pdf文件。但我無法正確傳遞上下文並訪問fragmet的PDFview。我使用C.pdfviewer.PDFView作爲我的PDFviewer。
這裏是我的代碼:
MyFragment.class
public class MyFragment extends Fragment {
PDFView pdfView;
String url = "mysite.pdf";
public MyFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_myfragment, container, false);
pdfView = (PDFView)view.findViewById(R.id.pdfViewer);
new RetrievePDFStream(this).execute(url);
return view;
}
}
RetrievePDFStream.class
public class RetrievePDFStream extends AsyncTask<String, Void, byte[]> {
public Fragment fContext;
PDFView pdfView;
public RetrievePDFStream(Fragment fContext) {
this.fContext = fContext;
}
@Override
protected byte[] doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException ex) {
return null;
}
try {
return IOUtils.toByteArray(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(byte[] inputStream) {
View view = fContext.getView();
pdfView = (PDFView)view.findViewById(R.id.pdfViewer);
pdfView.fromBytes(inputStream).load();
}
}
MyFragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="app.nvest.helpinsure.Fragment.MyFragment"
android:orientation="vertical"
android:background="#000000">
<com.github.barteksc.pdfviewer.PDFView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/pdfViewer"/>
</LinearLayout>
我已經試過了。它沒有工作 – vinitpradhan18
嘗試getActivity()。getBaseContext()。execute(url)。如果仍然沒有幫助,請發佈您的日誌 – Zoffa