Skip to content

Instantly share code, notes, and snippets.

@barron9
Created January 28, 2019 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barron9/3f90c230eb51972643b63273561bfc0f to your computer and use it in GitHub Desktop.
Save barron9/3f90c230eb51972643b63273561bfc0f to your computer and use it in GitHub Desktop.
photovieweractivity.java
package com.generalmobile.app.gmfilemanager.photoviewer;
import android.Manifest;
import android.animation.Animator;
import android.app.WallpaperManager;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.INotificationSideChannel;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.provider.DocumentFile;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.webkit.MimeTypeMap;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.generalmobile.app.gmfilemanager.BuildConfig;
import com.generalmobile.app.gmfilemanager.GmFileManagerApplication;
import com.generalmobile.app.gmfilemanager.R;
import com.generalmobile.app.gmfilemanager.adapters.ExifAdapter;
import com.generalmobile.app.gmfilemanager.adapters.PhotoThumbAdapter;
import com.generalmobile.app.gmfilemanager.adapters.PhotoViewerAdapter;
import com.generalmobile.app.gmfilemanager.core.AnalyticsConstants;
import com.generalmobile.app.gmfilemanager.core.DataSourceType;
import com.generalmobile.app.gmfilemanager.core.PhotoViewer;
import com.generalmobile.app.gmfilemanager.core.listeners.OnItemClickListener;
import com.generalmobile.app.gmfilemanager.datasources.LocalDataSource;
import com.generalmobile.app.gmfilemanager.db.Tag;
import com.generalmobile.app.gmfilemanager.explorer.ExplorerActivity;
import com.generalmobile.app.gmfilemanager.models.ExifModel;
import com.generalmobile.app.gmfilemanager.models.FileItem;
import com.generalmobile.app.gmfilemanager.utils.ColorUtils;
import com.generalmobile.app.gmfilemanager.utils.ConvertUtils;
import com.generalmobile.app.gmfilemanager.utils.FileDateUtils;
import com.generalmobile.app.gmfilemanager.utils.FileUtils;
import com.generalmobile.app.gmfilemanager.utils.Icons;
import com.generalmobile.app.gmfilemanager.utils.ImageUtils;
import com.generalmobile.app.gmfilemanager.utils.MimeTypes;
import com.github.piasy.biv.BigImageViewer;
import com.github.piasy.biv.loader.glide.GlideImageLoader;
import com.google.gson.Gson;
import com.pixplicity.easyprefs.library.Prefs;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnLongClick;
import timber.log.Timber;
import static com.generalmobile.app.gmfilemanager.utils.BaseActivity.FILE_PERMISSION_CODE;
public class PhotoViewerActivity extends AppCompatActivity implements OnItemClickListener, ViewPager.OnPageChangeListener, IPhotoViewerView, View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private static final int REQUEST_SD_STORAGE_PERMISSION = 1903;
private static final int WALLPAPER_REQUEST_CODE = 1903;
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.appbarlayout)
AppBarLayout appbarlayout;
@BindView(R.id.pager)
ViewPager pager;
@BindView(R.id.thumbnails)
RecyclerView thumbnails;
@BindView(R.id.deleteBottom)
ImageButton deleteBottom;
@BindView(R.id.shareBottom)
ImageButton shareBottom;
@BindView(R.id.infoBottom)
ImageButton infoBottom;
@BindView(R.id.bottomNavigation)
FrameLayout bottomNavigation;
@BindView(R.id.bottomBar)
LinearLayout bottomBar;
@BindView(R.id.appbarlayout)
AppBarLayout appbar;
@BindView(R.id.activity_photo_viewer)
FrameLayout activityPhotoViewer;
@BindView(R.id.imageTitleTextView)
TextView imageTitleTextView;
@BindView(R.id.imageDateTextView)
TextView imageDateTextView;
@BindView(R.id.photoTagLayout)
LinearLayout tagLayout;
@BindView(R.id.photoTagOpenerLayout)
LinearLayout tagOpenLayout;
@BindView(R.id.tagLayoutIcon)
ImageView tagLayoutIcon;
private PhotoViewerAdapter photoViewerAdapter;
private PhotoThumbAdapter photoThumbAdapter;
private LinearLayoutManager linearLayoutManager;
private IPhotoViewerPresenter presenter;
private int currentPosition;
private boolean bottomBarVisible;
private TextView size;
private Paint paint;
public int c=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
BigImageViewer.initialize(GlideImageLoader.with(getApplicationContext()));
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_viewer);
paint = new Paint();
ButterKnife.bind(this);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_back_white_24dp);
}
hideThumbnails();
checkPermissions();
}
public void hideshow(View v){
}
@Override
public void onClick(View v) {
hideshow(v);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private void checkPermissions() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, FILE_PERMISSION_CODE);
} else {
presenter = new PhotoViewerPresenter(this);
presenter.getImages(getIntent());
bottomBarVisible = true;
initBottomNavigation();
}
}
private void initBottomNavigation() {
presenter.checkPathForBottomNavigation(getIntent());
infoBottom.setOnClickListener(this);
shareBottom.setOnClickListener(this);
deleteBottom.setOnClickListener(this);
tagLayout.setOnClickListener(this);
tagOpenLayout.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return presenter != null && presenter.createMenu(menu, getIntent());
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
super.onBackPressed();
break;
case R.id.saveAs:
GmFileManagerApplication.getInstance().trackEvent(AnalyticsConstants.SCREEN_EVENT, "PhotoViewerOpenWith", "fotoğraf görüntüleyici birlikte aç");
if (photoViewerAdapter != null) {
FileItem fileItem = photoViewerAdapter.getImage(currentPosition);
if (fileItem != null) {
showFile(new File(fileItem.getPath()), Intent.ACTION_ATTACH_DATA);
}
}
break;
case R.id.imageInfo:
GmFileManagerApplication.getInstance().trackEvent(AnalyticsConstants.SCREEN_EVENT, "PhotoViewerInformation", "fotoğraf görüntüleyici özellikler");
information();
break;
case R.id.wallpaper:
GmFileManagerApplication.getInstance().trackEvent(AnalyticsConstants.SCREEN_EVENT, "PhotoViewerSetAsWallpaper", "fotoğraf görüntüleyici arkaplan yap");
setAsWallpaper(photoViewerAdapter.getImage(currentPosition));
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void setAsWallpaper(FileItem fileItem) {
try {
if (fileItem != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent intent = new Intent(WallpaperManager.ACTION_CROP_AND_SET_WALLPAPER);
intent.setFlags(1);
intent.setData(FileUtils.getImageContentUri(this, new File(fileItem.getPath())));
List<ResolveInfo> pkgAppsList = this.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_RESOLVED_FILTER);
if (pkgAppsList != null && !pkgAppsList.isEmpty()) {
ResolveInfo info = pkgAppsList.get(0);
String packageName = info.activityInfo.packageName;
String className = info.activityInfo.name;
intent.setClassName(packageName, className);
startActivityForResult(intent, WALLPAPER_REQUEST_CODE);
} else {
showFile(new File(fileItem.getPath()), Intent.ACTION_ATTACH_DATA);
}
} else {
showFile(new File(fileItem.getPath()), Intent.ACTION_ATTACH_DATA);
}
}
} catch (ActivityNotFoundException e) {
Timber.e(e);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case WALLPAPER_REQUEST_CODE:
if (resultCode == -1) {
Toast.makeText(this, R.string.wallpaper_set, Toast.LENGTH_SHORT).show();
}
break;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case FILE_PERMISSION_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
checkPermissions();
} else {
Toast.makeText(this, R.string.no_permission_text, Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (Exception e) {
Timber.d(e);
}
finish();
}
}).start();
}
break;
}
}
@Override
public void onItemClick(int position, View v) {
c=c+1;
if((c/2)*2 == c){hideBottomNavigationBar();}else{showBottomNavigationBar();}
switch (v.getId()) {
case R.id.thumb:
case R.id.gifViewThumb:
pager.setCurrentItem(position, false);
//hideBottomNavigationBar();
break;
case R.id.image:
break;
case R.id.photoLayout:
hideBottomNavigationBar();
break;
case R.id.bigImage:
break;
case R.id.gifView:
presenter.showChangeViewVisibilty();
break;
case R.id.pager:
break;
}
if (linearLayoutManager != null) {
linearLayoutManager.scrollToPositionWithOffset(position, (getScreenWidth() / 2) - 50);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// linearLayoutManager.scrollToPosition(position);
}
@Override
public void onPageSelected(int position) {
if (linearLayoutManager != null) {
linearLayoutManager.scrollToPositionWithOffset(position, (getScreenWidth() / 2) - 50);
}
changeTitle(position);
setCurrentPosition(position);
if (presenter.getTagVisibity())
checkTags();
}
private void changeTitle(int position) {
FileItem item = photoViewerAdapter.getImage(position);
if (item != null) {
File file = new File(item.getPath());
imageTitleTextView.setText(FileDateUtils.getDate(Locale.getDefault(), file.lastModified()));
imageDateTextView.setText(FileDateUtils.getTime(Locale.getDefault(), file.lastModified()));
}
}
public int getScreenWidth() {
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
return size.x;
}
public void showFile(File file, String action) {
MimeTypeMap myMime = MimeTypeMap.getSingleton();
String mimeType = myMime.getMimeTypeFromExtension(FileUtils.getExtension(file.getPath()).replace(".", ""));
Uri path = Uri.fromFile(file);
try {
path = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
} catch (Exception e) {
Timber.d(e);
}
if (FileUtils.isOnExtSdCard(file)) {
DocumentFile documentFile = FileUtils.getDocumentFile(file, false);
if (documentFile != null)
path = documentFile.getUri();
}
Intent intent = new Intent(action);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, mimeType);
if (action.equals(Intent.ACTION_ATTACH_DATA)) {
intent.putExtra("mimeType", mimeType);
}
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, path, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
try {
startActivity(intent);
} catch (Exception e) {
Timber.e(e);
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void hideThumbnails() {
if (getIntent().getAction().equals(Intent.ACTION_VIEW)) {
thumbnails.setVisibility(View.GONE);
}
}
@Override
public void showImages(List<FileItem> imageList, int position) {
photoViewerAdapter = new PhotoViewerAdapter(this);
photoViewerAdapter.setImageList(imageList);
photoViewerAdapter.setOnItemClickListener(this);
pager.addOnPageChangeListener(this);
pager.setAdapter(photoViewerAdapter);
pager.setCurrentItem(position, false);
changeTitle(position);
setCurrentPosition(position);
if (presenter.getTagVisibity())
checkTags();
}
public void setCurrentPosition(int currentPosition) {
if (photoThumbAdapter != null) {
photoThumbAdapter.setPosition(currentPosition);
}
this.currentPosition = currentPosition;
}
@Override
public void information() {
if (photoViewerAdapter != null) {
final MaterialDialog dialog = new MaterialDialog.Builder(this).customView(R.layout.dialog_file_information, false).positiveText(R.string.ok).title(R.string.information).build();
View view = dialog.getCustomView();
if (view != null) {
TextView name = (TextView) view.findViewById(R.id.fileInformationName);
TextView type = (TextView) view.findViewById(R.id.fileInformationType);
size = (TextView) view.findViewById(R.id.fileInformationSize);
TextView path = (TextView) view.findViewById(R.id.fileInformationPath);
TextView updateDate = (TextView) view.findViewById(R.id.fileInformationUpdateDate);
TableRow pathRow = (TableRow) view.findViewById(R.id.pathRow);
TableRow resolutionRow = (TableRow) view.findViewById(R.id.resolutionRow);
TextView resolution = (TextView) view.findViewById(R.id.resolutionText);
ImageView image = (ImageView) view.findViewById(R.id.dialogImage);
LinearLayout exifRow = (LinearLayout) view.findViewById(R.id.exifRow);
RecyclerView exifRecyclerView = (RecyclerView) view.findViewById(R.id.exifRecyclerView);
TableRow sizeRow = (TableRow) view.findViewById(R.id.sizeRow);
List<ExifModel> exifDataset = new ArrayList<>();
final FileItem file = photoViewerAdapter.getImage(currentPosition);
if (file != null) {
final File currentFile = new File(file.getPath());
String sizeString = "";
if (file.isDirectory()) {
if (file.getDataSource() == DataSourceType.LOCAL_DATASOURCE) {
new CalculateSize(currentFile).execute();
sizeString = String.valueOf(file.getSize()) + " " + getString(R.string.item) + " " + getString(R.string.calculating);
} else {
sizeRow.setVisibility(View.GONE);
}
type.setText(R.string.folder);
image.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_folder_black_24dp));
} else {
sizeString = ConvertUtils.readableFileSize(currentFile.length());
type.setText(FileUtils.getExtension(file.getPath()));
if (Icons.isPicture(file.getPath())) {
Bitmap bitsat;
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inJustDecodeBounds = true;
options.inSampleSize = ImageUtils.calculateInSampleSize(options, 50, 50);
options.inJustDecodeBounds = false;
Bitmap bit;
bit = BitmapFactory.decodeFile(file.getPath(), options);
bitsat = bit;
} catch (Exception e) {
bitsat = BitmapFactory.decodeResource(getResources(), R.drawable.ic_insert_drive_file_white_24dp);
Timber.e(e);
}
image.setImageBitmap(bitsat);
} else {
image.setImageDrawable(getResources().getDrawable(R.drawable.ic_insert_drive_file_white_24dp));
}
}
if (file.getHeight() != null && file.getWidth() != null) {
resolutionRow.setVisibility(View.VISIBLE);
resolution.setText(file.getHeight() + " x " + file.getWidth());
}
name.setText(currentFile.getName());
size.setText(sizeString);
path.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(PhotoViewerActivity.this, ExplorerActivity.class);
intent.putExtra("path", currentFile.getPath().replace(currentFile.getName(), ""));
startActivity(intent);
}
});
String mimeType = MimeTypes.getMimeType(new File(file.getPath()));
if (mimeType != null && (mimeType.contains("image") && !mimeType.contains("gif"))) {
ExifInterface exifInterface = null;
try {
exifInterface = new ExifInterface(file.getPath());
for (Field field : ExifInterface.class.getDeclaredFields()) {
if (field.getType() == String.class) {
try {
String fieldName = String.valueOf(field.get(exifInterface));
exifDataset.add(new ExifModel(camelCase(field.getName().replaceFirst("TAG_", "").replace("_", " ").toLowerCase(Locale.ENGLISH)), exifInterface.getAttribute(fieldName)));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
exifRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager exifLayoutManager = new LinearLayoutManager(this);
exifRecyclerView.setLayoutManager(exifLayoutManager);
RecyclerView.Adapter exifAdapter = new ExifAdapter(exifDataset);
exifRecyclerView.setAdapter(exifAdapter);
} catch (IOException e) {
e.printStackTrace();
exifRow.setVisibility(View.GONE);
exifRecyclerView.setVisibility(View.GONE);
}
} else {
exifRow.setVisibility(View.GONE);
exifRecyclerView.setVisibility(View.GONE);
}
if (currentFile.getPath().startsWith(getExternalCacheDir().getPath())) {
pathRow.setVisibility(View.GONE);
} else {
path.setText(currentFile.getParent().substring(currentFile.getParent().lastIndexOf('/') + 1));
}
updateDate.setText(FileDateUtils.getShortDate(currentFile.lastModified()));
dialog.show();
}
}
}
}
@Override
public void delete() {
GmFileManagerApplication.getInstance().trackEvent(AnalyticsConstants.SCREEN_EVENT, "PhotoViewerDelete", "fotoğraf görüntüleyici silme tuşuna basıldı");
if (photoViewerAdapter != null) {
final FileItem image = photoViewerAdapter.getImage(currentPosition);
MaterialDialog.Builder builder = new MaterialDialog.Builder(this).title(R.string.delete).positiveText(R.string.delete).onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
Prefs.putBoolean("permDelete", dialog.isPromptCheckBoxChecked());
presenter.deleteFiles(image, Prefs.getBoolean("permDelete", dialog.isPromptCheckBoxChecked()));
if (getIntent().getAction().equals(Intent.ACTION_VIEW)) {
if (Build.VERSION.SDK_INT >= 21)
finishAndRemoveTask();
else
finish();
}
}
}).negativeText(R.string.cancel);
if (isCloudFile() || isTrashBin()) {
builder.content(R.string.permanent_delete);
}
if (!isCloudFile() && !isTrashBin()) {
builder.checkBoxPrompt(getString(R.string.permanent_delete), false, this);
}
MaterialDialog dialog = builder.build();
dialog.setPromptCheckBoxChecked(Prefs.getBoolean("permDelete", false));
dialog.show();
}
}
private boolean isCloudFile() {
if (getIntent().getAction().equals(PhotoViewer.ACTION.CLOUD_IMAGE_ACTION)) {
return true;
}
return false;
}
private boolean isTrashBin() {
if (photoViewerAdapter != null) {
FileItem item = photoViewerAdapter.getImage(currentPosition);
if (item != null) {
LocalDataSource localDataSource = new LocalDataSource();
File trash = new File(localDataSource.getRoots().get(0).getPath() + "/.trash");
if (trash.exists()) {
List<File> files = FileUtils.getListFiles(trash);
for (File file : files) {
if (file.getPath().equals(item.getPath())) {
return true;
}
}
return false;
}
}
}
return false;
}
private void deleteFromPager() {
photoViewerAdapter.removeView(pager, currentPosition);
currentPosition--;
currentPosition = currentPosition < 0 ? 0 : currentPosition;
setCurrentPosition(currentPosition);
pager.setCurrentItem(currentPosition, false);
if (photoViewerAdapter.getCount() == 0) {
finish();
}
}
@Override
public void postDelete() {
if (photoThumbAdapter != null) {
photoThumbAdapter.notifyItemRemoved(currentPosition);
deleteFromPager();
}
}
@Override
public void deleteIntentStart(FileItem cloudFile) {
Intent intent = new Intent(this, ExplorerActivity.class);
intent.putExtra("deleteFile", new Gson().toJson(cloudFile));
intent.putExtra("datasource", cloudFile.getDataSource());
startActivity(intent);
}
@Override
public void hideBottomNavigationBar() {
bottomBar.setVisibility(View.GONE);
appbar.setVisibility(View.GONE);
bottomBarVisible = false;
}
public void showBottomNavigationBar() {
bottomBar.setVisibility(View.VISIBLE);
appbar.setVisibility(View.VISIBLE);
bottomBarVisible = true;
}
@Override
public void showThumbNails(List<FileItem> imageList, int position) {
if (!getIntent().getAction().equals(Intent.ACTION_VIEW)) {
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
photoThumbAdapter = new PhotoThumbAdapter(this);
photoThumbAdapter.setImageList(imageList);
photoThumbAdapter.setOnItemClickListener(this);
photoThumbAdapter.setPosition(position);
thumbnails.setLayoutManager(linearLayoutManager);
thumbnails.setAdapter(photoThumbAdapter);
linearLayoutManager.scrollToPositionWithOffset(position, (getScreenWidth() / 2) - 50);
}
}
@Override
public void showViews() {
appbarlayout.animate().translationY(0).setInterpolator(new DecelerateInterpolator()).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
appbarlayout.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animator) {
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
}).start();
if (bottomBarVisible) {
bottomBar.animate().translationY(0).setInterpolator(new AccelerateDecelerateInterpolator()).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
bottomBar.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animator) {
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
}).start();
}
}
@Override
public void hideViews() {
appbarlayout.animate().translationY(-appbarlayout.getBottom()).setInterpolator(new AccelerateInterpolator()).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
appbarlayout.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
}).start();
if (bottomBarVisible) {
bottomBar.animate().translationY(bottomBar.getTop()).setInterpolator(new AccelerateDecelerateInterpolator()).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
bottomBar.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
}).start();
}
}
@Override
public void openShareActivity() {
GmFileManagerApplication.getInstance().trackEvent(AnalyticsConstants.SCREEN_EVENT, "PhotoViewerShare", "fotoğraf görüntüleyici paylaş butonu basıldı");
if (photoViewerAdapter != null) {
FileItem item = photoViewerAdapter.getImage(currentPosition);
if (item != null) {
Intent shareIntent;
ArrayList<Uri> uriList = new ArrayList<>();
if (FileUtils.isOnExtSdCard(new File(item.getPath()))) {
String uri = Prefs.getString("URI", "");
if (uri != null && uri.isEmpty()) {
requestSdCardPermission();
return;
} else {
DocumentFile documentFile = FileUtils.getDocumentFile(new File(item.getPath()), false);
if (documentFile != null) {
uriList.add(documentFile.getUri());
}
}
} else {
uriList.add(FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", new File(item.getPath())));
}
shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uriList.get(0));
ContentResolver cR = getContentResolver();
String type = cR.getType(uriList.get(0));
shareIntent.setType(type);
startActivity(Intent.createChooser(shareIntent, getString(R.string.share_via)));
}
}
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
}
@Override
public void guideDialogForLEXA() {
final MaterialDialog.Builder x = new MaterialDialog.Builder(PhotoViewerActivity.this);
x.title(R.string.sd_card_permission_title);
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.dialog_sd_permission, null);
x.customView(view, true);
// textView
TextView textView = (TextView) view.findViewById(R.id.description);
textView.setText(R.string.sd_card_permission_text);
((ImageView) view.findViewById(R.id.icon)).setImageResource(R.drawable.sd_operate_step);
x.positiveText(R.string.open);
x.negativeText(R.string.cancel);
x.callback(new MaterialDialog.ButtonCallback() {
@Override
public void onPositive(MaterialDialog materialDialog) {
triggerStorageAccessFramework();
}
@Override
public void onNegative(MaterialDialog materialDialog) {
makeSnackbar(getString(R.string.sd_card_permission_denied));
}
});
final MaterialDialog y = x.build();
y.show();
}
private void triggerStorageAccessFramework() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, REQUEST_SD_STORAGE_PERMISSION);
}
}
@Override
public void makeSnackbar(String message) {
Snackbar.make(activityPhotoViewer, message, Snackbar.LENGTH_LONG).show();
}
@Override
public void hideDeleteButton() {
deleteBottom.setVisibility(View.GONE);
}
@Override
public void requestSdCardPermission() {
runOnUiThread(new Runnable() {
@Override
public void run() {
guideDialogForLEXA();
}
});
}
@Override
public void showImageTags(List<Tag> tagList) {
tagOpenLayout.removeAllViewsInLayout();
// for (Tag tag : tagList) {
// ImageView image = new ImageView((GmFileManagerApplication.getContext()));
// image.setImageDrawable(ContextCompat.getDrawable((GmFileManagerApplication.getContext()), R.drawable.ic_label_black_24dp));
// image.setColorFilter(tag.getTagColor());
//
// LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
// LinearLayout.LayoutParams.WRAP_CONTENT,
// LinearLayout.LayoutParams.WRAP_CONTENT
// );
//
// tagOpenLayout.addView(image, params);
// tagOpenLayout.setVisibility(View.VISIBLE);
// }
int color = ColorUtils.getColorFromAttr(R.attr.gridBackground);
//tagLayoutIcon.setBackgroundColor(color);
/*tagLayoutIcon.setColorFilter(color);*/
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
//122 for the unusable area of layout, padding and other components
int tagPerLineRatio = (int) (((float) metrics.widthPixels) / metrics.density - 32);
int tagsTitleSize = 0;
int tempTitleSize = 0;
LinearLayout currentLayout = null;
for (Tag tag : tagList) {
TextView textView = new TextView((GmFileManagerApplication.getContext()));
textView.setTextColor(Color.BLACK);
Drawable drawable = ContextCompat.getDrawable((GmFileManagerApplication.getContext()), R.drawable.ic_label_outline_black_24dp);
ImageView image = new ImageView(this);
image.setImageDrawable(ContextCompat.getDrawable((GmFileManagerApplication.getContext()), R.drawable.ic_label_black_24dp));
image.setColorFilter(tag.getTagColor());
//background:?gridBackground
//getResources().get
//R.attr.gridBackground
// LinearLayout linearLayout = new LinearLayout(this);
// linearLayout.setOrientation(LinearLayout.HORIZONTAL);
textView.setText(tag.getTagName());
textView.setPadding(4, 4, 4, 4);
textView.setTextSize(12);
textView.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 4, 4, 4);
// linearLayout.addView(image);
// linearLayout.addView(textView);
// linearLayout.setBackgroundColor(color);
// tagOpenLayout.addView(linearLayout, params);
// tagOpenLayout.setVisibility(View.VISIBLE);
tempTitleSize = tagsTitleSize;
//4 is left margin , 24 is image dp , other value is left and right margins , paint is textSize
tagsTitleSize += (4 + 24 + 2 * ((4 / 2) + 0.5) + paint.measureText(tag.getTagName()) + 4 + 4 + 4);
tempTitleSize = tagsTitleSize;
tagsTitleSize += tag.getTagName().length();
if (tagsTitleSize > tagPerLineRatio) {
//tagsTitleSize = tagsTitleSize - tagPerLineRatio;
tagsTitleSize = tagsTitleSize - tempTitleSize;
LinearLayout secondRowLayout = new LinearLayout((GmFileManagerApplication.getContext()));
secondRowLayout.setBackgroundColor(Color.TRANSPARENT);
LinearLayout secRowLay = new LinearLayout((GmFileManagerApplication.getContext()));
secRowLay.setOrientation(LinearLayout.HORIZONTAL);
secRowLay.addView(image);
secRowLay.addView(textView);
secRowLay.setBackgroundColor(color);
secondRowLayout.addView(secRowLay, params);
tagOpenLayout.addView(secondRowLayout, params);
tagOpenLayout.setVisibility(View.VISIBLE);
currentLayout = secondRowLayout;
} else {
if (currentLayout != null) {
LinearLayout innerLayout = new LinearLayout(this);
LinearLayout innLay = new LinearLayout(this);
innLay.setOrientation(LinearLayout.HORIZONTAL);
innLay.addView(image);
innLay.addView(textView);
innLay.setBackgroundColor(color);
innerLayout.addView(innLay, params);
//innerLayout.setLayoutParams(params);
currentLayout.addView(innerLayout);
} else {
LinearLayout rowLayout = new LinearLayout(this);
rowLayout.setBackgroundColor(Color.TRANSPARENT);
LinearLayout rLay = new LinearLayout(this);
rLay.setOrientation(LinearLayout.HORIZONTAL);
rLay.addView(image);
rLay.addView(textView);
rLay.setBackgroundColor(color);
rowLayout.addView(rLay, params);
tagOpenLayout.addView(rowLayout, params);
tagOpenLayout.setVisibility(View.VISIBLE);
currentLayout = rowLayout;
}
}
}
}
@Override
public void onClickPhotoTag() {
if (photoViewerAdapter != null) {
FileItem fileItem = photoViewerAdapter.getImage(currentPosition);
presenter.getFileTags(fileItem.getPath());
}
}
@Override
public void onClickPhotosDetailTag() {
tagOpenLayout.setVisibility(View.GONE);
}
@Override
public void setTagIconVisible() {
int color = ColorUtils.getColorFromAttr(R.attr.gridBackground);
tagLayoutIcon.setColorFilter(color);
tagOpenLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (tagOpenLayout.getVisibility() == View.VISIBLE)
tagOpenLayout.setVisibility(View.GONE);
else
tagOpenLayout.setVisibility(View.VISIBLE);
}
});
tagLayout.setVisibility(View.VISIBLE);
}
public void checkTags() {
tagLayout.setVisibility(View.GONE);
tagOpenLayout.setVisibility(View.GONE);
if (photoViewerAdapter != null) {
FileItem fileItem = photoViewerAdapter.getImage(currentPosition);
if (fileItem != null)
presenter.fileHasTags(fileItem.getPath());
}
}
String camelCase(String str) {
StringBuilder builder = new StringBuilder(str);
boolean isLastSpace = true;
for (int i = 0; i < builder.length(); i++) {
char ch = builder.charAt(i);
if (isLastSpace && ch >= 'a' && ch <= 'z') {
builder.setCharAt(i, (char) (ch + ('A' - 'a')));
isLastSpace = false;
} else if (ch != ' ')
isLastSpace = false;
else
isLastSpace = true;
}
return builder.toString();
}
private class CalculateSize extends AsyncTask<Void, Void, String> {
File file;
long innerSize;
public CalculateSize(File file) {
this.file = file;
}
@Override
protected String doInBackground(Void... voids) {
innerSize = getInnerSize(file);
return getStringSizeLengthFile(innerSize);
}
private long getInnerSize(File currentFile) {
long fileSize = 0;
if (currentFile != null && currentFile.exists())
for (File file : currentFile.listFiles()) {
if (file.isFile())
fileSize += file.length();
else
fileSize += getInnerSize(file);
}
return fileSize;
}
public String getStringSizeLengthFile(long size) {
DecimalFormat df = new DecimalFormat("0.00");
float sizeKb = 1024.0f;
float sizeMo = sizeKb * sizeKb;
float sizeGo = sizeMo * sizeKb;
float sizeTerra = sizeGo * sizeKb;
if (size < sizeMo)
return df.format(size / sizeKb) + " Kb";
else if (size < sizeGo)
return df.format(size / sizeMo) + " Mb";
else if (size < sizeTerra)
return df.format(size / sizeGo) + " Gb";
return "";
}
@Override
protected void onPostExecute(final String aLong) {
super.onPostExecute(aLong);
runOnUiThread(new Runnable() {
@Override
public void run() {
size.setText(size.getText().toString().replace(getString(R.string.calculating), " ") + aLong);
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment