Android Studio: создать приложение apk из вебсайта

Здесь мы собираемся сделать приложение для своего сайта. Сделав это приложение, мы сможем узнать, как можно преобразовать веб-сайт в приложение для Android, просто выполнив простые шаги.

Что мы будем строить в этой статье?

В этом приложении мы узнаем, как можно использовать различные разделы веб-сайта и отображать их в виде фрагментов в нашем андроид-приложении. В этом приложении 3 раздела сайта Home, Practice и Contribute - будут использоваться в качестве фрагментов нашего приложения. Итак, вы можете увидеть живой пример преобразования веб-сайта в приложение. Для выполнения этой нужной работы используется концепция WebView. Ниже приведен пример видео, чтобы получить представление о том, что мы будем делать в этой статье. Мы собираемся реализовать этот проект, используя языки программирования Java и Kotlin для Android.

Простые шаги по превращению вашего сайта в приложение для Android

  • Добавить логотип вашего приложения.
  • Добавить заставку в приложение.
  • Использовать навигационное окно в нашем приложении, чтобы различные разделы нашего сайта можно было использовать в качестве фрагментов в навигационном окне.
  • Использование WebView для упрощения доступа к веб-контенту.
  • Использовать класс WebViewController, чтобы содержимое веб-сайта можно было отображать непосредственно в приложении, а не открывать его в браузере.
  • Добавление деятельности службы поддержки.

Следуя этим шагам, вы сможете преобразовать свой сайт в приложение самым простым способом. Итак, давайте рассмотрим пошаговую реализацию преобразования сайта в приложение.

Шаг 1. Создайте новый проект в Android Studio

Устанавливаем Android Studio. Далее пошагово создадим и настроим новый проект. Код для этого предоставлен как на Java, так и на языке программирования Kotlin для Android.

Как создать/запустить новый проект в Android Studio? Ниже приведены инструкции по запуску и настройке нового проекта Android в Android Studio.

1. Выберите Empty Activity

Выберите Phone and Tablet. Под активностью в Android понимается один экран с пользовательским интерфейсом.

создать/запустить новый проект в Android Studio

Примечание. Для новичков Empty Activity является хорошей рекомендацией.

2. Создайте новый проект Android

Затем укажите имя своего приложения в текстовом поле Name. По умолчанию имя приложения отображается как MyApplication и выберите местоположение приложения, которое вы собираетесь создать.

Создайте новый проект Android

Затем выберите Minimum SDK, чтобы выбрать операционную систему, версия которой должна быть наименьшей для запуска вашего приложения. Здесь Nougat представляет собой минимальный SDK, и телефоны и планшеты с версиями ниже этой ОС не смогут запускать ваши приложения. Нажмите Finish.

На этом этапе мы заполнили данные, указанные ниже:

  • Name: Имя представляет собой имя приложения.
  • Package name: Имя пакета создается автоматически и импортируется в программы, используемые в приложении.
  • Save location: место, где хранится приложение.
  • Language: относится к языку программирования, который используется в приложении.
  • Minimum SDK: это минимальная версия Andorid, на которой можно запустить приложение.
  • Build configuration language: используется для выбора инструмента, который создаст .apk в качестве конечного результата работы приложения.

3. Затем создается приложение по умолчанию со всеми файлами по умолчанию

И теперь вы можете приступить к написанию кода приложения.

Структура каталогов создаваемого приложения.

Структура каталогов создаваемого приложения

MainActivity.kt - это основная область исходного кода Kotlin, который обычно используется при разработке приложений для Android. Этот файл содержит основные действия приложения Android.

MainActivity.kt

Шаг 2. Добавление логотипа в приложение

Вставьте логотип вашего приложения в res > drawable. Дальнейшие действия описаны ниже на странице.

Развернуть / Свернуть

Как изменить значок приложения Android по умолчанию

Чтобы опубликовать приложение в таких магазинах, как Google Play Store, Amazon App Store и т.д., или если вы просто хотите персонализировать приложение, можно изменить значок по умолчанию.

17

Мы можем изменить значок приложения Android, используя саму Android Studio и выполнив следующие шаги:

1. Создайте проект Android Studio

Откройте проект Android Studio и убедитесь, что ваш проект относится к типу Android. Если это не Android, выберите Android из раскрывающегося списка. Это не обязательно, но облегчит поиск необходимых файлов и каталогов.

23

2. Теперь нажмите на папку app

Нажмите на папку res, затем на папку mipmap.

31

3. Убедитесь, что изображение значка уже присутствует на компьютере

Найдите путь к изображению. Здесь файл с именем gfgLogo присутствует в нашей папке «Загрузки». Если мы не можем найти значок для нашего приложения или не можем его создать, то следует поискать его на сайтах Flaticon или Material.io.

42

4. Импортируйте изображение

Теперь, когда наш значок находится в нужном месте и мы знаем путь, щелкните правой кнопкой мыши по папке mipmap, затем нажмите New и выберите Image Asset в раскрывающемся меню. Порядок действий будет следующим: mipmap (Правый клик) > New > Image Asset.

523

5. Теперь, когда мы нажмем Image Asset, откроется следующее окно
618

6. Изменение размера значка изображения

При необходимости размер изображения можно изменить с помощью параметра «Изменить размер» или изменить цвет нашего логотипа, перейдя к параметру «Фоновый слой». После внесения всех необходимых изменений мы нажмем кнопку Next, а затем Finish, после чего значок приложения изменится!

71

Шаг 3. Добавьте заставку в приложение

Разверните ниже страницу Создание заставки (Splash Screen), чтобы узнать, как добавить заставку в приложение. Пример дизайна заставки приложения.

Развернуть / Свернуть

Заставка - это, как правило, первый экран приложения при его открытии. Это постоянный экран, который появляется на определенное время и обычно появляется впервые при запуске приложения. Экран-заставка используется для отображения некоторой основной вводной информации, такой как логотип компании, контент и т.д., непосредственно перед полной загрузкой приложения.

Создание заставки с использованием обработчика в Android

Здесь мы создали два действия MainActivity, отображающие экран-заставку, и SecondActivity, чтобы переключиться с MainActivity на SecondActivity. Основная программа написана на MainActivity, вы можете менять действия по своему усмотрению.

  • Чтобы удалить ActionBar, вам необходимо внести следующие изменения в файл Styles.xml.
style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"
...
  • Используйте цвета, подходящие для вашего применения.
  • Нет необходимости вносить какие-либо изменения в файл манифеста.
  • MainActivity
package com.example.hp.splashscreen;
 
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Handler;
import android.view.WindowManager;
 
public class MainActivity extends AppCompatActivity {
    private static final int SPLASH_SCREEN_TIME_OUT = 2000; // After completion of 2000 ms, the next activity will get started.
     
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // This method is used so that your splash activity can cover the entire screen.
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
 
        setContentView(R.layout.activity_main); // this will bind your MainActivity.class file with activity_main.
         
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // Intent is used to switch from one activity to another.
                Intent i = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(i); // invoke the SecondActivity.
                finish(); // the current activity will get finished.
            }
        }, SPLASH_SCREEN_TIME_OUT);
    }
}

Шаг 4. Работа с XML-файлами

Откройте layout > nav_header_main.xml, чтобы создать заголовок нашего навигационного окна. Для этого используйте в нем следующий код.

  • nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Constraint Layout to display all the details of header file -->
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="#6C6B74"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">
 
    <!-- Image View to display logo of application in header -->
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="107dp"
        android:layout_height="87dp"
        android:layout_gravity="center"
        android:contentDescription="@string/nav_header_desc"
        android:foregroundGravity="center"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.247"
        app:srcCompat="@drawable/gfg_round" />
 
    <!-- TextView for name of application -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="51dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="GeeksForGeeks"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:textColor="#01A109"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/imageView"
        app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>

Измените цвет активной панели на #6C6B74, чтобы он соответствовал цветовому коду логотипа нашего приложения и наш пользовательский интерфейс стал более привлекательным.

Как изменить цвет ActionBar в приложении Android

Дополнительно, если вы не знаете, как изменить цвет ActionBar, то развернув ниже, прочтите страницу.

Развернуть / Свернуть

1. Изменив файл styles.xml

  • Перейдите в файл res/values/styles.xml.
  • Отредактируйте XML-файл, чтобы изменить цвет активной панели ActionBar.
  • Код для style.xml приведен ниже.
  • styles.xml
  • activity_main.xml
  • MainActivity.java
<resources> 
  
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> 
        <!-- Customize your theme here. -->
        <!-- This code is for changing the color of the bar. -->
        <!-- Type your colour code which you want to set in colorPrimary item -->
        <item name="colorPrimary">#0F9D58</item> 
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item> 
        <item name="colorAccent">@color/colorAccent</item> 
    </style> 
    <style name="AppTheme.NoActionBar"> 
        <item name="windowActionBar">false</item> 
        <item name="windowNoTitle">true</item> 
    </style> 
    <!-- Define other styles to fix theme -->
    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /> 
    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /> 
</resources>
<?xml version="1.0" encoding="utf-8"?> 
  
<!--Relative Layout-->
<RelativeLayout
    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:id="@+id/relativelayout"> 
  
    <!--Text View-->
   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/textview"
       android:textColor="#0F9D58"
       android:textSize="32dp"
       android:layout_centerInParent="true"/> 
</RelativeLayout>
package com.geeksforgeeks.changecolor; 
import android.widget.TextView; 
import android.support.v7.app.AppCompatActivity; 
  
public class MainActivity extends AppCompatActivity { 
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
        // Define text View 
        TextView t = findViewById(R.id.textview); 
        t.setText("Geeks for Geeks"); 
    } 
}
2. Через файл Java путем определения объекта ActionBar

  • Определите объект для класса ActionBar и colorDrawable.
  • Установите цвет с помощью функции setBackgroundDrawable с объектом colorDrawable в качестве параметра.
  • Вот полный код MainActivity.java.

  • MainActivity.java
  • activity_main.xml
package com.geeksforgeeks.changecolor; 
  
import android.support.v7.app.ActionBar; 
import android.graphics.Color; 
import android.graphics.drawable.ColorDrawable; 
import android.support.v7.app.AppCompatActivity; 
  
public class MainActivity extends AppCompatActivity { 
  
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
  
        // Define ActionBar object 
        ActionBar actionBar; 
        actionBar = getSupportActionBar(); 
  
        // Define ColorDrawable object and parse color 
        // using parseColor method 
        // with color hash code as its parameter 
        ColorDrawable colorDrawable 
            = new ColorDrawable(Color.parseColor("#0F9D58")); 
  
        // Set BackgroundDrawable 
        actionBar.setBackgroundDrawable(colorDrawable); 
    } 
}
<?xml version="1.0" encoding="utf-8"?> 
  
<!--Relative Layout-->
<RelativeLayout 
    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:id="@+id/relativelayout"> 
  
    <!--Text View-->
   <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textColor="#0F9D58"
       android:textSize="30dp"
       android:text="Geeks for Geeks"
       android:layout_centerInParent="true"/> 
</RelativeLayout>

Результат

  • Цвет активной панели ActionBar по умолчанию.
    Цвет панели действий по умолчанию
  • В MainActivity цвет ActionBar меняется на хэш-код, определенный в приведенном выше коде.
    В основной активности цвет панели действий

Шаг 4.1. Продолжение. Работа с XML-файлами

Откройте menu > activity_main_drawer.xml и используйте в нем следующий код, чтобы мы могли добавлять различные элементы (разделы нашего веб-сайта) в наш навигационное меню и использовать их фрагменты.

  • activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Group is used to group all these items together -->
    <group android:checkableBehavior="single">
 
        <!-- Three items are added as name of three portals -->
        <!-- Portal number 1- Home -->
        <!-- menu category is used as secondary so that backstack
        (going back by pressing back button) can be used -->
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/home"
            android:menuCategory="secondary"
            android:title="@string/menu_home" />
 
        <!-- Portal number 2- Practice -->
        <item
            android:id="@+id/nav_gallery"
            android:icon="@drawable/practice_gfg"
            android:menuCategory="secondary"
            android:title="Practice" />
 
        <!-- Portal number 3- Contribute -->
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@drawable/contribute_gfg"
            android:menuCategory="secondary"
            android:title="Contribute" />
    </group>
</menu>

Перейдите в layout > activity_main.xml и используйте в нем следующий код.

  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- DrawerLayout acts as top level container for window content that allows for
     interactive “drawer” views to be pulled out from one or both vertical edges of the window -->
<androidx.drawerlayout.widget.DrawerLayout
    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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">
 
    <!-- To reuse layouts include tag is used -->
    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
 
    <!-- Navigation view to make navigation drawer -->
    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#2E303E"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:itemIconTint="#fff"
        app:itemTextColor="#fff"
        app:menu="@menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>

После оформления приведенного выше кода файла activity_main.xml выглядит следующим образом.

activity_main.xml

Перейдите в navigation > mobile_navigation.xml и используйте в нем следующий код, чтобы мы могли указать заголовок и метку разделов нашего веб-сайта и могли легко использовать их в Java-файлах.

  • mobile_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation
    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:id="@+id/mobile_navigation"
    app:startDestination="@+id/nav_home">
 
    <!-- These fragments are made to work on all 
    the items listed in navigation drawer
    so that the java files can be managed separately -->
 
    <!-- Fragment for Home portal-->
    <fragment
        android:id="@+id/nav_home"
        android:name="com.example.geeksforgeeks.ui.home.HomeFragment"
        android:label="@string/menu_home"
        tools:layout="@layout/fragment_home" />
 
    <!-- Fragment for Practice portal-->
    <fragment
        android:id="@+id/nav_gallery"
        android:name="com.example.geeksforgeeks.ui.gallery.GalleryFragment"
        android:label="Practice"
        tools:layout="@layout/fragment_gallery" />
 
    <!-- Fragment for Contribute-->
    <fragment
        android:id="@+id/nav_slideshow"
        android:name="com.example.geeksforgeeks.ui.slideshow.SlideshowFragment"
        android:label="Contribute"
        tools:layout="@layout/fragment_slideshow" />
</navigation>

Теперь пришло время вставить WebView во все фрагменты, открыть fragment_home, fragment_gallery, and fragment_slideshow XML-файлов и использовать код соответственно.

  • home
  • gallery
  • slideshow
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
    tools:context=".ui.home.HomeFragment">
 
    <!-- WebView is added on full screen so that application interface can 
    be interactive and user can the web content is visible on full screen -->
    <WebView
        android:id="@+id/web_view_home"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
    tools:context=".ui.gallery.GalleryFragment">
 
    <WebView
        android:id="@+id/web_view_practice"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
    tools:context=".ui.slideshow.SlideshowFragment">
 
    <WebView
        android:id="@+id/web_view_contribute"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Теперь нам нужно создать новое действие с именем help. Таким образом, пользователь приложения может получить информацию для получения помощи от поставщика услуг. Перейдите в layout > right-click > new > activity > Empty Activity.

new > activity > Empty Activity

Назовите действие по вашему выбору (название, используемое в этом приложении – help). Откройте layout > activity_help.xml и используйте в нем следующий код.

  • activity_help.xml
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
    android:background="#6C6B74"
    tools:context=".help">
 
    <!-- Image to display help sign-->
    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="255dp"
        android:layout_height="173dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.222"
        app:srcCompat="@drawable/help" />
 
    <!-- Indicating user that we are here
         to help by using a textview-->
    <TextView
        android:id="@+id/textView2"
        android:layout_width="371dp"
        android:layout_height="95dp"
        android:background="#2E303E"
        android:text="For any kind of queries or help you can contact us at-"
        android:textColor="#FFFCFC"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView3"
        app:layout_constraintVertical_bias="0.296" />
 
    <!-- Contact details for help-->
    <TextView
        android:id="@+id/textView3"
        android:layout_width="393dp"
        android:layout_height="59dp"
        android:background="#2E303E"
        android:text="careers@geeksforgeeks.org"
        android:textColor="#FFFFFF"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.666"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        app:layout_constraintVertical_bias="0.159" />
</androidx.constraintlayout.widget.ConstraintLayout>

Теперь мы добавили фрагмент кода для получения разрешения на доступ к Интернету, чтобы наш WebView мог легко работать. Перейдите в раздел manifests > AndroidManifest.xml и добавьте в него следующий код.

<uses-permission android:name="android.permission.INTERNET" />

Шаг 5. Работа с файлами Java/Kotlin

Создайте новый класс, как показано ниже, и назовите его WebViewController.

Работа с файлами Java/Kotlin

Используйте следующий код в файле WebViewController, чтобы можно было выполнить код, использующий URL-адрес веб-сайта.

  • Java
  • Kotlin
import android.webkit.WebView;
import android.webkit.WebViewClient;
 
// class is extended to WebViewClient to access the WebView 
public class WebViewController extends WebViewClient {
   
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // loadurl function will load the 
        // url we will provide to our webview  
        view.loadUrl(url);
        return true;
    }
}
import android.webkit.WebView
import android.webkit.WebViewClient
 
// class is extended to WebViewClient to access the WebView 
class WebViewController : WebViewClient() {
    
   override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
       // loadurl function will load the 
       // url we will provide to our webview  
       view.loadUrl(url)
       return true
   }
}

Откройте файл HomeFragment и используйте код соответственно.

  • Java
  • Kotlin
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.geeksforgeeks.R;
import com.example.geeksforgeeks.WebViewController;
 
public class HomeFragment extends Fragment {
 
    private HomeViewModel homeViewModel;
 
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
 
        // Created a WebView and used the loadurl method to give url to WebViewController class
        WebView webView = root.findViewById(R.id.web_view_home);
        webView.loadUrl("https://www.geeksforgeeks.org/");  // Url of portal is passed
        webView.setWebViewClient(new WebViewController());  // WebViewController is used
        return root;
    }
}
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.geeksforgeeks.WebViewController
 
class HomeFragment : Fragment() {
 
    private lateinit var homeViewModel: HomeViewModel
 
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
 
        homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
        val root: View = inflater.inflate(R.layout.fragment_home, container, false)
 
        // Created a WebView and used the loadurl method to give url to WebViewController class
        val webView = root.findViewById<WebView>(R.id.web_view_home)
        webView.loadUrl("https://www.geeksforgeeks.org/") // Url of portal is passed
        webView.webViewClient = WebViewController() // WebViewController is used
        return root
    }
}

Откройте файл GalleryFragment и используйте соответствующий код.

  • Java
  • Kotlin
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.geeksforgeeks.R;
import com.example.geeksforgeeks.WebViewController;
 
public class GalleryFragment extends Fragment {
 
    private GalleryViewModel galleryViewModel;
 
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
        galleryViewModel = new ViewModelProvider(this).get(GalleryViewModel.class);
        View root = inflater.inflate(R.layout.fragment_gallery, container, false);
 
        WebView webView = root.findViewById(R.id.web_view_practice);
        webView.loadUrl("https://practice.geeksforgeeks.org/");
        webView.setWebViewClient(new WebViewController());
        return root;
    }
}
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.geeksforgeeks.WebViewController
 
 
class GalleryFragment : Fragment() {
     
    private lateinit var galleryViewModel: GalleryViewModel
     
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
         
        galleryViewModel = ViewModelProvider(this).get(GalleryViewModel::class.java)
        val root: View = inflater.inflate(R.layout.fragment_gallery, container, false)
         
        val webView = root.findViewById<WebView>(R.id.web_view_practice)
        webView.loadUrl("https://practice.geeksforgeeks.org/")
        webView.webViewClient = WebViewController()
        return root
    }
}

Откройте файл SlideshowFragment и используйте соответствующий код.

  • Java
  • Kotlin
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.geeksforgeeks.R;
import com.example.geeksforgeeks.WebViewController;
 
public class SlideshowFragment extends Fragment {
 
    private SlideshowViewModel slideshowViewModel;
 
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 
        slideshowViewModel = new ViewModelProvider(this).get(SlideshowViewModel.class);
        View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
 
        WebView webView = root.findViewById(R.id.web_view_contribute);
        webView.loadUrl("https://www.geeksforgeeks.org/contribute/");
        webView.setWebViewClient(new WebViewController());
        return root;
    }
}
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.geeksforgeeks.WebViewController
 
class SlideshowFragment : Fragment() {
 
    private lateinit var slideshowViewModel: SlideshowViewModel
 
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
 
        slideshowViewModel = ViewModelProvider(this).get(SlideshowViewModel::class.java)
        val root: View = inflater.inflate(R.layout.fragment_slideshow, container, false)
 
        val webView = root.findViewById<WebView>(R.id.web_view_contribute)
        webView.loadUrl("https://www.geeksforgeeks.org/contribute/")
        webView.webViewClient = WebViewController()
        return root
    }
}

Теперь вся наша работа завершена, и последняя работа - подключить действие справки к плавающей кнопке в нашем приложении с помощью намерения в файле MainActivity. Для этого используйте следующий код.

  • Java
  • Kotlin
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
 
public class MainActivity extends AppCompatActivity {
 
    private AppBarConfiguration mAppBarConfiguration;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 
        // Code for floating button
        FloatingActionButton fab = findViewById(R.id.fab);
 
        // On click listener is used on floating button
        // to redirect to help activity
        fab.setOnClickListener(view -> {
            // Intent is used to connect help activity to floating button
            Intent activity2Intent = new Intent(getApplicationContext(), help.class);
            startActivity(activity2Intent);
        });
 
        // default code for drawer layout and navigation view
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
 
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
                .setOpenableLayout(drawer)
                .build();
 
        // default code to control the navigation view
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items
        // to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.navigation.NavigationView
 
class MainActivity : AppCompatActivity() {
     
    private lateinit var mAppBarConfiguration: AppBarConfiguration
     
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)
 
        // Code for floating button
        val fab = findViewById<FloatingActionButton>(R.id.fab)
 
        // On click listener is used on floating button
        // to redirect to help activity
        fab.setOnClickListener {
            // Intent is used to connect help activity to floating button
            val activity2Intent = Intent(applicationContext, help::class.java)
            startActivity(activity2Intent)
        }
 
        // default code for drawer layout and navigation view
        val drawer = findViewById<DrawerLayout>(R.id.drawer_layout)
        val navigationView = findViewById<NavigationView>(R.id.nav_view)
 
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = Builder(
            R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
            .setDrawerLayout(drawer)
            .build()
 
        // default code to control the navigation view
        val navController: NavController = Navigation.findNavController(this, R.id.nav_host_fragment)
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration)
        NavigationUI.setupWithNavController(navigationView, navController)
    }
 
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items
        // to the action bar if it is present.
        menuInflater.inflate(R.menu.main, menu)
        return true
    }
 
    override fun onSupportNavigateUp(): Boolean {
        val navController: NavController = Navigation.findNavController(this, R.id.nav_host_fragment)
        return (NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp())
    }
}

Примечание

В MainActivity.java весь код по умолчанию предварительно существует, мы только добавили код intent для связи с Activity помощи через плавающую кнопку.

Результат

Источник

Следующий Предыдущий
Нет комментариев
Добавить комментарий
Ссылка комментария