- Android. Вывод изображений, различные способы
- Is it possible to display inline images from html in an Android TextView?
- 9 Answers 9
- How to get the HTML source of a page from a HTML link in Android?
- 8 Answers 8
- Html.fromHtml deprecated in Android N
- 14 Answers 14
- Html from html image android
- Example 1 Of Parse HTML File content Using WebView With Example In Android Studio:
- Example 2 Of HTML In Android Studio Using TextView:
- Example 3 Of HTML content in WebView With Example in Android Studio:
Android. Вывод изображений, различные способы
Эта статья будет полезна начинающим разработчикам, здесь я предложу несколько вариантов вывода изображений на Android. Будут описаны следующие способы:
Обычный метод – стандартный способ, используя ImageView. Рассмотрены варианты загрузки картинки из ресурса, а также из файла на SD карте устройства.
Продвинутый вариант — вывод изображения, используя WebView. Добавляется поддержка масштабирования и прокрутки картинки при помощи жестов.
“Джедайский” способ – улучшенный предыдущий вариант. Добавлен полноэкранный просмотр с автоматическим масштабированием изображения при показе и поддержкой смены ориентации устройства.
Исходники тестового проекта на GitHub github.com/Voldemar123/andriod-image-habrahabr-example
В этой статье я не рассматриваю вопросы загрузки изображений из Интернета, кеширования, работы с файлами и необходимых для работы приложения permissions – только вывод картинок.
Итак, задача — предположим, в нашем приложении необходимо вывести изображение на экран.
Картинка может размерами превышать разрешение экрана и иметь различное соотношение сторон.
Хранится она либо в ресурсах приложения, либо на External Storage — SD карте.
Также допустим, мы уже записали на карту памяти несколько изображений (в тестовом проекте – загружаем из сети). Храним их в каталоге данных нашего приложения, в кеше.
public static final String APP_PREFS_NAME = Constants.class.getPackage().getName();
public static final String APP_CACHE_PATH =
Environment.getExternalStorageDirectory().getAbsolutePath() +
«/Android/data/» + APP_PREFS_NAME + «/cache/»;
Layout, где выводится картинка
android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:orientation=»vertical» >
Масштабирование по умолчанию, по меньшей стoроне экрана.
В Activity, где загружаем содержимое картинки
private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageView1);
Из ресурсов приложения (файл из res/drawable/img3.jpg)
Задавая Bitmap изображения
FileInputStream fis = new FileInputStream(Constants.APP_CACHE_PATH + this.image);
BufferedInputStream bis = new BufferedInputStream(fis);
Bitmap img = BitmapFactory.decodeStream(bis);
Или передать URI на изображение (может хранится на карте или быть загружено из сети)
mImageView.setImageURI( imageUtil.getImageURI() );
Uri.fromFile( new File( Constants.APP_CACHE_PATH + this.image ) );
Этот способ стандартный, описан во множестве примеров и поэтому нам не особо интересен. Переходим к следующему варианту.
Предположим, мы хотим показать большое изображение (например фотографию), которое размерами превышает разрешение нашего устройства. Необходимо добавить прокрутку и масштабирование картинки на экране.
android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:orientation=»vertical» >
В Activity, где загружаем содержимое
protected WebView webView;
webView = (WebView) findViewById(R.id.webView1);
установка черного цвета фона для комфортной работы (по умолчанию – белый)
включаем поддержку масштабирования
больше места для нашей картинки
webView.setPadding(0, 0, 0, 0);
полосы прокрутки – внутри изображения, увеличение места для просмотра
загружаем изображение как ссылку на файл хранящийся на карте памяти
webView.loadUrl(imageUtil.getImageFileLink() );
«file:///» + Constants.APP_CACHE_PATH + this.image;
Теперь мы хотим сделать так, чтобы картинка при показе автоматически масштабировалась по одной из сторон, при этом прокрутка остается только в одном направлении.
Например, для просмотра фотографий более удобна ландшафтная ориентация устройства.
Также при смене ориентации телефона масштаб изображения должен автоматически меняться.
Дополнительно расширим место для просмотра изображения на полный экран.
В AndroidManifest.xml для нашей Activity добавляем
В код Activity добавлен метод, который вызыватся при каждом повороте нашего устройства.
@Override
public void onConfigurationChanged(Configuration newConfig) <
super.onConfigurationChanged(newConfig);
changeContent();
>
В приватном методе описана логика пересчета масштаба для картинки
Получаем информацию о размерах дисплея. Из-за того, что мы изменили тему Activity, теперь WebView раскрыт на полный экран, никакие другие элементы интерфейса не видны. Видимый размер дисплея равен разрешению экрана нашего Android устройства.
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Размеры изображения, выбранного для показа
Bitmap img = imageUtil.getImageBitmap();
int picWidth = img.getWidth();
int picHeight = img.getHeight();
Меняем масштаб изображения если его высота больше высоты экрана. Прокрутка теперь будет только по горизонтали.
if (picHeight > height)
val = new Double(height) / new Double(picHeight);
Подбрасываем в WebView специально сформированный HTML файл, содержащий изображение.
webView.loadDataWithBaseURL(«/»,
imageUtil.getImageHtml(picWidth, picHeight),
«text/html»,
«UTF-8»,
null);
StringBuffer html = new StringBuffer();
Такой способ я применил из-того, что после загрузки изображения в WebView через метод loadUrl, как в прошлом варианте, setInitialScale после поворота устройства не изменяет масштаб картинки. Другими словами, показали картинку, повернули телефон, масштаб остался старый. Очень похоже на то, что изображение как-то кешируется.
Я не нашел в документации упоминания об этом странном поведении. Может быть местные специалисты скажут, что я делаю не так?
Источник
Is it possible to display inline images from html in an Android TextView?
Given the following HTML:
This is text and this is an image .
Is it possible to make the image render? When using this snippet: mContentText.setText(Html.fromHtml(text)); , I get a cyan box with black borders, leading me to believe that a TextView has some idea of what an img tag is.
9 Answers 9
If you have a look at the documentation for Html.fromHtml(text) you’ll see it says:
Any tags in the HTML will display as a generic replacement image which your program can then go through and replace with real images.
If you don’t want to do this replacement yourself you can use the other Html.fromHtml() method which takes an Html.TagHandler and an Html.ImageGetter as arguments as well as the text to parse.
In your case you could parse null as for the Html.TagHandler but you’d need to implement your own Html.ImageGetter as there isn’t a default implementation.
However, the problem you’re going to have is that the Html.ImageGetter needs to run synchronously and if you’re downloading images from the web you’ll probably want to do that asynchronously. If you can add any images you want to display as resources in your application the your ImageGetter implementation becomes a lot simpler. You could get away with something like:
You’d probably want to figure out something smarter for mapping source strings to resource IDs though.
Источник
How to get the HTML source of a page from a HTML link in Android?
I’m working on an application that needs to get the source of a web page from a link, and then parse the html from that page.
Could you give me some examples, or starting points where to look to start writing such an app?
8 Answers 8
You can use HttpClient to perform an HTTP GET and retrieve the HTML response, something like this:
I would suggest jsoup.
According to their website:
Fetch the Wikipedia homepage, parse it to a DOM, and select the headlines from the In the news section into a list of Elements (online sample):
- Download the jsoup jar core library
- Read the cookbook introduction
This question is a bit old, but I figured I should post my answer now that DefaultHttpClient , HttpGet , etc. are deprecated. This function should get and return HTML, given a URL.
RetrieveFeedTask.class
OnTaskFinished.java
If you have a look here or here, you will see that you can’t do that directly with android API, you need an external librairy.
You can choose between the 2 here’s hereabove if you need an external librairy.
Источник
Html.fromHtml deprecated in Android N
I am using Html.fromHtml to view html in a TextView .
But Html.fromHtml is now deprecated in Android N+
What/How do I find the new way of doing this?
14 Answers 14
update: as @Andy mentioned below Google has created HtmlCompat which can be used instead of the method below. Add this dependency implementation ‘androidx.core:core:1.0.1 to the build.gradle file of your app. Make sure you use the latest version of androidx.core:core .
This allows you to use:
You can read more about the different flags on the HtmlCompat-documentation
original answer: In Android N they introduced a new Html.fromHtml method. Html.fromHtml now requires an additional parameter, named flags. This flag gives you more control about how your HTML gets displayed.
On Android N and above you should use this new method. The older method is deprecated and may be removed in the future Android versions.
You can create your own Util-method which will use the old method on older versions and the newer method on Android N and above. If you don’t add a version check your app will break on lower Android versions. You can use this method in your Util class.
You can convert the HTML.FROM_HTML_MODE_LEGACY into an additional parameter if you want. This gives you more control about it which flag to use.
You can read more about the different flags on the Html class documentation
Источник
Html from html image android
7. FROM_HTML_SEPARATOR_LINE_BREAK_LIST: This flag is used to indicate that texts inside
- elements will be separated from other texts with one newline character by default.
8. FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM: This flag is used to indicate that texts inside
elements will be separated from other texts with one newline character by default.
9. FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH: This flag is used to indicate that inside
elements will be separated from other texts with one newline character by default.
Example 1 Of Parse HTML File content Using WebView With Example In Android Studio:
Below is the example of HTML in which we parse the HTML file and display the HTML content in our Android WebView. In this example firstly we create a assets folder and store a HTML file in it. After that we create a WebView in our XML file and then get the reference of WebView in our MainActivity and finally with the help of loadUrl() method we display the content in our webView.
Step 1: Create a new project and name it HtmlExample.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we open an xml file and add the code for displaying a WebView.
Step 3: Now create assets folder in App. You can read here how to create assets folder in Android Studio
Step 4: Now inside assets folder add a HTML file name myfile.html. You can read here how to add local html file in Android Studio. Also inside myfile.html add the below HTML content or add any content in HTML format.
Step 5: Now Open src -> package -> MainActivity.java
In this step we open MainActivity where we add the code to initiate the WebView and then display the HTML content from file stored in assets folder into WebView.
Output:
Now run the App and you will see local content added in HTML file is loaded in Webview.
Example 2 Of HTML In Android Studio Using TextView:
Below is the example of HTML in which we display the HTML content in our Android TextView with the help of fromHtml() method. In this example firstly we create a TextView in our XML file and then get the reference of TextView in our MainActivity and finally with the help of fromHtml() method we set the content in our TextView.
Step 1: Create a new project and name it HtmlExample.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we open an xml file and add the code for displaying a TextView.
Step 3: Now Open src -> package -> MainActivity.java
In this step we open MainActivity where we add the code to initiate the TextView and then set the HTML content which is stored in a string variable into TextView using fromHtml() method.
Output:
Now run the App and you will see HTML content is shown in TextView.
Example 3 Of HTML content in WebView With Example in Android Studio:
Below is the example of HTML in which we display the HTML content in our Android WebView. In this example firstly we create a WebView in our XML file and then get the reference of WebView in our MainActivity and finally with the help of loadDataWithBaseURL() method we display the content in our webView.
Step 1: Create a new project and name it HtmlWebViewExample.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we open an xml file and add the code for displaying a WebView.
Step 3: Now Open src -> package -> MainActivity.java
In this step we open MainActivity where we add the code to initiate the WebView and then display the HTML content which is stored in a string variable into WebView.
Output:
Now run the App and you will see HTML content is displayed using Webview.
Источник