How can set full screen background gif in Android Studio - java

I have a GIF image in my app and want this to become my full screen background. I use width and height = match parent but it's not becoming full screen. Here is my code :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
GifView pGif = (GifView) findViewById(R.id.gif);
pGif.setImageResource(R.drawable.bbbb);
}}
and this is my class:
public class GifView extends View {
private static final int DEFAULT_MOVIEW_DURATION = 1000;
private int mMovieResourceId;
private Movie mMovie;
private long mMovieStart = 0;
private int mCurrentAnimationTime = 0;
#SuppressLint("NewApi")
public GifView(Context context, AttributeSet attrs) {
super(context, attrs);
/**
* Starting from HONEYCOMB have to turn off HardWare acceleration to draw
* Movie on Canvas.
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
}
public void setImageResource(int mvId){
this.mMovieResourceId = mvId;
mMovie = Movie.decodeStream(getResources().openRawResource(mMovieResourceId));
requestLayout();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if(mMovie != null){
setMeasuredDimension(mMovie.width(), mMovie.height());
}else{
setMeasuredDimension(getSuggestedMinimumWidth(), getSuggestedMinimumHeight());
}
}
#Override
protected void onDraw(Canvas canvas) {
if (mMovie != null){
updateAnimtionTime();
drawGif(canvas);
invalidate();
}else{
drawGif(canvas);
}
}
private void updateAnimtionTime() {
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) {
mMovieStart = now;
}
int dur = mMovie.duration();
if (dur == 0) {
dur = DEFAULT_MOVIEW_DURATION;
}
mCurrentAnimationTime = (int) ((now - mMovieStart) % dur);
}
private void drawGif(Canvas canvas) {
mMovie.setTime(mCurrentAnimationTime);
mMovie.draw(canvas, 0, 0);
canvas.restore();
}
}
and xml :
<com.example.fabulous.comic.GifView
android:fitsSystemWindows="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/gif"/>

You can do this with help of glide
It is an image loading and caching library for Android focused on smooth scrolling
Glide supports fetching, decoding, and displaying video stills, images, and animated GIFs
you can use Glide using this
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support:support-v4:19.1.0'
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relative"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/img"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
<!--Rest of your coding-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
</FrameLayout>
java
ImageView img=(ImageView)findViewById(R.id.img);
Glide.with(Gif.this).load(R.drawable.giphy).asGif().into(img);
ps: i do not tested the code

Try using WebView, layout your view using simple html with your background as the gif then put it on your assets directory and load it using WebView. I have tried this on my other project, probably not the best solution but it works and quite easy.

In file build.gradle(module) add dependencies:
dependencies {
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support:support-v4:19.1.0'
}
For a simple view:
#Override public void onCreate(Bundle savedInstanceState) {
...
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
Glide.with(this).load("*link to image*").into(imageView);
}
Set in all layouts around image:
android:layout_width="match_parent"
android:layout_height="match_parent"

Related

Why is my Android ImageView empty (loading up through Uri, Bitmap or using Picasso)

I have a fragment to display a queue of either videos of images. The video I display in the VideoView works fine, it replays, it's golden. But the images I put in the ImageView just appear invisible. I tried loading them through Uri, by reading a Bitmap, now they're set up with Picasso, and none of it fixed it. The AssetObtainer you'll see in MultimediaPlayer works with both sound files and videos so far, so I highly doubt it has an issue with images. Here's the code:
MultimediaPlayer.java :
public class MultimediaPlayer extends Fragment
{
VideoView mVideoView;
ImageView mImageView;
MultimediaViewModel mMultimediaViewModel;
Play mPlayThread;
Activity mActivity;
AssetObtainer assetObtainer = new AssetObtainer();
public Long mTutorialId;
public List<Multimedia> multimedias = new LinkedList<>();
#Override
public View onCreateView(#NotNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_multimedia_player, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
mActivity = requireActivity();
mMultimediaViewModel = new ViewModelProvider(this).get(MultimediaViewModel.class);
mVideoView = view.findViewById(R.id.video_embed);
mImageView = view.findViewById(R.id.image_embed);
getPlayer(0);
}
private void getPlayer(int position)
{
if(mPlayThread != null) {
mPlayThread.interrupt();
position++;
}
if(!multimedias.isEmpty()) {
mPlayThread = new Play(multimedias.get(position));
mPlayThread.start();
}
}
private class Play extends Thread
{
private final Multimedia currentMedia;
Play(Multimedia media){
currentMedia = media;
}
#Override
public void run()
{
int position = currentMedia.getPosition();
int displayTime = currentMedia.getDisplayTime();
boolean loopBool = currentMedia.getLoop();
if(currentMedia.getType()) {
mActivity.runOnUiThread(() -> {
mImageView.setVisibility(View.VISIBLE);
mVideoView.setVisibility(View.GONE);
try {
Picasso.get().load(assetObtainer.getFileFromAssets(requireContext(), currentMedia.getFullFileName())).into(mImageView);
} catch (IOException ignored) {}
});
if(displayTime>0) {
try {
sleep(displayTime);
if(!loopBool) multimedias.remove(currentMedia);
if(position<multimedias.size()-1) {
getPlayer(position);
} else getPlayer(0);
} catch (InterruptedException e) {
mActivity.runOnUiThread(() -> mImageView.setVisibility(View.GONE));
interrupt();
}
}
} else {
mActivity.runOnUiThread(() -> {
mVideoView.setVisibility(View.VISIBLE);
mImageView.setVisibility(View.GONE);
try {
mVideoView.setVideoURI(Uri.fromFile(assetObtainer.getFileFromAssets(requireContext(), currentMedia.getFullFileName())));
} catch (IOException ignored) {}
if(loopBool && multimedias.size()==1) mVideoView.setOnCompletionListener(v->getPlayer(position-1));
mVideoView.start();
});
}
}
}
#Override
public void onPause()
{
if(mPlayThread!=null){
mPlayThread.interrupt();
}
super.onPause();
}
}
bed for the fragment in the activity .xml file :
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/layout_multimedia"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="#id/active_instructions" />
and the .xml file of the fragment :
<androidx.constraintlayout.widget.ConstraintLayout
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="wrap_content"
tools:context=".tutorial.mediaplayer.MultimediaPlayer">
<VideoView
android:id="#+id/video_embed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/image_embed"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:contentDescription="#string/image_default_no_description" />
</androidx.constraintlayout.widget.ConstraintLayout>
As mentioned, video works super fine, but images won't show. I'd appreciate even monkey wrench suggestions before I have to rework this entirely.
As mentioned in my other answer, it's not related to the ImageView, it's a problem with SQLite and loading a boolean from the database. The default false which I wanted to correspond with video types is default, so it worked, but since it doesn't default to true the image condition wasn't fulfilled. Anyway the ImageView will work once it is actually ran.

Using the camera in android

I am trying to build an Android app that simply uses the camera to take a picture without launching the default camera app. In other words, I want to make a custom camera app. I can do this using the Camera hardware object class, however this is deprecated and I want to use some of the new features of camerax and not have to worry about the code not working after some time. I have also read the camera API documentation, however it is still unclear how to use the camera. Are there any very simple step by step tutorials or guides that might help me?
Thanks,
You can check my example about how to use AndroidX libraries and TextureView for camera customization.
https://github.com/icerrate/Custom-Camera-App
First at all, define your layout. This is my activity_main.xml file:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextureView
android:id="#+id/view_finder"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/take_photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_margin="#dimen/horizontal_margin"
app:layout_constraintStart_toStartOf="parent"
android:src="#drawable/ic_camera"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Remember that TextureView will receive the camera preview and the Floating Action Button works as a "Take Photo" button.
Then add your MainActivity.java file:
public class MainActivity extends AppCompatActivity implements LifecycleOwner {
private static final int RC_PERMISSIONS = 100;
private TextureView viewFinder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
viewFinder = findViewById(R.id.view_finder);
FloatingActionButton takePhotoFab = findViewById(R.id.take_photo);
//Check permissions
if (allPermissionGranted()) {
viewFinder.post(new Runnable() {
#Override
public void run() {
startCamera();
}
});
} else {
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.CAMERA}, RC_PERMISSIONS);
}
takePhotoFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePhoto();
}
});
}
private void startCamera() {
Point screenSize = getScreenSize();
int width = screenSize.x;
int height = screenSize.y;
//Get real aspect ratio
DisplayMetrics displayMetrics = new DisplayMetrics();
Display display = getWindowManager().getDefaultDisplay();
display.getRealMetrics(displayMetrics);
Rational rational = new Rational(displayMetrics.widthPixels, displayMetrics.heightPixels);
//Build the camera preview
PreviewConfig build = new PreviewConfig.Builder()
.setTargetAspectRatio(rational)
.setTargetResolution(new Size(width,height))
.build();
Preview preview = new Preview(build);
preview.setOnPreviewOutputUpdateListener(new Preview.OnPreviewOutputUpdateListener() {
#Override
public void onUpdated(Preview.PreviewOutput output) {
ViewGroup group = (ViewGroup) viewFinder.getParent();
group.removeView(viewFinder);
group.addView(viewFinder, 0);
viewFinder.setSurfaceTexture(output.getSurfaceTexture());
}
});
CameraX.bindToLifecycle(this, preview);
}
private void takePhoto() {
Toast.makeText(this, "Shot!",
Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == RC_PERMISSIONS) {
if (allPermissionGranted()) {
viewFinder.post(new Runnable() {
#Override
public void run() {
startCamera();
}
});
} else {
Toast.makeText(this, "Permission not granted",
Toast.LENGTH_SHORT).show();
finish();
}
}
}
private boolean allPermissionGranted() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
}
private Point getScreenSize() {
Display display = getWindowManager(). getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size;
}
}
In this class, you would be able to send the camera preview to the TextureView, with help of PreviewConfig.Builder() and binding it to the Activity lifeCycle using CameraX.bindToLifeCycle()
Also, don't forget to add Camera permission to the manifest and consider runtime permissions.
Screenshot:
Custom Camera preview
Hope this help you!

How to make a horizontal ContextMenu?

I have made an Activity called Accounts and I want to add a horizontal ContextMenu. This may look like the cut, copy and paste options. Is there any way to add this horizontal custom menu onLongClick on the list items?
Here's what I've got so far.
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
LayoutInflater inflater = getLayoutInflater().from(this);
View view = inflater.inflate(R.layout.custom_listview, null, false);
menu.setHeaderView(view);
menu.add("Delete");
menu.add("Edit");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int position = info.position;
View v = listView.getChildAt(position);
TextView typeTv = v.findViewById(R.id.custom_listview_type);
TextView userTv = v.findViewById(R.id.custom_listview_user);
TextView passTv = v.findViewById(R.id.custom_listview_password);
if (item.getTitle().equals("Delete")) {
db.execSQL("delete from user_added_accounts where accountType = '" + typeTv.getText().toString() + "' and username = '" + userTv.getText().toString() + "';");
recreate();
}
if (item.getTitle().equals("Edit")) {
update(typeTv.getText().toString(), userTv.getText().toString(), passTv.getText().toString());
}
return true;
}
And the current UI looks like this.
Here is something like I want,
Simply you can achieve by QuickAction library.
https://github.com/piruin/quickaction
https://github.com/lorensiuswlt/NewQuickAction
Hope this will help you!!
I think the thing you need is the PopupWindow. Its easier to implement and has its custom layout setting option. The PopupWindow can be set in custom position as you wish and the idea of implementing a sample copy/paste UI that you are thinking of, can be served with the implementation of PopupWindow as well.
I found this answer very informative if you want to implement your situation with PopupWindow instead of implementing it with context menu.
In the above answer that I mentioned and provided a like to, has a PopupWindow which has a TextView only. You might implement any custom/complex UI instead of having a simple TextView like its shown there.
I hope that helps.
Update
As asked in the comment that getting locations of the position of PopupWindow can be set dynamically as well. I am referring to another link, so that you can check the implementation from there as well.
Here's the implementation of using PopupWindow in a list.
So , I wrote below code few year back. You need to make two class first is PopUp and second is TringleView.
PopUp :- Make dialog box and open into near your view(where you want
to open dialog). You can change popup bg color.
TringleView :- Make tringle view or you can say pointed arrow.You can change pointed arrow bg color.
View contentView = ((FragmentActivity)v.getContext()).getLayoutInflater().inflate(R.layout.edit_delete_layout,getAttachedRecyclerView(),false);
// this view denote where you click or you want to open dialog near
PopUp.showPopupOnView(((FragmentActivity) v.getContext()).getSupportFragmentManager(),contentView,view,false);
PopUp.class
public class PopUp extends DialogFragment {
protected int targetX;
protected int targetY;
protected int targetWidth;
protected int targetHeight;
protected Bitmap targetViewImage;
protected View contentView;
private SmartWorksPopUpViewHolder fragmentViewHolder;
private static int bgDrawable = R.drawable.round_corner_white_bg;
protected static int ONE_DIP;
private static int arrowBgColor = R.color.border_color;
private static int arrowWidthMultiple = 25;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (ONE_DIP == 0) {
ONE_DIP = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 1, getResources()
.getDisplayMetrics());
}
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Translucent);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
AbsoluteLayout parent = new AbsoluteLayout(getActivity());
parent.setId(R.id.parentLayout);
return parent;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.fragmentViewHolder = createViewHolder(view);
bindView(fragmentViewHolder);
}
protected SmartWorksPopUpViewHolder createViewHolder(
View fragmentView) {
return new SmartWorksPopUpViewHolder(fragmentView, contentView);
}
private void bindView(SmartWorksPopUpViewHolder vh) {
if (fragmentViewHolder != null) {
setupTargetDummyView(vh);
boolean showOnTop = shouldShowOnTop();
setupArrow(vh, showOnTop);
setupContent(vh, showOnTop);
}
}
protected void setupContent(SmartWorksPopUpViewHolder vh, boolean showOnTop) {
final int y;
AbsoluteLayout.LayoutParams arrowParams = (android.widget.AbsoluteLayout.LayoutParams) vh.arrow
.getLayoutParams();
int measureHeight = View.MeasureSpec.makeMeasureSpec(
ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED);
int measureWidth = View.MeasureSpec.makeMeasureSpec(
getActivity().getWindow().getDecorView().getWidth(), View.MeasureSpec.EXACTLY);
vh.popupView.measure(measureWidth, measureHeight);
if (showOnTop) {
y = this.targetY - vh.popupView.getMeasuredHeight() + ONE_DIP;
} else {
y = arrowParams.y + arrowParams.height - ONE_DIP * 2;
}
updateAbsoluteLayoutParams(
getActivity().getResources().getDimensionPixelOffset(R.dimen.sixty_dp),
y,
getActivity().getWindow().getDecorView().getWidth() -
getActivity().getResources().getDimensionPixelOffset(R.dimen.seventy_dp),
ViewGroup.LayoutParams.WRAP_CONTENT, vh.popupView);
vh.parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
exit();
}
});
}
private void setupArrow(SmartWorksPopUpViewHolder vh, boolean showOnTop) {
final int arrowHeight = 15 * ONE_DIP;
final int arrowWidth = arrowWidthMultiple * ONE_DIP;
vh.arrow.setDirectionAndColor(showOnTop ? "down" : "top", vh.popupView.getContext().getResources().getColor(arrowBgColor));
final int x = (int) (targetX + targetWidth / 3 - arrowWidth / 2);
final int y = targetY + (showOnTop ? -arrowHeight : targetHeight);
updateAbsoluteLayoutParams(x, y, arrowWidth, arrowHeight, vh.arrow);
}
private void setupTargetDummyView(SmartWorksPopUpViewHolder vh) {
vh.targetViewDummy.setImageBitmap(targetViewImage);
updateAbsoluteLayoutParams(targetX, targetY, targetWidth, targetHeight, vh.targetViewDummy);
}
protected void updateAbsoluteLayoutParams(int x, int y, int width, int height, View view) {
AbsoluteLayout.LayoutParams layoutParams =
(android.widget.AbsoluteLayout.LayoutParams) view.getLayoutParams();
layoutParams.x = x;
layoutParams.y = y;
layoutParams.height = height;
layoutParams.width = width;
view.setLayoutParams(layoutParams);
}
private boolean shouldShowOnTop() {
int windowHeight = getActivity().getWindow().getDecorView().getHeight();
int windowMid = windowHeight / 4;
return targetY > windowMid;
}
#Override
public void onDestroyView() {
this.fragmentViewHolder = null;
super.onDestroyView();
}
protected static class SmartWorksPopUpViewHolder {
protected AbsoluteLayout parent;
protected View popupView;
protected TringleView arrow;
protected AppCompatImageView targetViewDummy;
protected SmartWorksPopUpViewHolder(View fragmentView, View content) {
this.parent = (AbsoluteLayout) fragmentView;
final Context mContext = fragmentView.getContext();
this.popupView = content;
this.arrow = new TringleView(mContext);
this.targetViewDummy = new SmartWorksAppCompactImageView(mContext);
this.parent.addView(popupView);
this.parent.addView(arrow);
this.parent.addView(targetViewDummy);
this.parent.setBackgroundColor(0x00000000);
content.setBackgroundResource(bgDrawable);
}
}
public static PopUp showPopupOnView(FragmentManager fm, View contentView, View targetView, boolean showTargetView) {
int[] location = new int[2];
targetView.getLocationInWindow(location);
PopUp fragment = new PopUp();
fragment.targetX = location[0];
fragment.targetY = (int) (location[1] - TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 25,
targetView.getResources().getDisplayMetrics()));
fragment.targetWidth = targetView.getMeasuredWidth();
fragment.targetHeight = targetView.getMeasuredHeight();
fragment.contentView = contentView;
fragment.show(fm, "offer");
return fragment;
}
public void exit() {
dismiss();
}
public static void setArrowBackgroundColor(int color) {
arrowBgColor = color;
}
public static void setArrowWidthMultiple(int arrowWidth) {
arrowWidthMultiple = arrowWidth;
}
}
TringleView.class
public class TringleView extends View {
private String direction;
private int color;
public TringleView(Context context) {
super(context);
setDirectionAndColor("right", Color.RED);
}
public TringleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setDirectionAndColor(attrs.getAttributeValue(null, "direction"), Color.RED);
}
public TringleView(Context context, AttributeSet attrs) {
super(context, attrs);
setDirectionAndColor(attrs.getAttributeValue(null, "direction"), Color.RED);
}
public void setDirectionAndColor(String direction, int color) {
if (direction != null && !direction.equals(this.direction) || this.color != color) {
createTriangleDrawable(direction, color);
}
}
private void createTriangleDrawable(String string, int color) {
int width = MeasureSpec.makeMeasureSpec(30, MeasureSpec.UNSPECIFIED);
int height = MeasureSpec.makeMeasureSpec(20, MeasureSpec.UNSPECIFIED);
Path path = new Path();
if (string == null) {
string = "right";
}
if (string.equals("top")) {
path.moveTo(0, height);
path.lineTo(width / 2, 0);
path.lineTo(width, height);
} else if (string.equals("left")) {
path.moveTo(width, 0);
path.lineTo(0, height / 2);
path.lineTo(width, height);
} else if (string.equals("right")) {
path.moveTo(0, 0);
path.lineTo(width, height / 2);
path.lineTo(0, height);
} else if (string.equals("down")) {
path.moveTo(0, 0);
path.lineTo(width / 2, height);
path.lineTo(width, 0);
}
path.close();
ShapeDrawable shapeDrawable = new ShapeDrawable(new PathShape(path, width, height));
shapeDrawable.getPaint().setColor(color);
setBackground(shapeDrawable);
this.color = color;
this.direction = string;
}
}
edit_delete_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
app:cardCornerRadius="#dimen/five_dp"
android:layout_margin="#dimen/ten_dp"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="5"
android:gravity="center"
android:orientation="horizontal"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<sis.com.smartworks.widget.SmartWorksTextView
android:id="#+id/share"
android:textSize="#dimen/smallest_text_size"
android:textColor="#color/black"
android:visibility="visible"
android:gravity="center"
android:paddingRight="#dimen/four_dp"
android:paddingLeft="#dimen/four_dp"
android:paddingTop="#dimen/ten_dp"
android:paddingBottom="#dimen/ten_dp"
android:text="Share"
android:layout_weight="1"
android:textStyle="bold"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<View
android:layout_width="1dp"
android:background="#color/grey_unselect"
android:layout_height="match_parent" />
<sis.com.smartworks.widget.SmartWorksTextView
android:id="#+id/reportSpam"
android:textSize="#dimen/smallest_text_size"
android:textColor="#color/black"
android:visibility="visible"
android:gravity="center"
android:paddingRight="#dimen/four_dp"
android:paddingLeft="#dimen/four_dp"
android:paddingTop="#dimen/ten_dp"
android:paddingBottom="#dimen/ten_dp"
android:text="Spam"
android:layout_weight="1"
android:textStyle="bold"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<View
android:layout_width="1dp"
android:background="#color/grey_unselect"
android:layout_height="match_parent" />
<!--<View-->
<!--android:layout_width="match_parent"-->
<!--android:layout_marginLeft="#dimen/three_dp"-->
<!--android:layout_marginRight="#dimen/three_dp"-->
<!--android:background="#color/white"-->
<!--android:layout_height="#dimen/one_dp" />-->
<sis.com.smartworks.widget.SmartWorksTextView
android:id="#+id/edit"
android:textSize="#dimen/smallest_text_size"
android:textColor="#color/black"
android:gravity="center"
android:paddingRight="#dimen/four_dp"
android:paddingLeft="#dimen/four_dp"
android:paddingTop="#dimen/ten_dp"
android:paddingBottom="#dimen/ten_dp"
app:swFontName="robotoNormal"
android:layout_weight="1"
android:text="#string/edit"
android:textStyle="bold"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<View
android:layout_width="1dp"
android:background="#color/grey_unselect"
android:layout_height="match_parent" />
<!--<View-->
<!--android:layout_width="match_parent"-->
<!--android:layout_marginLeft="#dimen/three_dp"-->
<!--android:layout_marginRight="#dimen/three_dp"-->
<!--android:background="#color/white"-->
<!--android:layout_height="#dimen/one_dp" />-->
<sis.com.smartworks.widget.SmartWorksTextView
android:id="#+id/delete"
android:textSize="#dimen/smallest_text_size"
android:textColor="#color/black"
android:gravity="center"
android:paddingRight="#dimen/four_dp"
android:paddingLeft="#dimen/four_dp"
android:paddingTop="#dimen/ten_dp"
android:paddingBottom="#dimen/ten_dp" android:layout_weight="1"
android:text="#string/delete"
android:textStyle="bold"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<View
android:layout_width="1dp"
android:background="#color/grey_unselect"
android:layout_height="match_parent" />
<sis.com.smartworks.widget.SmartWorksTextView
android:id="#+id/cancel"
android:textSize="#dimen/smallest_text_size"
android:textColor="#color/black"
android:gravity="center"
android:layout_weight="1"
android:visibility="visible"
android:paddingRight="#dimen/four_dp"
android:paddingLeft="#dimen/four_dp"
android:paddingTop="#dimen/ten_dp"
android:paddingBottom="#dimen/ten_dp"
android:textStyle="bold"
android:text="#string/select_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
Result
So if you want to make view as horizontal then you need to make horizontal layout according to your requirement. So can do this task to change your edit_delete_layout.xml which your putting into contentView then pass to Popup class method.
Note:- You can customise popup class according to your requirement and I know this code having so many deprecated view so you can update yourself.
To show compact contextual menu you need to create ActionMode for the Menu, let me show you how:
Suppose your action menu XML have delete, copy and forward actions:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_copy"
android:icon="#drawable/ic_vector_menu_copy"
android:title="Copy"
app:showAsAction="always" />
<item
android:id="#+id/action_delete"
android:icon="#drawable/ic_vector_menu_delete"
android:title="Delete"
app:showAsAction="always" />
<item
android:id="#+id/action_forward"
android:icon="#drawable/ic_vector_menu_forward"
android:title="Forward"
app:showAsAction="always" />
</menu>
Create your action menu in your Activity
//Global variable in Activity/Fragment to manage close the menu
private ActionMode mActionMode;
//Action mode callbacks
//Contextual Action bar - for showing delete/copy/... on action bar
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.menu_contextual_action, menu);
return true;
}
// Called each time the action mode is shown.
// Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
#Override
public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
//Do the delete action
//mAdapter.resetSelection();
mode.finish(); // Action picked, so close the TAB
//showToast "Deleted successfully"
return true;
case R.id.action_copy:
//mAdapter.resetSelection();
MyClipboardManager.copyToClipboard(ChatDetailActivity.this, mAdapter.getSelectedMessageText());
mode.finish(); // Action picked, so close the TAB
//showToast "Text copied to clipboard"
return true;
default:
return false;
}
}
// Called when the user exits the action mode
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
//mAdapter.resetSelection();
}
};
#Override
public void onBackPressed() {
//Closing menu first if it's visible rather than doing the back press action
if (mActionMode != null && mActionMode.getMenu().hasVisibleItems()) {
mActionMode.finish();
return;
}
super.onBackPressed();
}
#Override
public void onDestroy() {
//Closing menu
if (mActionMode != null) {
mActionMode.finish();
}
super.onDestroy();
}
*Set the callback to the global action mode variable
mActionMode = startSupportActionMode(mActionModeCallback);
*Set title to the menu
mActionMode.setTitle("Menu title");
*Invalidate the menu after settings value
mActionMode.invalidate();
Style to manage compact contextual menu
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:windowDisablePreview">true</item>
<!--CONTEXTUAL action MODE-->
<item name="android:windowContentOverlay">#null</item>
<!--ActionMode background color-->
<!-- <item name="android:actionModeBackground">#color/colorPrimary</item>-->
<!--To Overlay existing toolbar, NOTE We are not using android: to let it work everywhere-->
<item name="windowActionModeOverlay">true</item>
<item name="actionModeStyle">#style/AppActionModeStyle</item>
<item name="android:actionModeCloseDrawable">#drawable/ic_arrow_back_24dp</item>
</style>
<style name="AppActionModeStyle" parent="#style/Widget.AppCompat.ActionMode">
<!--ActionMode background color-->
<item name="background">#color/colorPrimary</item>
<!--ActionMode text title color-->
<item name="titleTextStyle">#style/ActionModeTitleTextStyle</item>
</style>
<style name="ActionModeTitleTextStyle" parent="#style/TextAppearance.AppCompat.Widget.ActionMode.Title">
<item name="android:textColor">#android:color/white</item>
</style>

How to implement PdfRenderer Zoom and Scroll support?

I am trying to use PdfRenderer, and the requirement is to have Zoom and scroll available with it, but in Android PdfRenderer do not provide any support for Zoom and scroll, there is only page navigation support available.
But i guess zoom and scroll support can be implemented as PdfRenderer uses bitmap to show the content using imageview.
How to implement Zoom and Scroll support with Google PdfRenderer
sample?
PS: I am using this PdfRenderer sample provided by Google, https://github.com/googlesamples/android-PdfRendererBasic
I used the idea of #yan-yankelevich and wrote the code in Java. Much problem was with finding proper zoom and corresponding Bitmap size values. Don't forget that PdfRenderer works only on API 21+.
Fragment with PDF Bitmap fragment_pdf_renderer.xml:
<?xml version="1.0" encoding="utf-8"?>
<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"
android:background="#color/white"
android:orientation="vertical"
tools:context=".PdfRendererFragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:contentDescription="#null" />
</HorizontalScrollView>
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/from_divider_gray"
android:gravity="center_vertical"
android:orientation="horizontal">
<Button
android:id="#+id/previous"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/previous_page"
android:textSize="13sp" />
<Button
android:id="#+id/next"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/next_page"
android:textSize="13sp" />
<ImageButton
android:id="#+id/zoomout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:padding="8dp"
android:src="#drawable/ic_zoom_out_black_36dp" />
<ImageButton
android:id="#+id/zoomin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0dp"
android:padding="8dp"
android:src="#drawable/ic_zoom_in_black_36dp" />
</LinearLayout>
</LinearLayout>
The PdfRendererFragment:
/**
* This fragment has a big {#ImageView} that shows PDF pages, and 2
* {#link android.widget.Button}s to move between pages. We use a
* {#link android.graphics.pdf.PdfRenderer} to render PDF pages as
* {#link android.graphics.Bitmap}s.
*/
#RequiresApi(Build.VERSION_CODES.LOLLIPOP)
public class PdfRendererFragment extends Fragment implements View.OnClickListener {
/**
* Key string for saving the state of current page index.
*/
private static final String STATE_CURRENT_PAGE_INDEX = "current_page_index";
/**
* The filename of the PDF.
*/
public String FILENAME;
public String PURCHASE_ID;
public int TICKETS_NUMBER;
/**
* File descriptor of the PDF.
*/
private ParcelFileDescriptor mFileDescriptor;
/**
* {#link android.graphics.pdf.PdfRenderer} to render the PDF.
*/
private PdfRenderer mPdfRenderer;
/**
* Page that is currently shown on the screen.
*/
private PdfRenderer.Page mCurrentPage;
/**
* {#link android.widget.ImageView} that shows a PDF page as a {#link android.graphics.Bitmap}
*/
private ImageView mImageView;
/**
* {#link android.widget.Button} to move to the previous page.
*/
private Button mButtonPrevious;
private ImageView mButtonZoomin;
private ImageView mButtonZoomout;
private Button mButtonNext;
private float currentZoomLevel = 12;
/**
* PDF page index
*/
private int mPageIndex;
public PdfRendererFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_pdf_renderer, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Retain view references.
mImageView = (ImageView) view.findViewById(R.id.image);
mButtonPrevious = (Button) view.findViewById(R.id.previous);
mButtonNext = (Button) view.findViewById(R.id.next);
mButtonZoomin = view.findViewById(R.id.zoomin);
mButtonZoomout = view.findViewById(R.id.zoomout);
// Bind events.
mButtonPrevious.setOnClickListener(this);
mButtonNext.setOnClickListener(this);
mButtonZoomin.setOnClickListener(this);
mButtonZoomout.setOnClickListener(this);
mPageIndex = 0;
// If there is a savedInstanceState (screen orientations, etc.), we restore the page index.
if (null != savedInstanceState) {
mPageIndex = savedInstanceState.getInt(STATE_CURRENT_PAGE_INDEX, 0);
}
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FILENAME = getActivity().getIntent().getExtras().getString("pdfFilename");
TICKETS_NUMBER = getActivity().getIntent().getExtras().getInt("tickets_number");
PURCHASE_ID = getActivity().getIntent().getExtras().getString("purchaseGuid");
}
#Override
public void onStart() {
super.onStart();
try {
openRenderer(getActivity());
showPage(mPageIndex);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), getString(R.string.ticket_file_not_found, FILENAME), Toast.LENGTH_SHORT).show();
App app = (App) getActivity().getApplicationContext();
TicketUtil.downloadTicket(app, PURCHASE_ID);
getActivity().finish();
}
}
#Override
public void onStop() {
try {
closeRenderer();
} catch (IOException e) {
e.printStackTrace();
}
super.onStop();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mCurrentPage) {
outState.putInt(STATE_CURRENT_PAGE_INDEX, mCurrentPage.getIndex());
}
}
/**
* Sets up a {#link android.graphics.pdf.PdfRenderer} and related resources.
*/
private void openRenderer(Context context) throws IOException {
// In this sample, we read a PDF from the assets directory.
File file = TicketUtil.getTicketFile(context, PURCHASE_ID);
if (!file.exists()) {
// Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
// the cache directory.
InputStream asset = context.getAssets().open(FILENAME);
FileOutputStream output = new FileOutputStream(file);
final byte[] buffer = new byte[1024];
int size;
while ((size = asset.read(buffer)) != -1) {
output.write(buffer, 0, size);
}
asset.close();
output.close();
}
mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
// This is the PdfRenderer we use to render the PDF.
if (mFileDescriptor != null) {
mPdfRenderer = new PdfRenderer(mFileDescriptor);
}
}
/**
* Closes the {#link android.graphics.pdf.PdfRenderer} and related resources.
*
* #throws java.io.IOException When the PDF file cannot be closed.
*/
private void closeRenderer() throws IOException {
if (null != mCurrentPage) {
mCurrentPage.close();
mCurrentPage = null;
}
if (null != mPdfRenderer) {
mPdfRenderer.close();
}
if (null != mFileDescriptor) {
mFileDescriptor.close();
}
}
/**
* Zoom level for zoom matrix depends on screen density (dpiAdjustedZoomLevel), but width and height of bitmap depends only on pixel size and don't depend on DPI
* Shows the specified page of PDF to the screen.
*
* #param index The page index.
*/
private void showPage(int index) {
if (mPdfRenderer.getPageCount() <= index) {
return;
}
// Make sure to close the current page before opening another one.
if (null != mCurrentPage) {
mCurrentPage.close();
}
// Use `openPage` to open a specific page in PDF.
mCurrentPage = mPdfRenderer.openPage(index);
// Important: the destination bitmap must be ARGB (not RGB).
int newWidth = (int) (getResources().getDisplayMetrics().widthPixels * mCurrentPage.getWidth() / 72 * currentZoomLevel / 40);
int newHeight = (int) (getResources().getDisplayMetrics().heightPixels * mCurrentPage.getHeight() / 72 * currentZoomLevel / 64);
Bitmap bitmap = Bitmap.createBitmap(
newWidth,
newHeight,
Bitmap.Config.ARGB_8888);
Matrix matrix = new Matrix();
float dpiAdjustedZoomLevel = currentZoomLevel * DisplayMetrics.DENSITY_MEDIUM / getResources().getDisplayMetrics().densityDpi;
matrix.setScale(dpiAdjustedZoomLevel, dpiAdjustedZoomLevel);
// Toast.makeText(getActivity(), "width " + String.valueOf(newWidth) + " widthPixels " + getResources().getDisplayMetrics().widthPixels, Toast.LENGTH_LONG).show();
// matrix.postTranslate(-rect.left/mCurrentPage.getWidth(), -rect.top/mCurrentPage.getHeight());
// Here, we render the page onto the Bitmap.
// To render a portion of the page, use the second and third parameter. Pass nulls to get
// the default result.
// Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
mCurrentPage.render(bitmap, null, matrix, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
// We are ready to show the Bitmap to user.
mImageView.setImageBitmap(bitmap);
updateUi();
}
/**
* Updates the state of 2 control buttons in response to the current page index.
*/
private void updateUi() {
int index = mCurrentPage.getIndex();
int pageCount = mPdfRenderer.getPageCount();
if (pageCount == 1) {
mButtonPrevious.setVisibility(View.GONE);
mButtonNext.setVisibility(View.GONE);
} else {
mButtonPrevious.setEnabled(0 != index);
mButtonNext.setEnabled(index + 1 < pageCount);
}
if (currentZoomLevel == 2) {
mButtonZoomout.setActivated(false);
} else {
mButtonZoomout.setActivated(true);
}
}
/**
* Gets the number of pages in the PDF. This method is marked as public for testing.
*
* #return The number of pages.
*/
public int getPageCount() {
return mPdfRenderer.getPageCount();
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.previous: {
// Move to the previous page
currentZoomLevel = 12;
showPage(mCurrentPage.getIndex() - 1);
break;
}
case R.id.next: {
// Move to the next page
currentZoomLevel = 12;
showPage(mCurrentPage.getIndex() + 1);
break;
}
case R.id.zoomout: {
// Move to the next page
--currentZoomLevel;
showPage(mCurrentPage.getIndex());
break;
}
case R.id.zoomin: {
// Move to the next page
++currentZoomLevel;
showPage(mCurrentPage.getIndex());
break;
}
}
}
}
Bring your attention to the fact that zoom level depends on your screen density, but width and height of Bitmap (it is in pixels) depend only on your zoom level. Also, you need to tweak your sizes so that at default zoom (for me it was pdf rendered full screen and value was 12) you PDF bitmap takes no more and no less than needed in your View.
int newWidth = (int) (getResources().getDisplayMetrics().widthPixels * mCurrentPage.getWidth() / 72 * currentZoomLevel / 40);
int newHeight = (int) (getResources().getDisplayMetrics().heightPixels * mCurrentPage.getHeight() / 72 * currentZoomLevel / 64);
Bitmap bitmap = Bitmap.createBitmap(
newWidth,
newHeight,
Bitmap.Config.ARGB_8888);
I found out that zoom 12 fits my screen and 40 and 64 are coefficents that make Bitmap proper size.
mCurrentPage.getWidth() returns width in Postscript points, where each pt is 1/72 inch.
72 (DPI) is the default PDF resolution.
PS. If you need simultaneous vertical and horizontal scroll Scrollview vertical and horizontal in android
The solution i used when confronted to this situation was :
Load the pdfRenderer page in a ImageView
Put my ImageView in a ScrollView (tadam scroll managed), and this ScrollView in a FrameLayout
Add two buttons (outside the scroll view) to manage zoom in and out (each button triggering a scale animation on my ImageView). You could also manage it with a gesture detector but i had hard time with the scrolling behaviour when doing so
Add two buttons to manage page changes (still outside the ScrollView)
For a nice effect i added FadeIn/FadeOut animations on my buttons, FadeIn triggering on OnTouchEvents (if no animation is playing), and FadeOut triggering when FadeIn animation is over
Hope i helped, aks me if you need more detailed informations, but you should know where to start now
Here is a code sample (wich do not inclue page navigation etc, but only zoom behaviour and scrolling, as the rest being in the google code sample you linked)
Code :
C# (but very easy to convert into Java)
private Button _zoomInButton;
private Button _zoomOutButton;
private ImageView _pdfViewContainer;
private float _currentZoomLevel;
private float _zoomFactor;
private float _maxZoomLevel;
private float _minZoomLevel;
private void Init(View view) // the content of this method must go in your OnViewCreated method, here the view being the frameLayout you will find in xml
{
_zoomInButton = view.FindViewById<Button>(Resource.Id.PdfZoomInButton);
_zoomOutButton = view.FindViewById<Button>(Resource.Id.PdfZoomOutButton);
_pdfViewContainer = view.FindViewById<ImageView>(Resource.Id.PdfViewContainer);
_zoomInButton.Click += delegate { ZoomIn(); }; //for you (in Java) this must looks like setOnClickListener(this); and in the onClick metghod you just have to add a case for R.id.PdfZoomInButton containing a call to ZoomIn();
_zoomOutButton.Click += delegate { ZoomOut(); };
_minZoomLevel = 0.9f;
_maxZoomLevel = 1.2f;
_zoomFactor = 0.1f;
}
private void ZoomIn()
{
if (_currentZoomLevel + _zoomFactor < _maxZoomLevel)
{
ScaleAnimation scale = new ScaleAnimation(_currentZoomLevel, _currentZoomLevel + _zoomFactor, _currentZoomLevel, _currentZoomLevel + _zoomFactor, Dimension.RelativeToSelf, 0.5f, Dimension.RelativeToSelf, 0.5f);
scale.Duration = 50;
scale.FillAfter = true;
_pdfViewContainer.StartAnimation(scale);
_currentZoomLevel += _zoomFactor;
}
}
private void ZoomOut()
{
if (_currentZoomLevel - _zoomFactor > _minZoomLevel)
{
ScaleAnimation scale = new ScaleAnimation(_currentZoomLevel, _currentZoomLevel - _zoomFactor, _currentZoomLevel, _currentZoomLevel - _zoomFactor, Dimension.RelativeToSelf, 0.5f, Dimension.RelativeToSelf, 0.5f);
scale.Duration = 50;
scale.FillAfter = true;
_pdfViewContainer.StartAnimation(scale);
_currentZoomLevel -= _zoomFactor;
}
}
XMl
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/PdfContainer">
<ScrollView xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:id="#+id/PdfScrollView">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"
android:adjustViewBounds="true"
android:scrollbars="vertical"
android:src="#drawable/mediaIconPDF"
android:id="#+id/PdfViewContainer" />
</ScrollView>
<LinearLayout
android:id="#+id/PdfRightLayout"
android:layout_gravity="right"
android:orientation="vertical"
android:gravity="center"
android:layout_width="50dp"
android:layout_height="match_parent"
android:weightSum="1">
<Button
android:id="#+id/PdfZoomInButton"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="+" />
<space
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.2" />
<Button
android:id="#+id/PdfZoomOutButton"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="-" />
</LinearLayout>
<LinearLayout
android:id="#+id/PdfBottomLayout"
android:layout_gravity="bottom"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/vogofTransparentGrey"
android:weightSum="1">
<Button
android:id="#+id/PdfPreviousPage"
android:layout_width="0dp"
android:layout_weight="0.15"
android:layout_height="match_parent"
android:text="Prev" />
<TextView
android:id="#+id/PdfCurrentPageLabel"
android:layout_width="0dp"
android:layout_weight="0.7"
android:gravity="center"
android:layout_height="match_parent"
/>
<Button
android:id="#+id/PdfNextPage"
android:layout_width="0dp"
android:layout_weight="0.15"
android:layout_height="match_parent"
android:text="Next" />
</LinearLayout>
</FrameLayout>
With this, some time to understand it and little efforts you should be able to get the desired result. Have a nice day
I found a nicer answer here: PdfRendering zoom on page linked by CommonsWare: https://github.com/commonsguy/cw-omnibus/tree/v8.8/PDF/PdfRenderer . So based on soshial's answer, you have pinch zoom and can get rid of the zoom buttons and the constants:
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
....
private void showPage(int index) {
if (mPdfRenderer.getPageCount() <= index) {
return;
}
// Make sure to close the current page before opening another one.
if (null != mCurrentPage) {
mCurrentPage.close();
}
// Use `openPage` to open a specific page in PDF.
mCurrentPage = mPdfRenderer.openPage(index);
if(mBitmap==null) {
// Important: the destination bitmap must be ARGB (not RGB).
int newWidth = (int) (getResources().getDisplayMetrics().densityDpi * mCurrentPage.getWidth() / 72);
int newHeight = (int) (getResources().getDisplayMetrics().densityDpi * mCurrentPage.getHeight() / 72);
mBitmap = Bitmap.createBitmap(
newWidth,
newHeight,
Bitmap.Config.ARGB_8888);
}
mBitmap.eraseColor(0xFFFFFFFF);
mCurrentPage.render(mBitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
// We are ready to show the Bitmap to user.
mSubsamplingImageView.resetScaleAndCenter();
mSubsamplingImageView.setImage(ImageSource.cachedBitmap(mBitmap));
updateUi();
}
I also added bitmap recycle:
/**
* Closes the {#link android.graphics.pdf.PdfRenderer} and related resources.
*
* #throws java.io.IOException When the PDF file cannot be closed.
*/
private void closeRenderer() throws IOException {
if (null != mCurrentPage) {
mCurrentPage.close();
mCurrentPage = null;
}
if (null != mPdfRenderer) {
mPdfRenderer.close();
}
if (null != mFileDescriptor) {
mFileDescriptor.close();
}
if(mBitmap!=null)
{
mBitmap.recycle();
mBitmap = null;
}
}
And in the xml, instead of ImageView:
<com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
android:id="#+id/report_viewer_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Starting with this solution : https://stackoverflow.com/a/46002017/5049286 I found a good way to avoid the initial zoom coefficient and the others fixed coefficients, only changed this method :
private void showPage(int index) {
if (mPdfRenderer.getPageCount() <= index) {
return;
}
if (null != mCurrentPage) {
mCurrentPage.close();
}
mCurrentPage = mPdfRenderer.openPage(index);
int newWidth = (int) (mVerticalScrollView.getWidth() *
currentZoomLevel);
int newHeight = (int) (newWidth *
((float)mCurrentPage.getHeight()/(float)mCurrentPage.getWidth()));
Bitmap bitmap = Bitmap.createBitmap(
newWidth,
newHeight,
Bitmap.Config.ARGB_8888);
mCurrentPage.render(bitmap, null, null,
PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
mImageView.setImageBitmap(bitmap);
updateUi();
}
With this solution currentZoomLevel starts from 1.0f to xxx ( you decide a limit ) and the rendered image at zoom 1.0f fit into the scrollview and the proportions are maintained...

Showing software keyboard with GLSurfaceView (and getting input from it)

I want to get user input for my OpenGL ES 2.0 application, but there are 2 problems:
1) How can I bring the software keyboard to the front of my app?
2) How can I catch input from it?
I tried to use this:
//OpenGL ES 2.0 view class
public class OGLES2View extends GLSurfaceView
{
private static final int OGLES_VERSION = 2;
private static Handler softKeyboardHandler;
private final static int SHOW_IME_KEYBOARD = 0;
private final static int HIDE_IME_KEYBOARD = 1;
private static EditText textEdit;
private static InputMethodManager imm;
private void setSoftKeyboardHandler()
{
softKeyboardHandler = new Handler()
{
public void handleMessage(Message msg)
{
switch(msg.what)
{
case SHOW_IME_KEYBOARD:
textEdit.requestFocus();
imm.showSoftInput(textEdit,inputMethodManager.SHOW_IMPLICIT);//Nothing happens
Log.i("GLVIEW","SHOW KEYBOARD");
break;
case HIDE_IME_KEYBOARD:
imm.hideSoftInput(textEdit, 0);
Log.i("GLVIEW","HIDE KEYBOARD");
break;
default:
break;
}
}
};
}
public OGLES2View(Context context)
{
super(context);
textEdit = new EditText(context);
setEGLContextClientVersion(OGLES_VERSION);
setRenderer(new OGLES2Renderer());
imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
setSoftKeyboardHandler();
}
public static void showIMEKeyboard()
{
softKeyboardHandler.sendEmptyMessage(SHOW_IME_KEYBOARD);
}
public static void hideIMEKeyboard()
{
softKeyboardHandler.sendEmptyMessage(HIDE_IME_KEYBOARD);
}
//In main activity class
private GLSurfaceView ogles2SurfaceView = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//...
ogles2SurfaceView = new OGLES2View(this);
setContentView(ogles2SurfaceView);
}
Handler gets messages, but I got no software keyboard.
To catch text, I wrote some class:
public class TextInputWatcher implements TextWatcher
and:
textEdit.addTextChangedListener(/*TextInputWatcher instance*/);
Or extend a TextEdit so it catches inputed text on back or enter key.
P.S. I got a tablet - transformer, so there is a hardware keyboard attached. I tried with it and without, but no difference. So bonus question - if there is a hardware keyboard will it prevent a software keyboard from popping up and how can input be gotten from it then?.
Show keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Hide keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
I made 2d game. I think you have the same problem like me before. Try this:
class DrawingPanel extends SurfaceView implements SurfaceHolder.Callback {
private static DrawThread _thread;
public DrawingPanel(Context context, AttributeSet attrs) {
super(context, attrs);
getHolder().addCallback(this);
_thread = new DrawThread(getHolder(), this);
}
....
Layout 'gameview':
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- YOUR SURFACE -->
<com.yourcompany.DrawingPanel android:id="#+id/surfaceView" android:layout_width="fill_parent"
android:layout_height="fill_parent"></com.yourcompany.DrawingPanel>
<!-- YOUR BUTTONS -->
<RelativeLayout android:id="#+id/controlPanel" android:layout_width="fill_parent" android:orientation="horizontal"
android:layout_height="fill_parent" >
<RelativeLayout android:layout_width="50px" android:orientation="vertical"
android:layout_height="fill_parent" android:gravity="center_vertical" android:layout_alignParentLeft="true">
<Button android:id="#+id/leftButton" android:layout_width="wrap_content"
android:layout_height="50px" android:background="#xml/button_left_state"/>
<Button android:id="#+id/upgradeButton" android:layout_width="wrap_content"
android:layout_below="#id/leftButton"
android:layout_height="50px" android:background="#xml/button_upgrade_state"/>
</RelativeLayout>
</RelativeLayout>
</FrameLayout>
Then you should set content in game activity like below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameview);
...
Hope It helps you.

Categories