I want to create a PDF of "full page" of the activity. The view contains a RecyclerView with many items.
I can take a full dimensions of my Recyclerview but the file is drawed only of the current view. This is my code:
public void tela (){ // create a new document
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
PdfDocument document = new PdfDocument();
getScreenshotFromRecyclerView(mRecyclerView);
content = mRecyclerView;
content.setBackgroundColor(Color.parseColor("#303030"));
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(wil,
height, 1).create();
// create a new page from the PageInfo
PdfDocument.Page page = document.startPage(pageInfo);
// repaint the user's text into the page
content.draw(page.getCanvas());
// do final processing of the page
document.finishPage(page);
// saving pdf document to sdcard
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy - HH-mm-ss",Locale.getDefault());
String pdfName = "Revisões_"
+ sdf.format(Calendar.getInstance().getTime()) + ".pdf";
// all created files will be saved at path /sdcard/PDFDemo_AndroidSRC/
File outputFile = new File(Environment.getExternalStorageDirectory().getPath(), pdfName);
try {
outputFile.createNewFile();
OutputStream out = new FileOutputStream(outputFile);
document.writeTo(out);
document.close();
out.close();
Toast.makeText(this,"PDF gerado com sucesso",Toast.LENGTH_SHORT).show();
Log.i("Gerou", "pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
}
// getting the limits
public void getScreenshotFromRecyclerView(RecyclerView view) {
RecyclerView.Adapter adapter = view.getAdapter();
if (adapter != null) {
int size = adapter.getItemCount();
for (int i = 0; i < size; i++) {
RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
adapter.onBindViewHolder(holder, i);
holder.itemView.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(), holder.itemView.getMeasuredHeight());
height += holder.itemView.getMeasuredHeight();
}
wil=view.getMeasuredWidth();
}
}
The result is this:
Can I create the pdf with the all values of my Recyclerview?
Thanks.
I implemented a helper class to handle image saving to PDF. In the method saveImageToPDF() I pass:
a TabLayout, which is above my recyclerView
the Bitmap of the recyclerView
the Context
to get the recyclerView Bitmap I used this Take a screenshot of RecyclerView in FULL length
public class PDFHelper {
private File mFolder;
private File mFile;
private Context mContext;
public PDFHelper(File folder, Context context) {
this.mContext = context;
this.mFolder = folder;
if(!mFolder.exists())
mFolder.mkdirs();
}
public void saveImageToPDF(View title, Bitmap bitmap, String filename) {
mFile = new File(mFolder, filename + ".pdf");
if (!mFile.exists()) {
int height = title.getHeight() + bitmap.getHeight();
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), height, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
title.draw(canvas);
canvas.drawBitmap(bitmap, null, new Rect(0, title.getHeight(), bitmap.getWidth(),bitmap.getHeight()), null);
document.finishPage(page);
try {
mFile.createNewFile();
OutputStream out = new FileOutputStream(mFile);
document.writeTo(out);
document.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I have found a more simpler way to do it. I am not sure if my code is clean or is this the right way to do it. I had a recycler view with variable size. I wanted to print the whole length of the recycler view in pdf. Also I use IText Pdf just for reference.
Things that I did.
Below is the XML file for the single item in the recycler view. Please note that I have given an ID to the card view as I used card view (You can use any that you want as the root, LinearLayout or RelativeLayout etc.)android:id="#+id/preview_order_list_card_root"
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/preview_order_list_card_root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
android:src="#drawable/car"/>
<TextView
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#android:color/darker_gray"
android:text="12"/>
<TextView
android:id="#+id/preview_car_name"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="7dp"
android:gravity="center"
android:textSize="20sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/preview_car_model"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"/>
</LinearLayout>
<TextView
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/darker_gray"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/preview_part_name"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="7dp"
android:gravity="center"
android:textSize="20sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/preview_part_model"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="7dp"
android:gravity="center"/>
<TextView
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#android:color/darker_gray"
android:text="12"/>
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
android:src="#drawable/car_part"/>
</LinearLayout>
<TextView
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:background="#android:color/darker_gray"/>
<LinearLayout
android:layout_width="70dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="5dp"
android:orientation="vertical">
<TextView
android:id="#+id/preview_quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/holo_green_light"
android:gravity="center"
android:textSize="25sp"
android:layout_gravity="center"/>
<TextView
android:id="#+id/preview_quantity_bucket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:gravity="center"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_margin="15dp"
android:orientation="vertical">
<TextView
android:id="#+id/preview_extra_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="15dp">
<TextView
android:id="#+id/preview_ordered_from"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:textColor="#android:color/holo_red_light"/>
<TextView
android:id="#+id/preview_list_price"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="center"/>
<TextView
android:id="#+id/preview_list_less"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:gravity="right"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Now in your adapter just create an arraylist with getters and setters that will save the card view object when ever it calls onBindViewHolder is called as below.
private static ArrayList<CardView> cardViewArrayList = new ArrayList<>();
#Override
public void onBindViewHolder(final PreviewOrderAdapter.MyViewHolder holder, int position)
{
OrderItemDetailsModel orderItemDetailsModel = namesArrList.get(position);
holder.orderedFrom.setText(orderItemDetailsModel.getOrderedFrom());
holder.listPrice.setText(orderItemDetailsModel.getListPrice());
holder.listLess.setText(orderItemDetailsModel.getListLess());
// ADDING THE CARD VIEW OBJECT IN THE ARRAYLIST
addCardView(holder.cardView);
}
#Override
public int getItemCount()
{
return namesArrList.size();
}
private static void addCardView(CardView cardView)
{
cardViewArrayList.add(cardView);
}
public static ArrayList<CardView> getCardViewList()
{
return cardViewArrayList;
}
Now finally, while printing the recycler views do this.
//Getting the card view array list from the adapter above
ArrayList<CardView> cardViewArrayList = adapter.getCardViewList();
for (int i = 0; i < cardViewArrayList.size(); i++)
{
// Iterate till the last of the array list and add each view individually to the document.
addContent(document, cardViewArrayList.get(i));
}
//Adding the content to the document
private void addContent(Document document, View view)
throws DocumentException
{
try
{
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
image.scalePercent(70);
image.setAlignment(Image.MIDDLE);
document.add(image);
}
catch (Exception ex)
{
Log.e("TAG-ORDER PRINT ERROR", ex.getMessage());
}
}
By this way we dont have to worry about memory leaks due to the large size of the recycler view as we are adding each view separately to the document.
Related
have db with _id,hName,lName,detail,images
images stored in assets
images name in db (SQLite)
list layout without images working fine, but with images layout display's on names not images (no error in logcat)
wanted to bind CursorAdpater with `ImageView'
public void bindView(View view, Context context, Cursor cursor) {
TextView hName = view.findViewById(R.id.hName);
hName.setText(cursor.getString(cursor.getColumnIndex("hName")));
TextView lName = view.findViewById(R.id.lName);
lName.setText(cursor.getString(cursor.getColumnIndex("lName")));
ImageView image = view.findViewById(R.id.image);
InputStream is = null;
try {
is = context.getAssets().open("birds/" + cursor.getColumnIndex("images"));
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(is);
image.setImageBitmap(bitmap);
}
XML file:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image"
android:scaleType="fitCenter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:padding="24dp"
/>
<TextView
android:id="#+id/hName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/image"
android:layout_marginLeft="21dp"
android:layout_marginStart="10dp"
android:layout_toEndOf="#+id/image"
android:layout_toRightOf="#+id/image"
android:text="Name"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/lName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/image"
android:layout_alignLeft="#+id/hName"
android:layout_alignStart="#+id/hName"
android:textSize="16sp"
android:text="About" />
check the image extension is used in database
then try this
try {
is = context.getAssets().open("birds/" + cursor.getColumnIndex("images"));
Drawable d = Drawable.createFromStream(is, null);
image.setImageDrawable(d);
} catch (IOException e) {
e.printStackTrace();
}
I'm kinda new to android studio and most of my work was done referring to Stack Overflow answered questions and topics cutting short to the question.
my JSON is as such:
[
{ "name":"station1",
"url":"http://example1.com",
"image":"R.drawable.radio1"
},
{ "name":"station2",
"url":"example2.com",
"image":"R.drawable.radio2"
}
]
and so on,
and my XML is
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="fill_parent"
android:layout_height="100dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_editor_absoluteY="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RelativeLayout
android:id="#+id/relative1"
android:layout_width="100dp"
android:layout_height="100dp"></RelativeLayout>
</LinearLayout>
</HorizontalScrollView>
I need to load the image and name in a scroll view horizontally created dynamically every time I add another "name and image" to the JSON file please can someone help me with a code (the text below every image that loads).
First i suggest to create a class BEAN like this:
public class MyBean{
String name;
String url;
String image;
}
Now, as GrIsHu describes in their answer here:
you need to read the Json File from your assests file using below code:
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
After, transform the Json String into JsonArray like this:
JSONArray ja = new JSONArray(loadJSONFromAsset());
Now you can popolate a
List<MyBeen.class> lst
like this:
for (int i = 0; i < ja.length(); i++) {
lst.add(gSon.fromJson(ja.get(i).toString(), MyBeen.class));
}
first to all do you need to change HorizontalScrollView in ListView
https://developer.android.com/guide/topics/ui/layout/listview.html
, as:
<LinearLayout
android:id="#+id/fullscreen_content_controls"
style="?metaButtonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:ignore="UselessParent">
<ListView
android:id="#+id/lstView"
android:layout_margin="5dp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:divider="#android:color/transparent"
android:dividerHeight="10.0sp">
</ListView>
</LinearLayout>
When you add a in MainClass this code for work with ListView:
ListView listView = findViewById(R.id.lstView);
listView.setAdapter(new CustomAdapter(this, lst));
After, in CustomAdapter.java, need:
public class CustomAdapter extends BaseAdapter {
public CustomAdapter(MainClass mainActivity, List<?> iLst) {
lst = iLst;
context=mainActivity;
inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView;
rowView = inflater.inflate(R.layout.listview_custom, null); <-- RAPPRESENTE A SINGLE ROW LAYOUT
ImageView img = (ImageView) rowView.findViewById(R.id.customImg);
TextView text =(TextView) rowView.findViewById(R.id.customText);
return rowView;
}
}
At end, you add the XML layout for a single row, it will duplicate automatically for each row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/border_radius"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0sp"
android:layout_weight=".2"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center">
<ImageView
android:id="#+id/customImg"
android:layout_width="50sp"
android:layout_height="45sp"
android:drawableTint="#color/White"
android:background="#drawable/upload"
android:tint="#color/White"/>
</LinearLayout>
<LinearLayout
android:layout_width="0sp"
android:layout_weight=".6"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/customText"
android:paddingTop="5dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:ellipsize="none"
android:scrollHorizontally="false"
android:maxLines="100"
android:textColor="#color/White"
android:text="Title" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
I want to display the video thumbnails in listview, I use images instead of thumbnails and add ImageView (image play button) on the front but failed my xml code like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/txttgl"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:paddingLeft="10dip"
android:gravity="center_horizontal"/>
<TextView
android:id="#+id/tv_batas_unread"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:paddingLeft="12dip"
android:background="#drawable/counter_shape_birudonker"
android:visibility="gone"
android:gravity="center_horizontal"/>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/ll_chat_item"
android:orientation="horizontal" >
<com.ltvie.chatkrawala.ImageViewRounded
android:id="#+id/img_photo_pp_chatbox"
android:layout_width="50dp"
android:layout_height="50dp"
android:paddingBottom="0dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:adjustViewBounds="true"
android:paddingTop="0dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="3dp"
android:src="#drawable/gada_photo"
android:scaleType="fitXY" />
<LinearLayout
android:id="#+id/wrapper"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="left"
android:orientation="vertical"
android:layout_marginBottom="12dp"
android:layout_weight="1"
android:cacheColorHint="#android:color/transparent"
>
<TextView
android:id="#+id/txtKodeGbr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
<TextView
android:id="#+id/txtPesan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
<TextView
android:id="#+id/comment"
android:layout_marginTop="9dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/buble_kiri"
android:text="Bismillahirohmanirrohim"
android:textColor="#000"
android:textSize="15sp" />
<LinearLayout
android:id="#+id/rowFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="wrap_content"
>
<ImageView
android:id="#+id/img_dilvChat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:contentDescription="#string/descGambar"
android:background="#drawable/buble_kanan"
android:src="#drawable/gada_photo"
/>
<ImageView
android:id="#+id/img_btn_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/descGambar"
android:layout_centerInParent="true"
android:src="#drawable/play_icon"
/>
<ProgressBar
android:id="#+id/chatBox_progress_img"
style="?android:attr/progressBarStyleSmallInverse"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
<LinearLayout
android:id="#+id/rowFileDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_gravity="bottom"
android:orientation="vertical">
<TextView
android:id="#+id/txtFileName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dip"
android:gravity="left"
android:text="Nama File : test.zip"
android:textSize="12sp" />
<TextView
android:id="#+id/txtFileSize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dip"
android:gravity="left"
android:text="Ukuran : 2324342 bytes"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/img_statusBaca"
android:layout_marginTop="2dip"
android:layout_width="15dip"
android:layout_height="15dip"
android:layout_marginRight="1dip"
android:background="#drawable/indicator_sending"
android:contentDescription="#string/descGambar"
/>
<TextView
android:id="#+id/txtjamchatMasuk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dip"
android:gravity="left"
android:text="setatus baca"
android:textSize="12sp" />
<TextView
android:id="#+id/txtKiriKanan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dip"
android:paddingRight="5dip"
android:text="right"
android:visibility="gone"
/>
</LinearLayout>
</LinearLayout>
<ImageView
android:id="#+id/imgselected"
android:layout_width="20dp"
android:layout_height="20dp"
android:contentDescription="#string/kosongan"
android:src="#drawable/ico_member" />
</LinearLayout>
</LinearLayout>
my java code
public class ChatboxArrayAdapter extends ArrayAdapter<OneComment> implements SectionIndexer{
private TextView countryName;
private LinearLayout wrapper,rowFileDesc,ll_chat_item;
private TextView TanggalMasuk,txtKodeGbr,txtPesan,txtJam,txtKiriKanan,txtUkuranFile;
private ImageView img_upload,img_statusbaca,imgPp_round;
ImageView imgPhoto,imgCheck,imgBtnPlay;
String namafileGambar,strPath,varStsBaca,tampilTgl;
public CacheImageLoader imageLoader;
Context ctx;
Options opts = new BitmapFactory.Options();
String TAG="chatboxArrayAdapter";
File dir = new File(Environment.getExternalStorageDirectory()+"");
File dirImage=new File(dir+"/a");
File dirVideo=new File(dir+"/a");
List<OneComment> countries;
#Override
public void add(OneComment object) {
countries.add(object);
super.add(object);
}
public void hapus_semua(){
countries.clear();
}
public void hapus_item(int nomerx){
countries.remove(nomerx);
notifyDataSetChanged();
}
public void refresh_lv(){
notifyDataSetChanged();
Log.d("notify", "datachange");
}
public ChatboxArrayAdapter(Context context, int textViewResourceId, List<OneComment> datanya) {
super(context, textViewResourceId);
this.countries=datanya;
this.ctx=context;
imageLoader=new CacheImageLoader(context.getApplicationContext());
}
public int getCount() {
return this.countries.size();
}
#Override
public OneComment getItem(int index) {
return this.countries.get(index);
}
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
try{
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.chatbox_detail, parent, false);
}
OneComment isiOneComen = getItem(position);
wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
rowFileDesc=(LinearLayout) row.findViewById(R.id.rowFileDesc);
ll_chat_item=(LinearLayout) row.findViewById(R.id.ll_chat_item);
imgPhoto = (ImageView) row.findViewById(R.id.img_dilvChat);
countryName = (TextView) row.findViewById(R.id.comment);
txtKiriKanan = (TextView) row.findViewById(R.id.txtKiriKanan); //isi dari coment untuk menentukan letak buble di kiri ato dikanan,hanya untuk buble file untuk menentukan filenya masih di server apa sudah di downloa
TanggalMasuk= (TextView) row.findViewById(R.id.txttgl);
img_upload=(ImageView) row.findViewById(R.id.img_dilvChat);
txtKodeGbr = (TextView) row.findViewById(R.id.txtKodeGbr);
txtPesan=(TextView) row.findViewById(R.id.txtPesan);
txtJam=(TextView) row.findViewById(R.id.txtjamchatMasuk);
txtUkuranFile=(TextView) row.findViewById(R.id.txtFileSize);
imgCheck=(ImageView) row.findViewById(R.id.imgselected);
img_statusbaca=(ImageView) row.findViewById(R.id.img_statusBaca);
imgPp_round=(ImageView) row.findViewById(R.id.img_photo_pp_chatbox);
imgBtnPlay=(ImageView) row.findViewById(R.id.img_btn_play);
txtPesan.setVisibility(View.GONE);
txtKodeGbr.setVisibility(View.GONE);
img_upload.setVisibility(View.GONE);
rowFileDesc.setVisibility(View.GONE);
if(isiOneComen.comment.trim().equalsIgnoreCase("video")){
//error goes here
countryName.setVisibility(View.GONE);
Log.d("fileDesc", isiOneComen.Filedesc);
//strPath = namafileGambar;
strPath = moduleGlobal.dirImageSent+"/"+isiOneComen.Filedesc;
imgPhoto.setImageBitmap(changeSize(strPath));
scaleImage(imgPhoto, ((int) isiOneComen.lebarScreen)-((int) isiOneComen.lebarScreen/4));
imgBtnPlay.setVisibility(View.VISIBLE);
}else{ //run work well
countryName.setVisibility(View.VISIBLE);
try{
countryName.setText(getSmiledText(getContext(),isiOneComen.comment.toString()));
}catch (Exception e) {
// TODO: handle exception
Log.e("addsmiley", e.toString());
}
countryName.setBackgroundResource(isiOneComen.left ? R.drawable.buble_kiri : R.drawable.buble_kanan);
}
}catch (Exception ez) {
ll_chat_item.setVisibility(View.GONE);
Log.e(TAG, ez.toString());
}
return row;
}
private Bitmap changeSize(String path){
opts.inSampleSize = 1;
Bitmap bm = BitmapFactory.decodeFile(path);
if (bm.getHeight() > 150 || bm.getWidth() > 150) {
final int halfHeight = bm.getHeight() / 2;
final int halfWidth = bm.getWidth() / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / opts.inSampleSize) > 150
&& (halfWidth / opts.inSampleSize) > 150) {
opts.inSampleSize *= 2;
}
}
bm = BitmapFactory.decodeFile(path,opts); // this bitmap will be 1/8 the size of the original
return bm;
}
private void scaleImage(ImageView view, int boundBoxInDp)
{
// Get the ImageView and its bitmap
Drawable drawing = view.getDrawable();
Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();
// Get current dimensions
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// Determine how much to scale: the dimension requiring less scaling is
// closer to the its side. This way the image always stays inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) boundBoxInDp) / width;
float yScale = ((float) boundBoxInDp) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap and convert it to a format understood by the ImageView
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
#SuppressWarnings("deprecation")
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
width = scaledBitmap.getWidth();
height = scaledBitmap.getHeight();
// Apply the scaled bitmap
view.setImageDrawable(result);
// Now change ImageView's dimensions to match the scaled image
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
}
public Bitmap decodeToBitmap(byte[] decodedByte) {
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
/**tambah smiley
*
*/
private static final HashMap<String, Integer> emoticons = new HashMap<String, Integer>();
static {
emoticons.put(":)", R.drawable.s1);
emoticons.put(":D", R.drawable.s2);
emoticons.put(":(", R.drawable.s3);
emoticons.put("8o|", R.drawable.s16);
emoticons.put(":/", R.drawable.s17);
}
// Get image for each text smiles
public static Spannable getSmiledText(Context context, String text) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
int index;
for (index = 0; index < builder.length(); index++) {
for (Entry<String, Integer> entry : emoticons.entrySet()) {
int length = entry.getKey().length();
if (index + length > builder.length())
continue;
if (builder.subSequence(index, index + length).toString().equals(entry.getKey())) {
builder.setSpan(new ImageSpan(context, entry.getValue()), index, index + length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
index += length - 1;
break;
}
}
}
return builder;
}
#Override
public int getPositionForSection(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getSectionForPosition(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object[] getSections() {
// TODO Auto-generated method stub
return null;
}
}
everything work well before i add relative layout,I want to add image view center with other imageview but I get error log
java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams
Problem with
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
This line Change this line to
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
Because you forgot to Add
</LinearLayout>
</LinearLayout>
at the end of your xml.
Use this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:gravity="center_horizontal"
android:paddingLeft="10dip" />
<LinearLayout
android:id="#+id/ll_chat_item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<LinearLayout
android:id="#+id/wrapper"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:layout_weight="1"
android:cacheColorHint="#android:color/transparent"
android:gravity="left"
android:orientation="vertical" >
<TextView
android:id="#+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<LinearLayout
android:id="#+id/rowFile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/img_dilvChat"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_margin="3dp"
android:background="#drawable/buble_kanan"
android:contentDescription="#string/descGambar" />
<ImageView
android:id="#+id/img_btn_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:contentDescription="#string/descGambar"
android:src="#drawable/play_icon" />
</RelativeLayout>
<TextView
android:id="#+id/tv4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:gravity="center_horizontal"
android:paddingLeft="10dip" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
In my application , one Relative Layout has totally three ImageView()'s . I want to save all the three imageviews as a single .png file to the device storage on a single button click.
My code:
Layout XML :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/make" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="300dp"
android:layout_above="#+id/button1"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:src="#drawable/am0" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="Save Meme"
android:textStyle="bold"
android:textColor="#color/wt" />
<ImageView
android:id="#+id/top"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="64dp"
android:src="#drawable/ic_launcher" />
<ImageView
android:id="#+id/down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="74dp"
android:src="#drawable/ic_launcher" />
Activity Code :
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sm);
main1 = (ImageView) findViewById(R.id.imageView1);
top = (ImageView) findViewById(R.id.top);
down = (ImageView) findViewById(R.id.down);
Bundle rec = getIntent().getExtras();
int rec1 = getIntent().getExtras().getInt("ams0");
Bitmap bmp = (Bitmap) rec.getParcelable("bm0");
Bitmap bmp1 = (Bitmap) rec.getParcelable("bm1");
main1.setImageResource(rec1);
top.setImageBitmap(bmp);
down.setImageBitmap(bmp1);
}
How do I save the image views as a file ?
Try using a Сanvas
Bitmap mainBitmap = ((BitmapDrawable)main1.getDrawable()).getBitmap().copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mainBitmap);
canvas.drawBitmap(bmp.copy(Bitmap.Config.ARGB_8888, true), 1, 1, null);
canvas.drawBitmap(bmp1.copy(Bitmap.Config.ARGB_8888, true), 1, 1, null);
OutputStream os = null;
try {
os = new FileOutputStream("/sdcard/DCIM/Camera/myImages.png");
mainBitmap.compress(Bitmap.CompressFormat.PNG, 50, os);
} catch (IOException e) {
e.printStackTrace();
}
After many problems, I have finally been able to generate a PDF Document that has content and isn't corrupted using the PrintedPDFClass.
The problem is, however, the content in the PDF doesn't seem to bear any relation to the VIew I gave it to render...
The view that I want to render:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:kingdomspas="http://www.kingdomspas.com/android/custom"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableLayout
android:id="#+id/salesAgreementTableLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"></TableLayout>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/companyLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:contentDescription="#string/logo_description"
android:src="#drawable/company_logo" />
<LinearLayout android:layout_height="match_parent" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_weight="1">
<ImageView
android:id="#+id/companyAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:contentDescription="#string/address_description"
android:src="#drawable/company_address" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/salesExecInitials"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/round"
android:inputType="text"
android:maxLines="1"
android:paddingLeft="130dp"
android:singleLine="true" >
<requestFocus />
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="10dp"
android:text="#string/sales_exec_initials" />
</FrameLayout>
</LinearLayout>
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/salesExecInitials"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/round"
android:inputType="text"
android:maxLines="1"
android:paddingLeft="130dp"
android:singleLine="true" >
<requestFocus />
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:paddingLeft="10dp"
android:text="#string/sales_exec_initials" />
</FrameLayout>
</TableRow>
</TableLayout>
<View
android:paddingTop="50dp"
android:layout_width="fill_parent"
android:layout_height="2dip"
android:layout_weight="1"
android:background="#android:color/darker_gray" />
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="#+id/submitButton"
android:text="#string/submit_form"
android:padding="10dp"/>
</LinearLayout>
</ScrollView>
Which results in a UI like this:
The code I use to generate the PDF is:
Builder printAttrsBuilder = new Builder();
printAttrsBuilder.setMediaSize(PrintAttributes.MediaSize.ISO_A4);
printAttrsBuilder.setMinMargins(new Margins(5, 5, 5, 5));
PrintedPdfDocument document = new PrintedPdfDocument(context, printAttrsBuilder.build());
PageInfo pageInfo = new PageInfo.Builder(150, 150, 1).create();
Page page = document.startPage(pageInfo);
Canvas pdfCanvas = page.getCanvas();
salesFragmentTableLayout.draw(page.getCanvas());
document.finishPage(page);
File result = null;
FileOutputStream fos = null;
BufferedOutputStream bos= null;
FileDescriptor descriptor = null;
try {
result = File.createTempFile("Kingdom Spas Agreement", ".pdf", context.getCacheDir());
fos = new FileOutputStream(result);
bos = new BufferedOutputStream(fos);
document.writeTo(bos);
descriptor = fos.getFD();
descriptor.sync();
} catch (FileNotFoundException e) {
throw new KingdomSpasException("Failed to find relevent file", e);
} catch (IOException e) {
throw new KingdomSpasException("IO Problem occured while creatin the PDF", e);
} finally {
try {
if (bos != null) { bos.flush(); bos.close(); }
} catch (SyncFailedException e) {
throw new KingdomSpasException("Failed to correctly sync PDF file - may be corrupted", e);
} catch (IOException e) {
throw new KingdomSpasException("Failed to correctly clean up streams", e);
}
}
document.close();
But the PDF that is created looks like (viewing at 100% zoom):
Can anyone explain to me why the resulting PDf is (to my eyes at least) so different from my Original view and explain how to fix it?
Edit: Here's a link to the generated PDF in case that rovides any useful information: https://dl.dropboxusercontent.com/u/134344/KingdomSpasAgreement.pdf
According to the documentation:
public PdfDocument.PageInfo.Builder (int pageWidth, int pageHeight, int pageNumber)
Creates a new builder with the mandatory page info attributes.
Parameters
pageWidth The page width in PostScript (1/72th of an inch).
pageHeight The page height in PostScript (1/72th of an inch).
pageNumber The page number.
You use a
PageInfo pageInfo = new PageInfo.Builder(150, 150, 1).create();
Page page = document.startPage(pageInfo);
So, you create a page merely about 2 in x 2 in in size. In this small area only a part of the submit button fits. (The PDF page content actually even contains the string "Submit" but it is far outside the viewable area.)
As you are using the PrintedPdfDocument, you should instead use:
Page page = document.startPage(1);
(cf. the documentation again)