1
0
Fork 0
mirror of https://github.com/gsantner/dandelion synced 2024-11-24 21:32:07 +01:00

Use opoc/Helpers

This commit is contained in:
Gregor Santner 2017-05-29 19:05:37 +02:00
parent b075f020a3
commit 756b31a4ea
No known key found for this signature in database
GPG key ID: 7E83A7834AECB009
16 changed files with 405 additions and 233 deletions

View file

@ -1,3 +1,6 @@
### v0.2.9
- Use opoc/Helpers
### v0.2.7 (2017-05-26) ### v0.2.7 (2017-05-26)
- Small improvements - Small improvements

View file

@ -9,8 +9,8 @@ android {
minSdkVersion 17 minSdkVersion 17
targetSdkVersion 24 targetSdkVersion 24
versionCode 17 versionCode 18
versionName "0.2.7" versionName "0.2.8"
applicationId "com.github.dfa.diaspora_android" applicationId "com.github.dfa.diaspora_android"
resValue 'string', 'app_name', "dandelion*" resValue 'string', 'app_name', "dandelion*"

View file

@ -212,13 +212,13 @@ public class AboutActivity extends ThemedActivity
public void buttonClicked(View view) { public void buttonClicked(View view) {
switch (view.getId()) { switch (view.getId()) {
case R.id.fragment_about__contribute_button: case R.id.fragment_about__contribute_button:
Helpers.openInExternalBrowser(getContext(), getString(R.string.fragment_about__contribute_link)); Helpers.get().openWebpageInExternalBrowser(getString(R.string.fragment_about__contribute_link));
break; break;
case R.id.fragment_about__translate_button: case R.id.fragment_about__translate_button:
Helpers.openInExternalBrowser(getContext(), getString(R.string.fragment_about__translate_link)); Helpers.get().openWebpageInExternalBrowser(getString(R.string.fragment_about__translate_link));
break; break;
case R.id.fragment_about__feedback_button: case R.id.fragment_about__feedback_button:
Helpers.openInExternalBrowser(getContext(), getString(R.string.fragment_About__feedback_link)); Helpers.get().openWebpageInExternalBrowser(getString(R.string.fragment_About__feedback_link));
break; break;
case R.id.fragment_about__spread_the_word_button: case R.id.fragment_about__spread_the_word_button:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
@ -263,14 +263,14 @@ public class AboutActivity extends ThemedActivity
View rootView = inflater.inflate(R.layout.about__fragment_license, container, false); View rootView = inflater.inflate(R.layout.about__fragment_license, container, false);
ButterKnife.bind(this, rootView); ButterKnife.bind(this, rootView);
final Context context = rootView.getContext(); final Context context = rootView.getContext();
accentColor = Helpers.colorToHex(ThemeHelper.getAccentColor()); accentColor = Helpers.get().colorToHexString(ThemeHelper.getAccentColor());
maintainers.setTextFormatted(getString(R.string.fragment_license__maintainers_text, maintainers.setTextFormatted(getString(R.string.fragment_license__maintainers_text,
Helpers.loadMarkdownFromRawForTextView(context, R.raw.maintainers, ""))); Helpers.get().loadMarkdownForTextViewFromRaw(R.raw.maintainers, "")));
contributors.setTextFormatted(getString(R.string.fragment_license__contributors_thank_you, contributors.setTextFormatted(getString(R.string.fragment_license__contributors_thank_you,
Helpers.loadMarkdownFromRawForTextView(context, R.raw.contributors, "* "))); Helpers.get().loadMarkdownForTextViewFromRaw(R.raw.contributors, "* ")));
thirdPartyLibs.setTextFormatted( thirdPartyLibs.setTextFormatted(
Helpers.loadMarkdownFromRawForTextView(context, R.raw.license_third_party, "")); Helpers.get().loadMarkdownForTextViewFromRaw(R.raw.license_third_party, ""));
return rootView; return rootView;
} }
@ -278,10 +278,10 @@ public class AboutActivity extends ThemedActivity
public void buttonClicked(View v) { public void buttonClicked(View v) {
switch (v.getId()) { switch (v.getId()) {
case R.id.fragment_license__leafpic_button: case R.id.fragment_license__leafpic_button:
Helpers.openInExternalBrowser(getContext(), getString(R.string.fragment_licesen__misc_leafpic_link)); Helpers.get().openWebpageInExternalBrowser(getString(R.string.fragment_licesen__misc_leafpic_link));
break; break;
case R.id.fragment_license__license_button: case R.id.fragment_license__license_button:
Helpers.openInExternalBrowser(getContext(), getString(R.string.fragment_license__license_gpl_link)); Helpers.get().openWebpageInExternalBrowser(getString(R.string.fragment_license__license_gpl_link));
break; break;
} }
} }

View file

@ -159,7 +159,7 @@ public class AspectListFragment extends ThemedFragment implements OnSomethingCli
final DiasporaAspect aspect = aspectList[position]; final DiasporaAspect aspect = aspectList[position];
holder.title.setText(aspect.name); holder.title.setText(aspect.name);
if (position % 2 == 1) { if (position % 2 == 1) {
holder.root.setBackgroundColor(Helpers.getColorFromRessource(c, R.color.alternate_row_color)); holder.root.setBackgroundColor(Helpers.get().color(R.color.alternate_row_color));
} }
// Favourite (Star) Image // Favourite (Star) Image

View file

@ -271,7 +271,7 @@ public class DiasporaStreamFragment extends BrowserFragment {
// Create the File where the photo should go // Create the File where the photo should go
File photoFile; File photoFile;
try { try {
photoFile = Helpers.createImageFile(); photoFile = Helpers.get().createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath); takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) { } catch (IOException ex) {
AppLog.e(this, "ERROR creating temp file: " + ex.toString()); AppLog.e(this, "ERROR creating temp file: " + ex.toString());

View file

@ -76,8 +76,6 @@ import com.github.dfa.diaspora_android.ui.theme.ThemedAlertDialogBuilder;
import com.github.dfa.diaspora_android.util.AppLog; import com.github.dfa.diaspora_android.util.AppLog;
import com.github.dfa.diaspora_android.util.AppSettings; import com.github.dfa.diaspora_android.util.AppSettings;
import com.github.dfa.diaspora_android.util.DiasporaUrlHelper; import com.github.dfa.diaspora_android.util.DiasporaUrlHelper;
import com.github.dfa.diaspora_android.util.Helpers;
import io.github.gsantner.opoc.util.SimpleMarkdownParser;
import com.github.dfa.diaspora_android.web.BrowserFragment; import com.github.dfa.diaspora_android.web.BrowserFragment;
import com.github.dfa.diaspora_android.web.ContextMenuWebView; import com.github.dfa.diaspora_android.web.ContextMenuWebView;
import com.github.dfa.diaspora_android.web.ProxyHandler; import com.github.dfa.diaspora_android.web.ProxyHandler;
@ -89,6 +87,8 @@ import java.io.IOException;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import butterknife.OnClick; import butterknife.OnClick;
import io.github.gsantner.opoc.util.HelpersA;
import io.github.gsantner.opoc.util.SimpleMarkdownParser;
public class MainActivity extends ThemedActivity public class MainActivity extends ThemedActivity
implements NavigationView.OnNavigationItemSelectedListener, implements NavigationView.OnNavigationItemSelectedListener,
@ -229,13 +229,13 @@ public class MainActivity extends ThemedActivity
+ smp.parse(getResources().openRawResource(R.raw.license_third_party), + smp.parse(getResources().openRawResource(R.raw.license_third_party),
SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW, ""); SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW, "");
html = smp.setHtml(html).removeMultiNewlines().getHtml(); html = smp.setHtml(html).removeMultiNewlines().getHtml();
Helpers.showDialogWithHtmlTextView(this, html, R.string.about_activity__title_about_license); HelpersA.get(this).showDialogWithHtmlTextView(R.string.about_activity__title_about_license, html);
appSettings.isAppCurrentVersionFirstStart(); appSettings.isAppCurrentVersionFirstStart();
} else if (appSettings.isAppCurrentVersionFirstStart()) { } else if (appSettings.isAppCurrentVersionFirstStart()) {
SimpleMarkdownParser smp = new SimpleMarkdownParser().parse( SimpleMarkdownParser smp = new SimpleMarkdownParser().parse(
getResources().openRawResource(R.raw.changelog), getResources().openRawResource(R.raw.changelog),
SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW, ""); SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW, "");
Helpers.showDialogWithHtmlTextView(this, smp.getHtml(), R.string.changelog); HelpersA.get(this).showDialogWithHtmlTextView(R.string.changelog, smp.getHtml());
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();

View file

@ -116,11 +116,11 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O
} }
}); });
LocalBroadcastManager.getInstance(getContext()).registerReceiver(podListReceiver, new IntentFilter(FetchPodsService.MESSAGE_PODS_RECEIVED)); LocalBroadcastManager.getInstance(getContext()).registerReceiver(podListReceiver, new IntentFilter(FetchPodsService.MESSAGE_PODS_RECEIVED));
Helpers.showInfoIfUserNotConnectedToInternet(getContext(), listViewPod); Helpers.get().showInfoIfUserNotConnectedToInternet(getActivity(), listViewPod);
} }
public void mergePodlistWithRessources(DiasporaPodList podlist) { public void mergePodlistWithRessources(DiasporaPodList podlist) {
String sPodlist = Helpers.readTextfileFromRawRessource(getContext(), R.raw.podlist, "", ""); String sPodlist = Helpers.get().readTextfileFromRawRes(R.raw.podlist, "", "");
try { try {
JSONObject jPodlist = new JSONObject(sPodlist); JSONObject jPodlist = new JSONObject(sPodlist);
podlist.mergeWithNewerEntries(new DiasporaPodList().fromJson(jPodlist)); podlist.mergeWithNewerEntries(new DiasporaPodList().fromJson(jPodlist));
@ -219,7 +219,7 @@ public class PodSelectionFragment extends ThemedFragment implements SearchView.O
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.action_reload: { case R.id.action_reload: {
if (!Helpers.showInfoIfUserNotConnectedToInternet(getContext(), listViewPod)) { if (!Helpers.get().showInfoIfUserNotConnectedToInternet(getActivity(), listViewPod)) {
Intent i = new Intent(getContext(), FetchPodsService.class); Intent i = new Intent(getContext(), FetchPodsService.class);
getContext().startService(i); getContext().startService(i);
return true; return true;

View file

@ -158,7 +158,7 @@ public class TagListFragment extends ThemedFragment implements OnSomethingClickL
final String tag = followedTagsList[position]; final String tag = followedTagsList[position];
holder.title.setText(tag); holder.title.setText(tag);
if (position % 2 == 1) { if (position % 2 == 1) {
holder.root.setBackgroundColor(Helpers.getColorFromRessource(c, R.color.alternate_row_color)); holder.root.setBackgroundColor(Helpers.get().color(R.color.alternate_row_color));
} }
// Favourite (Star) Image // Favourite (Star) Image

View file

@ -99,7 +99,7 @@ public abstract class ThemedActivity extends AppCompatActivity {
public void updateLanguage() { public void updateLanguage() {
AppSettings appSettings = getAppSettings(); AppSettings appSettings = getAppSettings();
Locale locale = Helpers.getLocaleByAndroidCode(appSettings.getLanguage()); Locale locale = Helpers.get().getLocaleByAndroidCode(appSettings.getLanguage());
Configuration config = appSettings.getContext().getResources().getConfiguration(); Configuration config = appSettings.getContext().getResources().getConfiguration();
config.locale = locale != null ? locale : Locale.getDefault(); config.locale = locale != null ? locale : Locale.getDefault();
appSettings.getContext().getResources().updateConfiguration(config, null); appSettings.getContext().getResources().updateConfiguration(config, null);

View file

@ -50,7 +50,7 @@ public class ThemedColorPickerPreference extends Preference implements Themeable
AppSettings appSettings = AppSettings.get(); AppSettings appSettings = AppSettings.get();
String key = getKey(); String key = getKey();
int color = Helpers.getColorFromRessource(c, R.color.primary); int color = Helpers.get().color(R.color.primary);
if ((appSettings.isKeyEqual(key, R.string.pref_key__primary_color_shade))) { if ((appSettings.isKeyEqual(key, R.string.pref_key__primary_color_shade))) {
color = appSettings.getPrimaryColor(); color = appSettings.getPrimaryColor();
} else if ((appSettings.isKeyEqual(key, R.string.pref_key__accent_color_shade))) { } else if ((appSettings.isKeyEqual(key, R.string.pref_key__accent_color_shade))) {

View file

@ -1,70 +1,36 @@
/*
This file is part of the dandelion*.
dandelion* is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dandelion* is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the dandelion*.
If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.dfa.diaspora_android.util; package com.github.dfa.diaspora_android.util;
import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Environment; import android.os.Environment;
import android.support.annotation.RawRes;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.TypedValue;
import android.view.View; import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.R; import com.github.dfa.diaspora_android.R;
import com.github.dfa.diaspora_android.web.WebHelper; import com.github.dfa.diaspora_android.web.WebHelper;
import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.Locale; import java.util.Locale;
import io.github.gsantner.opoc.util.SimpleMarkdownParser; import io.github.gsantner.opoc.util.HelpersA;
public class Helpers { @SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"})
public static int getColorFromRessource(Context context, int ressourceId) { public class Helpers extends io.github.gsantner.opoc.util.Helpers {
Resources res = context.getResources(); protected Helpers(Context context) {
if (Build.VERSION.SDK_INT >= 23) { super(context);
return res.getColor(ressourceId, context.getTheme());
} else {
return res.getColor(ressourceId);
}
} }
public static File createImageFile() throws IOException {
public static Helpers get() {
return new Helpers(App.get());
}
public File createImageFile() throws IOException {
// Create an image file name // Create an image file name
String timeStamp = new SimpleDateFormat("dd-MM-yy_HH-mm", Locale.getDefault()).format(new Date()); String timeStamp = new SimpleDateFormat("dd-MM-yy_HH-mm", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_"; String imageFileName = "JPEG_" + timeStamp + "_";
@ -78,125 +44,35 @@ public class Helpers {
); );
} }
public static Locale getLocaleByAndroidCode(String code) { /**
if (!TextUtils.isEmpty(code)) { * Show Information if user is offline, returns true if is not connected to internet
return code.contains("-r") *
? new Locale(code.substring(0, 2), code.substring(4, 6)) // de-rAT * @param activity Activity
: new Locale(code); // de * @param anchor A view anchor
*/
public boolean showInfoIfUserNotConnectedToInternet(Activity activity, View anchor) {
boolean isOnline = WebHelper.isOnline(context);
if (!isOnline) {
HelpersA.get(activity).showSnackBar(R.string.no_internet, true);
} }
return Locale.getDefault(); return !isOnline;
} }
public void logBundle(Bundle savedInstanceState, String k) {
public static String readTextfileFromRawRessource(Context context, int rawRessourceId, String linePrefix, String linePostfix) {
StringBuilder sb = new StringBuilder();
String line;
BufferedReader br = null;
linePrefix = linePrefix == null ? "" : linePrefix;
linePostfix = linePostfix == null ? "" : linePostfix;
try {
br = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(rawRessourceId)));
while ((line = br.readLine()) != null) {
sb.append(linePrefix);
sb.append(line);
sb.append(linePostfix);
sb.append("\n");
}
} catch (Exception ignored) {
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ignored) {
}
}
}
return sb.toString();
}
public static String loadMarkdownFromRawForTextView(Context context, @RawRes int rawMdFile, String prepend) {
try {
return new SimpleMarkdownParser()
.parse(context.getResources().openRawResource(rawMdFile),
SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW, prepend)
.replaceColor("#000001", ContextCompat.getColor(context, R.color.accent))
.removeMultiNewlines().replaceBulletCharacter("*").getHtml();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public static void showDialogWithHtmlTextView(Context context, String html, @StringRes int resTitleId) {
LinearLayout layout = new LinearLayout(context);
TextView textView = new TextView(context);
textView.setMovementMethod(LinkMovementMethod.getInstance());
ScrollView root = new ScrollView(context);
int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20,
context.getResources().getDisplayMetrics());
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
layoutParams.setMargins(margin, 0, margin, 0);
layout.setLayoutParams(layoutParams);
layout.addView(textView);
root.addView(layout);
textView.setText(new SpannableString(Html.fromHtml(html)));
AlertDialog.Builder dialog = new AlertDialog.Builder(context)
.setPositiveButton(android.R.string.ok, null)
.setTitle(resTitleId)
.setView(root);
dialog.show();
}
public static String colorToHex(int color) {
return "#" + Integer.toHexString(color & 0x00ffffff);
}
public static void printBundle(Bundle savedInstanceState, String k) {
if (savedInstanceState != null) { if (savedInstanceState != null) {
for (String key : savedInstanceState.keySet()) { for (String key : savedInstanceState.keySet()) {
AppLog.d("SAVED", key + " is a key in the bundle " + k); AppLog.d("Bundle", key + " is a key in the bundle " + k);
Object bun = savedInstanceState.get(key); Object bun = savedInstanceState.get(key);
if (bun != null) { if (bun != null) {
if (bun instanceof Bundle) { if (bun instanceof Bundle) {
printBundle((Bundle) bun, k + "." + key); logBundle((Bundle) bun, k + "." + key);
} else if (bun instanceof byte[]) { } else if (bun instanceof byte[]) {
AppLog.d("SAVED", "Key: " + k + "." + key + ": " + Arrays.toString((byte[]) bun)); AppLog.d("Bundle", "Key: " + k + "." + key + ": " + Arrays.toString((byte[]) bun));
} else { } else {
AppLog.d("SAVED", "Key: " + k + "." + key + ": " + bun.toString()); AppLog.d("Bundle", "Key: " + k + "." + key + ": " + bun.toString());
} }
} }
} }
} }
} }
/**
* Show Information if user is offline, returns true if is not connected to internet
*
* @param context Context
* @param anchor A view anchor
*/
public static boolean showInfoIfUserNotConnectedToInternet(Context context, View anchor) {
boolean isOnline = WebHelper.isOnline(context);
if (!isOnline) {
Snackbar.make(anchor, R.string.no_internet, Snackbar.LENGTH_LONG).show();
}
return !isOnline;
}
/**
* Send an Intent that opens url in any browser
*
* @param context context
* @param url url
*/
public static void openInExternalBrowser(Context context, String url) {
Intent openBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
openBrowserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(openBrowserIntent);
}
} }

View file

@ -1,10 +1,12 @@
/* /*
* ---------------------------------------------------------------------------- * ---------------------------------------------------------------------------- *
* "THE COKE-WARE LIBRARY LICENSE" (Revision 255):
* Gregor Santner <gsantner.github.io> wrote this file. You can do whatever * Gregor Santner <gsantner.github.io> wrote this file. You can do whatever
* you want with this stuff. If we meet some day, and you think this stuff is * you want with this stuff. If we meet some day, and you think this stuff is
* worth it, you can buy me a coke in return. Provided as is without any kind * worth it, you can buy me a coke in return. Provided as is without any kind
* of warranty. No attribution required. - Gregor Santner * of warranty. No attribution required. - Gregor Santner
*
* License: Creative Commons Zero (CC0 1.0)
* http://creativecommons.org/publicdomain/zero/1.0/
* ---------------------------------------------------------------------------- * ----------------------------------------------------------------------------
*/ */

View file

@ -0,0 +1,221 @@
/*
* ---------------------------------------------------------------------------- *
* Gregor Santner <gsantner.github.io> wrote this file. You can do whatever
* you want with this stuff. If we meet some day, and you think this stuff is
* worth it, you can buy me a coke in return. Provided as is without any kind
* of warranty. No attribution required. - Gregor Santner
*
* License: Creative Commons Zero (CC0 1.0)
* http://creativecommons.org/publicdomain/zero/1.0/
* ----------------------------------------------------------------------------
*/
package io.github.gsantner.opoc.util;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.RawRes;
import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatButton;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.webkit.WebView;
import com.github.dfa.diaspora_android.App;
import com.github.dfa.diaspora_android.BuildConfig;
import com.github.dfa.diaspora_android.R;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;
@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"})
public class Helpers {
protected Context context;
protected Helpers(Context context) {
this.context = context;
}
public static Helpers get() {
return new Helpers(App.get());
}
public String str(@StringRes int strResId) {
return context.getString(strResId);
}
public Drawable drawable(@DrawableRes int resId) {
return ContextCompat.getDrawable(context, resId);
}
public int color(@ColorRes int resId) {
return ContextCompat.getColor(context, resId);
}
public Context context() {
return context;
}
public String colorToHexString(int intColor) {
return String.format("#%06X", 0xFFFFFF & intColor);
}
public String getAppVersionName() {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
return info.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return "unknown";
}
}
public void openWebpageInExternalBrowser(String url) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public void showDonateBitcoinRequest() {
if (!BuildConfig.IS_GPLAY_BUILD) {
String btcUri = String.format("bitcoin:%s?amount=%s&label=%s&message=%s",
str(R.string.donate__bitcoin_id), str(R.string.donate__bitcoin_amount),
str(R.string.donate__bitcoin_message), str(R.string.donate__bitcoin_message));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(btcUri));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
openWebpageInExternalBrowser(str(R.string.donate__bitcoin_url));
}
}
}
public String readTextfileFromRawRes(@RawRes int rawResId, String linePrefix, String linePostfix) {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
String line;
linePrefix = linePrefix == null ? "" : linePrefix;
linePostfix = linePostfix == null ? "" : linePostfix;
try {
br = new BufferedReader(new InputStreamReader(context.getResources().openRawResource(rawResId)));
while ((line = br.readLine()) != null) {
sb.append(linePrefix);
sb.append(line);
sb.append(linePostfix);
sb.append("\n");
}
} catch (Exception ignored) {
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ignored) {
}
}
}
return sb.toString();
}
public void showDialogWithRawFileInWebView(String fileInRaw, @StringRes int resTitleId) {
WebView wv = new WebView(context);
wv.loadUrl("file:///android_res/raw/" + fileInRaw);
AlertDialog.Builder dialog = new AlertDialog.Builder(context)
.setPositiveButton(android.R.string.ok, null)
.setTitle(resTitleId)
.setView(wv);
dialog.show();
}
@SuppressLint("RestrictedApi")
public void setTintColorOfButton(AppCompatButton button, @ColorRes int resColor) {
button.setSupportBackgroundTintList(ColorStateList.valueOf(
color(resColor)
));
}
public boolean isConnectedToInternet() {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
return activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
}
public void restartApp(Class classToStartupWith) {
Intent restartIntent = new Intent(context, classToStartupWith);
PendingIntent restartIntentP = PendingIntent.getActivity(context, 555,
restartIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, restartIntentP);
System.exit(0);
}
public String loadMarkdownForTextViewFromRaw(@RawRes int rawMdFile, String prepend) {
try {
return new SimpleMarkdownParser()
.parse(context.getResources().openRawResource(rawMdFile),
SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW, prepend)
.replaceColor("#000001", color(R.color.accent))
.removeMultiNewlines().replaceBulletCharacter("*").getHtml();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public double getEstimatedScreenSizeInches() {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
double density = dm.density * 160;
double x = Math.pow(dm.widthPixels / density, 2);
double y = Math.pow(dm.heightPixels / density, 2);
double screenInches = Math.sqrt(x + y) * 1.16; // 1.16 = est. Nav/Statusbar
screenInches = screenInches < 4.0 ? 4.0 : screenInches;
screenInches = screenInches > 12.0 ? 12.0 : screenInches;
return screenInches;
}
public boolean isInPortraitMode() {
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
}
public Locale getLocaleByAndroidCode(String code) {
if (!TextUtils.isEmpty(code)) {
return code.contains("-r")
? new Locale(code.substring(0, 2), code.substring(4, 6)) // de-rAt
: new Locale(code); // de
}
return Locale.getDefault();
}
// "en"/"de"/"de-rAt"; Empty string = default locale
public void setAppLanguage(String androidLocaleString) {
Locale locale = getLocaleByAndroidCode(androidLocaleString);
Configuration config = context.getResources().getConfiguration();
config.locale = locale != null ? locale : Locale.getDefault();
context.getResources().updateConfiguration(config, null);
}
}

View file

@ -0,0 +1,112 @@
/*
* ---------------------------------------------------------------------------- *
* Gregor Santner <gsantner.github.io> wrote this file. You can do whatever
* you want with this stuff. If we meet some day, and you think this stuff is
* worth it, you can buy me a coke in return. Provided as is without any kind
* of warranty. No attribution required. - Gregor Santner
*
* License: Creative Commons Zero (CC0 1.0)
* http://creativecommons.org/publicdomain/zero/1.0/
* ----------------------------------------------------------------------------
*/
package io.github.gsantner.opoc.util;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.SpannableString;
import android.text.method.ScrollingMovementMethod;
import android.util.TypedValue;
import android.view.inputmethod.InputMethodManager;
import com.github.dfa.diaspora_android.R;
@SuppressWarnings({"WeakerAccess", "unused", "SameParameterValue"})
public class HelpersA extends Helpers {
protected Activity activity;
protected HelpersA(Activity activity) {
super(activity);
this.activity = activity;
}
public static HelpersA get(Activity activity) {
return new HelpersA(activity);
}
//########################
//## Methods
//########################
/**
* Animate to specified Activity
*
* @param to The class of the activity
* @param finishFromActivity true: Finish the current activity
* @param requestCode Request code for stating the activity, not waiting for result if null
*/
public void animateToActivity(Class to, Boolean finishFromActivity, Integer requestCode) {
animateToActivity(new Intent(activity, to), finishFromActivity, requestCode);
}
/**
* Animate to activity specified in intent
*
* @param intent Intent to open start an activity
* @param finishFromActivity true: Finish the current activity
* @param requestCode Request code for stating the activity, not waiting for result if null
*/
public void animateToActivity(Intent intent, Boolean finishFromActivity, Integer requestCode) {
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
if (requestCode != null) {
activity.startActivityForResult(intent, requestCode);
} else {
activity.startActivity(intent);
}
activity.overridePendingTransition(R.anim.fadein, R.anim.fadeout);
if (finishFromActivity != null && finishFromActivity) {
activity.finish();
}
}
public void showSnackBar(@StringRes int stringId, boolean showLong) {
Snackbar.make(activity.findViewById(android.R.id.content), stringId,
showLong ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT).show();
}
public void hideSoftKeyboard() {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
if (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) {
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
}
public void showDialogWithHtmlTextView(@StringRes int resTitleId, String html) {
showDialogWithHtmlTextView(resTitleId, html, null);
}
public void showDialogWithHtmlTextView(@StringRes int resTitleId, String html, DialogInterface.OnDismissListener dismissedListener) {
AppCompatTextView textView = new AppCompatTextView(context);
int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16,
context.getResources().getDisplayMetrics());
textView.setMovementMethod(new ScrollingMovementMethod());
textView.setPadding(padding, 0, padding, 0);
textView.setText(new SpannableString(Html.fromHtml(html)));
AlertDialog.Builder dialog = new AlertDialog.Builder(context)
.setPositiveButton(android.R.string.ok, null)
.setOnDismissListener(dismissedListener)
.setTitle(resTitleId)
.setView(textView);
dialog.show();
}
}

View file

@ -1,16 +1,20 @@
/* /*
* ---------------------------------------------------------------------------- * ---------------------------------------------------------------------------- *
* "THE COKE-WARE LIBRARY LICENSE" (Revision 255):
* Gregor Santner <gsantner.github.io> wrote this file. You can do whatever * Gregor Santner <gsantner.github.io> wrote this file. You can do whatever
* you want with this stuff. If we meet some day, and you think this stuff is * you want with this stuff. If we meet some day, and you think this stuff is
* worth it, you can buy me a coke in return. Provided as is without any kind * worth it, you can buy me a coke in return. Provided as is without any kind
* of warranty. No attribution required. - Gregor Santner * of warranty. No attribution required. - Gregor Santner
*
* License: Creative Commons Zero (CC0 1.0)
* http://creativecommons.org/publicdomain/zero/1.0/
* ---------------------------------------------------------------------------- * ----------------------------------------------------------------------------
*/ */
/* /*
* Get updates: * Get updates:
* https://github.com/gsantner/onePieceOfCode/blob/master/java/SimpleMarkdownParser.java * https://github.com/gsantner/onePieceOfCode/blob/master/java/SimpleMarkdownParser.java
* Apply to TextView:
* See https://github.com/gsantner/onePieceOfCode/blob/master/android/Helpers.get().java
* Parses most common markdown tags. Only inline tags are supported, multiline/block syntax * Parses most common markdown tags. Only inline tags are supported, multiline/block syntax
* is not supported (citation, multiline code, ..). This is intended to stay as easy as possible. * is not supported (citation, multiline code, ..). This is intended to stay as easy as possible.
* *
@ -21,54 +25,8 @@
* CHANGELOG.md file without inlcuding a WebView for showing HTML, or other additional UI-libraries. * CHANGELOG.md file without inlcuding a WebView for showing HTML, or other additional UI-libraries.
* *
* FILTER_HTMLPART is intended to be used at engines understanding most common HTML tags. * FILTER_HTMLPART is intended to be used at engines understanding most common HTML tags.
*
* You can use this anywhere you want, no backlink/attribution required, but I would appreciate it.
*/ */
/*
// Apply to Android TextView:
textView.setText(new SpannableString(Html.fromHtml(htmlFromParser)));
// As wrapper method, includes applying accent color
public static String loadMarkdownFromRawForTextView(Context context, @RawRes int rawMdFile, String prepend) {
try {
return new SimpleMarkdownParser()
.parse(context.getResources().openRawResource(rawMdFile),
SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW, prepend)
.replaceColor("#000001", ContextCompat.getColor(context, R.color.accent))
.removeMultiNewlines().replaceBulletCharacter("*").getHtml();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
// Show HTML a TextView in a scrollable Dialog
public static void showDialogWithHtmlTextView(Context context, String html, @StringRes int resTitleId) {
LinearLayout layout = new LinearLayout(context);
TextView textView = new TextView(context);
textView.setMovementMethod(LinkMovementMethod.getInstance());
ScrollView root = new ScrollView(context);
int margin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20,
context.getResources().getDisplayMetrics());
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
layoutParams.setMargins(margin, 0, margin, 0);
layout.setLayoutParams(layoutParams);
layout.addView(textView);
root.addView(layout);
textView.setText(new SpannableString(Html.fromHtml(html)));
AlertDialog.Builder dialog = new AlertDialog.Builder(context)
.setPositiveButton(android.R.string.ok, null)
.setTitle(resTitleId)
.setView(root);
dialog.show();
}
*/
package io.github.gsantner.opoc.util; package io.github.gsantner.opoc.util;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -137,9 +95,7 @@ public class SimpleMarkdownParser {
}; };
//######################## //########################
//##
//## Members //## Members
//##
//######################## //########################
private String html; private String html;
@ -193,14 +149,10 @@ public class SimpleMarkdownParser {
} }
public SimpleMarkdownParser replaceColor(String hexColor, int newIntColor) { public SimpleMarkdownParser replaceColor(String hexColor, int newIntColor) {
html = html.replace(hexColor, colorToHexString(newIntColor)); html = html.replace(hexColor, String.format("#%06X", 0xFFFFFF & newIntColor));
return this; return this;
} }
public static String colorToHexString(int intColor) {
return String.format("#%06X", 0xFFFFFF & intColor);
}
@Override @Override
public String toString() { public String toString() {
return html != null ? html : ""; return html != null ? html : "";

View file

@ -118,4 +118,10 @@
<string name="pod_address">Pod address</string> <string name="pod_address">Pod address</string>
<string name="missing_value">Missing value</string> <string name="missing_value">Missing value</string>
<string name="jump_to_last_visited_timestamp_in_stream">Jump to last visited page in stream?</string> <string name="jump_to_last_visited_timestamp_in_stream">Jump to last visited page in stream?</string>
<string name="not_implemented" translatable="false">not_implemented</string>
<string name="donate__bitcoin_id" translatable="false">@string/not_implemented</string>
<string name="donate__bitcoin_message" translatable="false">@string/not_implemented</string>
<string name="donate__bitcoin_amount" translatable="false">@string/not_implemented</string>
<string name="donate__bitcoin_url" translatable="false">@string/not_implemented</string>
</resources> </resources>