Android - Choose an image from gallery and then resize it to fit into ImageView - android-imageview

I'm trying to fit an image into ImageView maintaining the aspect ratio, it loads the image but I don't know how to resize it well. If the image it's too big I want to crop it and if it's small I want to fit the ImageView, my code so far it this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imageButtonFotoPerfil);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
and the XML for the imageView:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButtonFotoPerfil"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="15dp"
android:onClick="loadImagefromGallery"
android:src="#drawable/perfil_persona_b"
android:background="#null"/>

Change layout_width, hegiht to 100dp, 120dp what size do you want or you can calculate size of image depend on size of screen.

Related

File provider error to receive pdf from another program

`# Dears, this class works well to receive PDF files from another application on below Android 6, but it gives an error for Android uper 6
` #RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public int ExtractImage(Intent intent) {
try {
String filepath = null;
if (intent != null) {
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_VIEW.equals(action) && type.endsWith("pdf")) {
Uri file_uri = intent.getData();
if (file_uri != null) {
filepath = file_uri.getPath();
}
} else if (Intent.ACTION_SEND.equals(action) && type.endsWith("pdf")) {
Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (uri != null) {
filepath = uri.getPath();
}
}
}
File file = new File(filepath);
PdfRenderer renderer = null;
Bitmap bm;
try {
renderer = new PdfRenderer(ParcelFileDescriptor.open(file,
ParcelFileDescriptor.MODE_READ_ONLY));
} catch (Exception e) {
}
assert renderer != null;
final int pageCount = renderer.getPageCount();
totalPage = pageCount;
for (int i = 0; i < pageCount; i++) {
PdfRenderer.Page page = renderer.openPage(i);
// Create a bitmap and canvas to draw the page into
int width = 570;
int zarib = 570 / (page.getWidth() + 1);
int height = (page.getHeight() * 2) + 1;
heightArray.add(i, height);
// Create a bitmap and canvas to draw the page into
bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// Create canvas to draw into the bitmap
Canvas c = new Canvas(bm);
// Fill the bitmap with a white background
Paint whiteBgnd = new Paint();
whiteBgnd.setColor(Color.WHITE);
whiteBgnd.setStyle(Paint.Style.FILL);
c.drawRect(0, 0, width, height, whiteBgnd);
// paint the page into the canvas
page.render(bm, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT);
// Save the bitmap
OutputStream outStream = null;
try {
outStream = new
FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/printDo2ta" + i + ".png");
} catch (Exception e) {
e.printStackTrace();
}
bm.compress(Bitmap.CompressFormat.PNG, 80, outStream);
try {
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
page.close();
}
} catch (Exception e) {
runOnUiThread(() -> Toast.makeText(getBaseContext(),
"خطا در پردازش فایل: " + e.getMessage(),
Toast.LENGTH_SHORT).show());
}
return totalPage;
}
I inserted this code in AndroidManifest.xml
`<provider
android:name="androidx.core.content.FileProvider"
android:authorities="ir.myproject.test.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths" />
</provider>`
`
And I made the class provider_paths.xml
`<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>`
I don't know what else I need to change to make it work on Android 8
please help me`

if statement doesn't check the values of the edittexts reached by scrolling the recyclerview

i have a recyclerview the has an edittext in each row. the user can change the value of the edittext as he wishes but it should not be left empty for the values will be saved in a database. for this i'm trying to check if the edittext is empty. if any row has an empty edittext, the user is given a message when he wants to save that there is an empty value. this is the code that i wrote:
public class recyclerview_viewholder : RecyclerView.ViewHolder
{
public TextView rownbr, itemname;
public EditText qty;
public TextView unit;
public LinearLayout linearLayout;
public recyclerview_viewholder(View itemView, Action<int> listener)
: base(itemView)
{
rownbr = itemView.FindViewById<TextView>(Resource.Id.rownbr);
itemname = itemView.FindViewById<TextView>(Resource.Id.laborname);
unit = itemView.FindViewById<TextView>(Resource.Id.days);
qty = itemView.FindViewById<EditText>(Resource.Id.overtime);
linearLayout = itemView.FindViewById<LinearLayout>(Resource.Id.linearLayout);
itemView.Click += (sender, e) => listener(base.LayoutPosition);
}
}
public class recyclerviewAdapter : RecyclerView.Adapter
{
// Event handler for item clicks:
public event EventHandler<int> ItemClick;
DataTable summary_Requests = new DataTable();
//Context context;
public readonly new_request_items context;
int selected_pos = -1;
private SwipeToDeleteCallback swipeToDeleteCallback;
List<list_item> item_details = new List<list_item>();
public recyclerviewAdapter(new_request_items context, DataTable sum_req, List<list_item> item_details)
{
this.context = context;
summary_Requests = sum_req;
this.item_details = item_details;
}
public recyclerviewAdapter(DataTable sum_req, SwipeToDeleteCallback swipeToDeleteCallback)
{
this.swipeToDeleteCallback = swipeToDeleteCallback;
summary_Requests = sum_req;
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.recycler_view_request_new_data, parent, false);
recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
vh.qty.TextChanged += (sender, e) =>
{
if (vh.qty.Text != "")
try
{
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["itemQty"] = Convert.ToDecimal(vh.qty.Text);
user.zero_val = "Not_exist";
}
catch (System.FormatException exp)
{
var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("qty can be decimal", icon);
user.zero_val = "exits";
}
else if (vh.qty.Text == "")
{
var icon = AppCompatResources.GetDrawable(context.Context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("value can not be empty", icon);
user.zero_val = "exits";
}
};
vh.ItemView.LongClick += (sender, e) =>
{
int position = vh.AdapterPosition;
string itemcode = summary_Requests.Rows[position]["itemcode"].ToString();
list_item result = item_details.Find(list_item => list_item.item_code == itemcode);
Bundle bundle = new Bundle();
bundle.PutString("result", JsonConvert.SerializeObject(result));
items_info iteminf = new items_info();
iteminf.Arguments = bundle;
iteminf.Cancelable = true;
var SupportFragmentManager = this.context.FragmentManager;
iteminf.Show(SupportFragmentManager, "dialog");
selected_pos = position;
NotifyDataSetChanged();
//fill global variables that need to be passed to detail fragment
};
return vh;
}
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
recyclerview_viewholder vh = holder as recyclerview_viewholder;
vh.rownbr.Text = summary_Requests.Rows[position]["rowNumber"].ToString();
vh.itemname.Text = summary_Requests.Rows[position]["name"].ToString();
vh.unit.Text = summary_Requests.Rows[position]["itemsunitcode"].ToString();
vh.qty.Text= summary_Requests.Rows[position]["itemQty"].ToString();
if (selected_pos == position)
vh.ItemView.SetBackgroundColor(Color.ParseColor("#4fa5d5"));
else
vh.ItemView.SetBackgroundColor(Color.LightGray);
}
public void RemoveItem(int position)
{
if (laborers_dt_total.Rows.Count != 0)
{
if (position < laborers_dt_total.Rows.Count && position > -1)
{
laborers_dt_total.Rows.RemoveAt(position);
}
else
{
Toast.MakeText(context.Context, "select an item to delete", ToastLength.Long).Show();
}
}
else if (laborers_dt_total.Rows.Count == 0)
{
Toast.MakeText(context.Context, "no items to delete", ToastLength.Long).Show();
}
for (int i = 0; i < laborers_dt_total.Rows.Count; i++)
{
laborers_dt_total.Rows[i]["rowNumber"] = (i + 1).ToString();
NotifyDataSetChanged();
}
}
public DataTable get_dt_final()
{
DataTable final_dt = summary_Requests.Copy();
return final_dt;
}
public override int ItemCount
{
get { return summary_Requests.Rows.Count; }
}
// Raise an event when the item-click takes place:
void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
// user.req_pos = position;
}
}
now it works well when there are only few rows in the recyclerview, but when there are many in which i have to scroll through it, if i keep an edittext empty in a row reached by scrolling, the user.zero_val doesn't take the value of exits to tell me that an edittext is empty. what should i do in this case? where do i check for empty edittext? thanks in advance.
this is a simple code i wrote with hopes it would illustrate my problem:
this is the axml of the recyclerview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="255sp"
android:id="#+id/recyclerView1" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button1" />
</LinearLayout>
this is the layout of each row of the recyclerview:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/light_grey"
android:padding="1dp"
android:layout_marginTop="0.5dp"
android:weightSum="8"
android:gravity="center"
android:id="#+id/linearLayout"
>
<TextView
android:text=""
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:id="#+id/rownbr"
android:background="#drawable/back"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:textSize="12dp"
android:gravity="center"
android:textColor="#000000"
/>
<TextView
android:text=""
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="4"
android:id="#+id/laborname"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:textSize="12dp"
android:gravity="center"
android:textColor="#000000"
android:background="#drawable/back"
android:layout_marginLeft="2dp"/>
<TextView
android:text=""
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:id="#+id/days"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:textSize="12dp"
android:textColor="#000000"
android:layout_marginLeft="2dp"
android:gravity="center"
android:background="#drawable/back"/>
<EditText
android:text=""
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:id="#+id/overtime"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:textSize="12dp"
android:textColor="#000000"
android:layout_marginLeft="2dp"
android:gravity="center"
android:background="#drawable/back"/>
</LinearLayout>
this is the back.xml drawable:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="#android:color/white" />
<stroke android:width="1dip" android:color="#4fa5d5"/>
</shape>
this is the activity where the recyclerview is populated and managed:
public class MainActivity : AppCompatActivity
{
RecyclerView mRecyclerView;
DataTable dt = new DataTable();
RecyclerView.LayoutManager mLayoutManager;
recyclerviewAdapter RecyclerviewAdapter;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
dt.Columns.Add("rowNumber");
dt.Columns.Add("name");
dt.Columns.Add("itemsunitcode");
dt.Columns.Add("itemQty");
dt.Rows.Add("1", "rana hd", "pcs", "1");
dt.Rows.Add("2", "rana hd1", "pcs", "1");
dt.Rows.Add("3", "rana hd2", "pcs", "1");
dt.Rows.Add("4", "rana hd3", "pcs", "1");
dt.Rows.Add("5", "rana hd4", "pcs", "1");
dt.Rows.Add("6", "rana hd5", "pcs", "1");
dt.Rows.Add("7", "rana hd6", "pcs", "1");
dt.Rows.Add("8", "rana hd7", "pcs", "1");
dt.Rows.Add("9", "rana hd8", "pcs", "1");
dt.Rows.Add("10", "rana hd9", "pcs", "1");
mRecyclerView = FindViewById<RecyclerView>(Resource.Id.recyclerView1);
Button btn= FindViewById<Button>(Resource.Id.button1);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.HasFixedSize = true;
mRecyclerView.SetLayoutManager(mLayoutManager);
RecyclerviewAdapter = new recyclerviewAdapter(this, dt);
mRecyclerView.SetAdapter(RecyclerviewAdapter);
btn.Click += delegate
{
if (user.zero_val == "exits")
Toast.MakeText(this, "exists", ToastLength.Long).Show();
if (user.zero_val == "Not_exist")
Toast.MakeText(this, "Not_exist", ToastLength.Long).Show();
};
}
public class recyclerview_viewholder : RecyclerView.ViewHolder
{
public TextView rownbr, itemname;
public EditText qty;
public TextView unit;
public LinearLayout linearLayout;
public recyclerview_viewholder(View itemView, Action<int> listener)
: base(itemView)
{
rownbr = itemView.FindViewById<TextView>(Resource.Id.rownbr);
itemname = itemView.FindViewById<TextView>(Resource.Id.laborname);
unit = itemView.FindViewById<TextView>(Resource.Id.days);
qty = itemView.FindViewById<EditText>(Resource.Id.overtime);
linearLayout = itemView.FindViewById<LinearLayout>(Resource.Id.linearLayout);
itemView.Click += (sender, e) => listener(base.LayoutPosition);
}
}
public class recyclerviewAdapter : RecyclerView.Adapter
{
// Event handler for item clicks:
public event EventHandler<int> ItemClick;
DataTable summary_Requests = new DataTable();
//Context context;
public readonly MainActivity context;
int selected_pos = -1;
public recyclerviewAdapter(MainActivity context, DataTable sum_req)
{
this.context = context;
summary_Requests = sum_req;
}
public override RecyclerView.ViewHolder
OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.From(parent.Context).
Inflate(Resource.Layout.recyclerview_data, parent, false);
recyclerview_viewholder vh = new recyclerview_viewholder(itemView, OnClick);
vh.qty.TextChanged += (sender, e) =>
{
if (vh.qty.Text != "")
try
{
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["itemQty"] = Convert.ToDecimal(vh.qty.Text);
user.zero_val = "Not_exist";
}
catch (System.FormatException exp)
{
var icon = AppCompatResources.GetDrawable(context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("qty can be decimal", icon);
user.zero_val = "exits";
}
else if (vh.qty.Text == "")
{
var icon = AppCompatResources.GetDrawable(context, Resource.Drawable.error_ic);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("value can not be empty", icon);
user.zero_val = "exits";
}
};
vh.ItemView.LongClick += (sender, e) =>
{
int position = vh.AdapterPosition;
selected_pos = position;
NotifyDataSetChanged();
};
return vh;
}
public override void
OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
recyclerview_viewholder vh = holder as recyclerview_viewholder;
vh.rownbr.Text = summary_Requests.Rows[position]["rowNumber"].ToString();
vh.itemname.Text = summary_Requests.Rows[position]["name"].ToString();
vh.unit.Text = summary_Requests.Rows[position]["itemsunitcode"].ToString();
vh.qty.Text = summary_Requests.Rows[position]["itemQty"].ToString();
if (selected_pos == position)
vh.ItemView.SetBackgroundColor(Color.ParseColor("#4fa5d5"));
else
vh.ItemView.SetBackgroundColor(Color.LightGray);
}
public DataTable get_dt_final()
{
DataTable final_dt = summary_Requests.Copy();
return final_dt;
}
public override int ItemCount
{
get { return summary_Requests.Rows.Count; }
}
// Raise an event when the item-click takes place:
void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
// user.req_pos = position;
}
}
}
}
this is the user class:
public static class user
{
public static string zero_val = "";
}
If I undstand your meanings correctly, I don't think it's correct to use variable zero_val in class user to indicate whether or not null values exist.For example ,if you have enter a empty value for the first EditText, then the value of zero_val will been changed to Not_exist, then if we enter another empty value for the second EditText, then the value of zero_val will also been changed to Not_exist,after that, if we change the second EditText to a correct value, then the value of zero_val will been changed to exits.But now, actually the first EditText still be empty.
I think you can verify the values the table DataTable when clicking button.
You can refer to the following code:
btn.Click += delegate
{
bool hasEmpty = false ;
foreach (DataRow row in dt.Rows)
{
string itemQty = row["itemQty"].ToString();
string rowNumber = row["rowNumber"].ToString();
System.Diagnostics.Debug.WriteLine("rowNumber =" + rowNumber + "< --- > itemQty = " + itemQty);
if (string.IsNullOrEmpty(itemQty)) {
hasEmpty = true;
}
}
//if (user.zero_val.Equals("exits"))
// Toast.MakeText(this, "exists", ToastLength.Long).Show();
//if (user.zero_val.Equals("Not_exist"))
// Toast.MakeText(this, "Not_exist", ToastLength.Long).Show();
if (!hasEmpty)
Toast.MakeText(this, "exists", ToastLength.Long).Show();
else
Toast.MakeText(this, "Not_exist", ToastLength.Long).Show();
};
In addition, modify the TextChanged function in RecyclerviewAdapter:
vh.qty.TextChanged += (sender, e) =>
{
if (!vh.qty.Text.Equals(""))
try
{
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["itemQty"] = Convert.ToDecimal(vh.qty.Text);
}
catch (System.FormatException exp)
{
var icon = AppCompatResources.GetDrawable(context, Resource.Drawable.error);
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("qty can be decimal", icon);
//store a empty value for this textview
int position = vh.LayoutPosition;
summary_Requests.Rows[position]["itemQty"] = "";
}
else if (vh.qty.Text.Equals(""))
{
var icon = AppCompatResources.GetDrawable(context, Resource.Drawable.error);
int position = vh.LayoutPosition;
//store a empty value for this textview
summary_Requests.Rows[position]["itemQty"] = "";
icon.SetBounds(0, 0, 50, 50);
vh.qty.SetError("value can not be empty", icon);
}
};

Animation of textview in android

i want to animate textview in such a way that collide with display horizontally and vertically mean while that change random color of text and that runs infinte.is there any way??
i tried like
Animation a = AnimationUtils.loadAnimation(this, R.anim.anim);
a.setFillAfter(true);
a.reset();
tv.startAnimation(a);
i got solution....
MY Solution
textview.xml
<?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="fill_parent"
android:orientation="vertical"
android:id="#+id/layout">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Helo suni" />
</LinearLayout>
just call repeat function in on create ..
private void repeat() {
// TODO Auto-generated method stub
if (curAnimation == 1) {
animation1 = new TranslateAnimation(width / 2, width, 0, height / 2);
animation1.setDuration(800);
} else if (curAnimation == 2) {
animation1 = new TranslateAnimation(width, width / 2, height / 2, height);
animation1.setDuration(800);
}
else if (curAnimation == 3) {
animation1 = new TranslateAnimation(width / 2, 0, height, height / 2);
animation1.setDuration(800);
}
else if (curAnimation == 4) {
animation1 = new TranslateAnimation(0,width/2,height/2,0);
animation1.setDuration(800);
}
animation1.setFillAfter(true);
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256),
rnd.nextInt(256));
tv.setTextColor(color);
tv.startAnimation(animation1);
animation1.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
if (curAnimation == 4)
curAnimation = 1;
else
curAnimation++;
repeat();
}
});
}

android expandableListView animate slide up?

I want to animate slide down and slide up on expandablelistview when I click the groupItem.Then I have finish the slide down.
public class ExpandAnimation extends Animation {
private static final String TAG = "ExpandAnimation";
private View mAnimatedView;
private LayoutParams mViewLayoutParams;
private int mMarginStart, mMarginEnd;
private boolean mIsVisibleAfter = false;
private boolean mWasEndedAlready = false;
/**
* Initialize the animation
* #param view The layout we want to animate
* #param duration The duration of the animation, in ms
*/
public ExpandAnimation(View view, int duration) {
setDuration(duration);
mAnimatedView = view;
mViewLayoutParams = (LayoutParams) view.getLayoutParams();
// if the bottom margin is 0,
// then after the animation will end it'll be negative, and invisible.
mIsVisibleAfter = (mViewLayoutParams.bottomMargin == 0);
mMarginStart = mViewLayoutParams.bottomMargin;
Log.i(TAG, "mMarginStart:>>>>>>>"+mMarginStart);
mMarginEnd = (mMarginStart == 0 ? (0- view.getHeight()) : 0);
Log.i(TAG, "mMarginEnd:>>>>>>>"+mMarginEnd);
view.setVisibility(View.VISIBLE);
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
Log.i(TAG, "applyTransformation-->"+interpolatedTime);
if (interpolatedTime < 1.0f) {
// Calculating the new bottom margin, and setting it
mViewLayoutParams.bottomMargin = mMarginStart
+ (int) ((mMarginEnd - mMarginStart) * interpolatedTime);
// Invalidating the layout, making us seeing the changes we made
mAnimatedView.requestLayout();
// Making sure we didn't run the ending before (it happens!)
} else if (!mWasEndedAlready) {
mViewLayoutParams.bottomMargin = mMarginEnd;
mAnimatedView.requestLayout();
if (mIsVisibleAfter) {
mAnimatedView.setVisibility(View.GONE);
}
mWasEndedAlready = true;
}
}
}
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
Log.i(TAG, "getChildView");
#SuppressWarnings("unchecked")
String text = ((Map<String, String>) getChild(groupPosition,
childPosition)).get("child");
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.child, null);
}
View toolbar = convertView.findViewById(R.id.toolbar);
setAnimationView(toolbar);
((LinearLayout.LayoutParams) toolbar.getLayoutParams()).bottomMargin = -75;
toolbar.setVisibility(View.GONE);
ExpandAnimation expandAni = new ExpandAnimation(toolbar, 1000);
toolbar.startAnimation(expandAni);
TextView tv = (TextView) convertView.findViewById(R.id.childTo);
tv.setText(text);
return convertView;
}
But when I click the groupItem to collapse the group,it doesn't call the getChildView() method.So how can I to call the getChildView() and let it slide up?
I believe that you want to extend BaseExpandableListAdapter if you want to call (or #Override) getChildView.
http://developer.android.com/reference/android/widget/BaseExpandableListAdapter.html

How can I convert a PDF into a web-browsable image?

I need to create an online viewer which converts PDF files into browsable images, like http://view.samurajdata.se/. I would like to do this in Grails. Does Grails have any plugins for this?
that's is possible by download PDFRenderer.jar fie and writing code is below
downloadedfile = request.getFile('sourceFile');
println "download file->"+downloadedfile
File destFile=new File('web-app/source-pdf/'+downloadedfile+'.pdf');
if(destFile.exists()){
destFile.delete();
}
File file = null;
try{
file = new File('web-app/source-pdf/'+downloadedfile+'.pdf');
downloadedfile.transferTo(file)
println "file->"+file
}catch(Exception e){
System.err.println("File Already Use")
//out.close();
}
File imageFile=new File("web-app/pdf-images");
if(imageFile.isDirectory())
{
String[] list=imageFile.list()
for(int i=0;i<list.length;i++){
File img=new File("web-app/pdf-images/"+i+".png")
img.delete()
}
}
//response.setContentType("image/png");
// response.setHeader("Cache-control", "no-cache");
RandomAccessFile raf;
BufferedImage[] img;
// response.setContentType("image/png");
// response.setHeader("Cache-control", "no-cache");
file=new File('web-app/source-pdf/'+downloadedfile+'.pdf');
try {
raf = new RandomAccessFile(file, "rws");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
// draw the first page to an image
int num=pdffile.getNumPages();
img=new BufferedImage[num]
for(int i=0;i<num;i++)
{
PDFPage page = pdffile.getPage(i);
//get the width and height for the doc at the default zoom
int width=(int)page.getBBox().getWidth();
int height=(int)page.getBBox().getHeight();
Rectangle rect = new Rectangle(0,0,width,height);
int rotation=page.getRotation();
Rectangle rect1=rect;
if(rotation==90 || rotation==270)
rect1=new Rectangle(0,0,(int)rect.height,(int)rect.width);
//generate the image
img[i] = (BufferedImage)page.getImage(
width,height , //width & height
rect1, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
ImageIO.write(img[i], "png",new File("web-app/pdf-images/"+i+".png"));
}
// out.close();
}
catch (FileNotFoundException e1) {
System.err.println(e1.getLocalizedMessage());
} catch (IOException e) {
System.err.println(e.getLocalizedMessage());
}
file = null;
render(view:'save',model:[images:img])