Java tutorial
//--------------------------------------------------------------------------------------- // Copyright (c) 2001-2016 by PDFTron Systems Inc. All Rights Reserved. // Consult legal.txt regarding legal and license information. //--------------------------------------------------------------------------------------- package com.pdftron.pdf.controls; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import com.pdftron.common.PDFNetException; import com.pdftron.pdf.PDFDoc; import com.pdftron.pdf.PDFDocGenerator; import com.pdftron.pdf.Page; import com.pdftron.pdf.Rect; import com.pdftron.pdf.tools.R; import com.pdftron.pdf.utils.Utils; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link AddPageDialogFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link AddPageDialogFragment#newInstance} factory method to * create an instance of this fragment. */ public class AddPageDialogFragment extends DialogFragment { public enum PageType { Blank, Lined, Grid, Graph, Music, } public enum PageSize { SameAsLast, Letter, Legal, A4, A3, Ledger, } public enum PageOrientation { Portrait, Landscape, } private static final String ARG_CURRENT_PAGE_SIZE = "current_page_size"; private static final String ARG_CURRENT_PAGE_TYPE = "current_page_type"; private static final String ARG_LAST_PAGE_WIDTH = "last_page_width"; private static final String ARG_LAST_PAGE_HEIGHT = "last_page_height"; private static final String ARG_CREATE_NEW_PDF = "create_new_pdf"; private static final double LINE_SHADE = 0.35; private static final double MARGIN_RED = 1.0; private static final double MARGIN_GREEN = 0.5; private static final double MARGIN_BLUE = 0.5; private float mDeviceScale; private PageSize mCurrentPageSize; private PageType mCurrentPageType; private PageOrientation mCurrentPageOrientation; private double mLastPageWidth; private double mLastPageHeight; private Spinner mPageSizeSpinner; private Spinner mPageOrientationSpinner; private ViewPager mViewPager; private LinearLayout mViewPagerDotLayout; private ArrayList<LinearLayout> mViewPagerChildren; private OnFragmentInteractionListener mListener = null; private boolean mCreateNewPdf = false; private EditText mNumOfPagesEdit; private TextView mTitleEditLabel; private EditText mTitleEdit; public AddPageDialogFragment() { // Required empty public constructor } public static AddPageDialogFragment newInstance(PageSize currentPageSize, PageType currentPageType, double lastPageWidth, double lastPageHeight, boolean createNewPdf) { AddPageDialogFragment fragment = new AddPageDialogFragment(); Bundle args = new Bundle(); args.putInt(ARG_CURRENT_PAGE_SIZE, currentPageSize.ordinal()); args.putInt(ARG_CURRENT_PAGE_TYPE, currentPageType.ordinal()); args.putDouble(ARG_LAST_PAGE_WIDTH, lastPageWidth / 72); args.putDouble(ARG_LAST_PAGE_HEIGHT, lastPageHeight / 72); args.putBoolean(ARG_CREATE_NEW_PDF, createNewPdf); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mCurrentPageSize = PageSize.values()[getArguments().getInt(ARG_CURRENT_PAGE_SIZE)]; mCurrentPageType = PageType.values()[getArguments().getInt(ARG_CURRENT_PAGE_TYPE)]; mCreateNewPdf = getArguments().getBoolean(ARG_CREATE_NEW_PDF); mLastPageWidth = getArguments().getDouble(ARG_LAST_PAGE_WIDTH); mLastPageHeight = getArguments().getDouble(ARG_LAST_PAGE_HEIGHT); mCurrentPageOrientation = mLastPageWidth > mLastPageHeight ? PageOrientation.Landscape : PageOrientation.Portrait; mDeviceScale = getContext().getResources().getDisplayMetrics().density; mViewPagerChildren = new ArrayList<>(); } } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.fragment_add_page_dialog, null); //, container, false); builder.setView(view); builder.setPositiveButton(getActivity().getResources().getString(R.string.tools_misc_ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { generateDoc(); dismiss(); } }); builder.setNegativeButton(getActivity().getResources().getString(R.string.tools_misc_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dismiss(); } }); if (mCreateNewPdf) { TextView title = (TextView) view.findViewById(R.id.addpagedialog_title); title.setText(R.string.dialog_add_page_title_newdoc); } mViewPagerDotLayout = (LinearLayout) view.findViewById(R.id.dot_layout); initViewPagerDotLayout(); mViewPager = (ViewPager) view.findViewById(R.id.page_type_view_pager); mViewPager.setAdapter(new PageTypePagerAdapter()); mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { changeDotPosition(position); } @Override public void onPageScrollStateChanged(int state) { } }); mTitleEdit = (EditText) view.findViewById(R.id.add_page_document_title_input); mNumOfPagesEdit = (EditText) view.findViewById(R.id.addpagedialog_numpages_edit); mTitleEditLabel = (TextView) view.findViewById(R.id.addpagedialog_doctitle_label); if (!mCreateNewPdf) { mTitleEdit.setVisibility(View.GONE); mTitleEditLabel.setVisibility(View.GONE); } mPageSizeSpinner = (Spinner) view.findViewById(R.id.pageSize_spinner); mPageSizeSpinner.setAdapter(getPageSizeSpinnerAdapter()); mPageSizeSpinner.setSelection(mCurrentPageSize.ordinal() - (mCreateNewPdf ? 1 : 0)); mPageSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mCurrentPageSize = PageSize.values()[position + (mCreateNewPdf ? 1 : 0)]; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); mPageOrientationSpinner = (Spinner) view.findViewById(R.id.pageOrientation_spinner); mPageOrientationSpinner.setAdapter(getOrientationSpinnerAdapter()); mPageOrientationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mCurrentPageOrientation = PageOrientation.values()[position]; } @Override public void onNothingSelected(AdapterView<?> parent) { } }); return builder.create(); } private void initViewPagerDotLayout() { if ((int) Math.ceil(PageType.values().length / 3.0) < 2) return; for (int i = 0; i < (int) Math.ceil(PageType.values().length / 3.0); i++) { ImageView dot = new ImageView(getContext()); LinearLayout.LayoutParams dotParams = new LinearLayout.LayoutParams((int) (8 * mDeviceScale + 0.5f), (int) (8 * mDeviceScale + 0.5f)); int margin = (int) (5 * mDeviceScale + 0.5f); dotParams.setMargins(margin, margin, margin, margin); dot.setLayoutParams(dotParams); dot.setImageDrawable(getResources().getDrawable(R.drawable.viewpager_point)); dot.setEnabled(i == 0 ? true : false); mViewPagerDotLayout.addView(dot); } } private void changeDotPosition(int position) { if ((int) Math.ceil(PageType.values().length / 3.0) < 2) return; for (int i = 0; i < (int) Math.ceil(PageType.values().length / 3.0); i++) { ImageView dot = (ImageView) mViewPagerDotLayout.getChildAt(i); dot.setEnabled(i == position ? true : false); } } private void setActiveMode(PageType type) { mCurrentPageType = type; for (PageType pType : PageType.values()) { LinearLayout btnLayout = mViewPagerChildren.get(pType.ordinal()); ImageView imgView = (ImageView) btnLayout.getChildAt(0); switch (pType) { case Blank: imgView.setImageDrawable(getResources().getDrawable( (type == pType) ? R.drawable.blankpage_selected : R.drawable.blankpage_regular)); break; case Lined: imgView.setImageDrawable(getResources().getDrawable( (type == pType) ? R.drawable.linedpage_selected : R.drawable.linedpage_regular)); break; case Graph: imgView.setImageDrawable(getResources().getDrawable( (type == pType) ? R.drawable.graphpage2_selected : R.drawable.graphpage2_regular)); break; case Grid: imgView.setImageDrawable(getResources().getDrawable( (type == pType) ? R.drawable.graphpage_selected : R.drawable.graphpage_regular)); break; case Music: imgView.setImageDrawable(getResources().getDrawable( (type == pType) ? R.drawable.musicpage_selected : R.drawable.musicpage_regular)); break; } } } private ArrayAdapter<CharSequence> getPageSizeSpinnerAdapter() { ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item); for (PageSize size : PageSize.values()) { switch (size) { case Letter: adapter.add(getString(R.string.dialog_add_page_page_size_letter)); break; case Legal: adapter.add(getString(R.string.dialog_add_page_page_size_legal)); break; case Ledger: adapter.add(getString(R.string.dialog_add_page_page_size_ledger)); break; case SameAsLast: if (!mCreateNewPdf) adapter.add(getString(R.string.dialog_add_page_page_size_same)); break; case A4: adapter.add(getString(R.string.dialog_add_page_page_size_a4)); break; case A3: adapter.add(getString(R.string.dialog_add_page_page_size_a3)); break; } } adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); return adapter; } private ArrayAdapter<CharSequence> getOrientationSpinnerAdapter() { ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_item); for (PageOrientation size : PageOrientation.values()) { switch (size) { case Portrait: adapter.add(getString(R.string.dialog_add_page_orientation_portrait)); break; case Landscape: adapter.add(getString(R.string.dialog_add_page_orientation_landscape)); break; } } adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); return adapter; } private void generateDoc() { int numOfPages = 1; try { if (!Utils.isNullOrEmpty(mNumOfPagesEdit.getText().toString())) { numOfPages = Integer.parseInt(mNumOfPagesEdit.getText().toString()); if (numOfPages < 1 || numOfPages > 1000) numOfPages = 1; } } catch (NumberFormatException e) { numOfPages = 1; } String title = getString(R.string.controls_bookmark_dialog_default_empty_title); if (mCreateNewPdf) { if (!Utils.isNullOrEmpty(mTitleEdit.getText().toString())) title = mTitleEdit.getText().toString(); } new GenerateTask(numOfPages, title, mListener).execute(); } @Override public void onAttach(Context context) { super.onAttach(context); } @Override public void onDetach() { super.onDetach(); mListener = null; } public void setListener(OnFragmentInteractionListener listener) { mListener = listener; } private class PageTypePagerAdapter extends PagerAdapter { @Override public Object instantiateItem(ViewGroup collection, int position) { LinearLayout layout = new LinearLayout(getContext()); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); layout.setLayoutParams(layoutParams); layout.setGravity(Gravity.CENTER); layout.setOrientation(LinearLayout.HORIZONTAL); for (int i = position * 3; i < (position * 3 + 3) && i < PageType.values().length; i++) { PageType type = PageType.values()[i]; LinearLayout btnLayout = new LinearLayout(getContext()); LinearLayout.LayoutParams btnLayoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); btnLayoutParams.setMargins((int) (10 * mDeviceScale + 0.5f), 0, (int) (10 * mDeviceScale + 0.5f), (int) (10 * mDeviceScale + 0.5f)); btnLayout.setLayoutParams(btnLayoutParams); btnLayout.setGravity(Gravity.CENTER); btnLayout.setOrientation(LinearLayout.VERTICAL); btnLayout.setTag(new Integer(i)); btnLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setActiveMode(PageType.values()[(Integer) v.getTag()]); } }); layout.addView(btnLayout); mViewPagerChildren.add(btnLayout); ImageView btnImage = new ImageView(getContext()); LinearLayout.LayoutParams imgParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, (int) (100 * mDeviceScale + 0.5f)); imgParams.setMargins(0, (int) (5 * mDeviceScale + 0.5f), 0, 0); btnImage.setLayoutParams(imgParams); btnImage.setAdjustViewBounds(true); btnLayout.addView(btnImage); TextView btnTextView = new TextView(getContext()); btnTextView.setTextColor(getResources().getColor(R.color.black)); btnTextView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); btnLayout.addView(btnTextView); switch (type) { case Blank: btnImage.setImageDrawable( getResources().getDrawable(type == mCurrentPageType ? R.drawable.blankpage_selected : R.drawable.blankpage_regular)); btnTextView.setText(R.string.dialog_add_page_blank); break; case Lined: btnImage.setImageDrawable( getResources().getDrawable(type == mCurrentPageType ? R.drawable.linedpage_selected : R.drawable.linedpage_regular)); btnTextView.setText(R.string.dialog_add_page_lined); break; case Graph: btnImage.setImageDrawable( getResources().getDrawable(type == mCurrentPageType ? R.drawable.graphpage2_selected : R.drawable.graphpage2_regular)); btnTextView.setText(R.string.dialog_add_page_graph); break; case Grid: btnImage.setImageDrawable( getResources().getDrawable(type == mCurrentPageType ? R.drawable.graphpage_selected : R.drawable.graphpage_regular)); btnTextView.setText(R.string.dialog_add_page_grid); break; case Music: btnImage.setImageDrawable( getResources().getDrawable(type == mCurrentPageType ? R.drawable.musicpage_selected : R.drawable.musicpage_regular)); btnTextView.setText(R.string.dialog_add_page_music); break; } } collection.addView(layout); return layout; } @Override public void destroyItem(ViewGroup collection, int position, Object view) { collection.removeView((View) view); } @Override public int getCount() { return (int) Math.ceil(PageType.values().length / 3.0); } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } } public interface OnFragmentInteractionListener { void onPageAddRequest(Page page); void onPagesAddRequest(Page[] pages); void onDocumentCreateRequest(PDFDoc doc, String title); } private class GenerateTask extends AsyncTask<Void, Void, Boolean> { private int numOfPages; private String title; private PDFDoc finalDoc; private Page[] pages; private OnFragmentInteractionListener listener; private Handler mProgressDialogHandler; private ProgressDialog mProgressDialog; private DialogInterface.OnCancelListener mProgressDialogCancelListener = new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { GenerateTask.this.cancel(true); dialog.dismiss(); } }; private Runnable mProgressDialogExecutor = new Runnable() { @Override public void run() { mProgressDialog.show(); } }; public GenerateTask(int numOfPages, String title, OnFragmentInteractionListener listener) { this.numOfPages = numOfPages; this.title = title; pages = new Page[numOfPages]; this.listener = listener; mProgressDialogHandler = new Handler(); mProgressDialog = new ProgressDialog(getContext()); mProgressDialog.setIndeterminate(true); mProgressDialog.setMessage(getString(R.string.tools_misc_please_wait)); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.setCancelable(true); mProgressDialog.setOnCancelListener(mProgressDialogCancelListener); } @Override protected void onPreExecute() { mProgressDialogHandler.postDelayed(mProgressDialogExecutor, 790); } @Override protected Boolean doInBackground(Void... params) { PDFDoc doc = null; Page page = null; double width = 8.5; double height = 11; if (mCurrentPageSize == PageSize.Legal) { height = 14; } else if (mCurrentPageSize == PageSize.Ledger) { width = 11; height = 17; } else if (mCurrentPageSize == PageSize.A3) { width = 11.69; height = 16.53; } else if (mCurrentPageSize == PageSize.A4) { width = 8.27; height = 11.69; } else if (mCurrentPageSize == PageSize.SameAsLast) { width = mLastPageWidth; height = mLastPageHeight; } if ((mCurrentPageOrientation == PageOrientation.Portrait && width > height) || (mCurrentPageOrientation == PageOrientation.Landscape && height > width)) { double temp = width; width = height; height = temp; } try { finalDoc = new PDFDoc(); } catch (PDFNetException e) { return false; } try { for (int i = 0; i < numOfPages; i++) { if (isCancelled()) { return false; } if (mCurrentPageType == PageType.Grid) { doc = PDFDocGenerator.generateGridPaperDoc(width, height, 0.25, 0.45, LINE_SHADE, LINE_SHADE, LINE_SHADE); } else if (mCurrentPageType == PageType.Graph) { doc = PDFDocGenerator.generateGraphPaperDoc(width, height, 0.25, 0.45, 1.7, 5, LINE_SHADE, LINE_SHADE, LINE_SHADE); } else if (mCurrentPageType == PageType.Music) { doc = PDFDocGenerator.generateMusicPaperDoc(width, height, 0.5, 10, 6.5, 0.25, LINE_SHADE, LINE_SHADE, LINE_SHADE); } else if (mCurrentPageType == PageType.Lined) { doc = PDFDocGenerator.generateLinedPaperDoc(width, height, 0.25, 0.45, LINE_SHADE, LINE_SHADE, LINE_SHADE, 1.2, MARGIN_RED, MARGIN_GREEN, MARGIN_BLUE, MARGIN_RED, MARGIN_GREEN * 1.6, MARGIN_BLUE * 1.6, 0.85, 0.35); } else if (mCurrentPageType == PageType.Blank) { doc = new PDFDoc(); page = doc.pageCreate(); Rect pageRect = new Rect(0, 0, width * 72, height * 72); page.setMediaBox(pageRect); page.setCropBox(pageRect); } if (page == null && doc != null) page = doc.getPage(1); if (!mCreateNewPdf) pages[i] = page; else finalDoc.pagePushBack(page); } } catch (PDFNetException e) { return false; } return true; } @Override protected void onCancelled() { } @Override protected void onPostExecute(Boolean pass) { super.onPostExecute(pass); mProgressDialogHandler.removeCallbacks(mProgressDialogExecutor); if (mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } if (!pass) { return; } if (listener != null && mCreateNewPdf) listener.onDocumentCreateRequest(finalDoc, title); else if (listener != null && !mCreateNewPdf && numOfPages == 1) listener.onPageAddRequest(pages[0]); else if (listener != null && !mCreateNewPdf && numOfPages > 1) listener.onPagesAddRequest(pages); } } }