我有一个由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