0% found this document useful (0 votes)
9 views

Part-5-MD-101-Web-View-Auto-Complete-and-Fragments

The document provides a comprehensive guide on mobile application development using Kotlin, focusing on implementing WebView, AutoCompleteTextView, DatePicker, and Fragments. It includes step-by-step instructions for setting up a WebView to load local web applications via XAMPP, configuring AutoCompleteTextView for city suggestions, and utilizing DatePicker for date selection. Additionally, it explains the modularity and lifecycle of fragments in Android, along with practical examples of fragment transactions in an application.

Uploaded by

Aquino Laurence
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Part-5-MD-101-Web-View-Auto-Complete-and-Fragments

The document provides a comprehensive guide on mobile application development using Kotlin, focusing on implementing WebView, AutoCompleteTextView, DatePicker, and Fragments. It includes step-by-step instructions for setting up a WebView to load local web applications via XAMPP, configuring AutoCompleteTextView for city suggestions, and utilizing DatePicker for date selection. Additionally, it explains the modularity and lifecycle of fragments in Android, along with practical examples of fragment transactions in an application.

Uploaded by

Aquino Laurence
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

MD 101 –

Mobile
Application
Development

Development of Application using Kotlin


Programming Language – Web View,
Auto Complete and Fragments
By NCMH
WebView

 In the Palette>Widgets drag and drop a


WebView set the name property
 Drag one Button and one EditText
 In AndroidManifest.xml before the application
tag, write the following codes:
 <uses-permission
android:name="android.permission.INTERNE
T"/>
 In the MainActivity.kt, declare three variables
inside the class MainActivity:
 private lateinit var btnWebView:Button
private lateinit var webText:
private lateinit var
webBrowse:WebEditTextView
WebView Application

 Create a function with listener to our button click event


 private fun openUrl(){
btnWebView = findViewById<Button>(R.id.button2)
webText = findViewById<EditText>(R.id.editTextText)
webBrowse = findViewById<WebView>(R.id.webBrowse)

btnWebView.setOnClickListener{
val url = webText.text.toString()
webBrowse.settings.loadsImagesAutomatically = true
webBrowse.settings.javaScriptEnabled = true
webBrowse.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
webBrowse.loadUrl(url)
}

}
 Don’t forget the calling statement!
WebView Application

 webBrowse.settings.loadsImagesAutomatically = true
 This line sets the loadsImagesAutomatically property of the webBrowse WebView to true. When this property
is true, the WebView will load and display images from web pages.
 webBrowse.settings.javaScriptEnabled = true
 This line sets the javaScriptEnabled property of the webBrowse WebView to true. Enabling JavaScript allows
the WebView to execute JavaScript code on the web page, which is often necessary for interactive and
dynamic web content.
 webBrowse.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
 This line sets the scrollbar style of the webBrowse WebView. It specifies that the scrollbars should appear
inside the content, overlaid on top of the web page content. View.SCROLLBARS_INSIDE_OVERLAY is an
integer constant indicating this style.
 webBrowse.loadUrl(url)
 This line loads a URL (web page) into the webBrowse WebView. The URL to load is provided as the url
variable, which is a string containing the web address.
WebView and Web App in Localhost

 To run your web application in XAMPP and display it in a WebView in Android Studio, follow these
steps:
 Step 1: Set Up XAMPP

1. Install XAMPP: If you haven't already, download and install XAMPP from
the Apache Friends website.

2. Start Apache: Open the XAMPP Control Panel and start the Apache server. This will allow your
local web server to serve files.

3. Place Your Web Application: Copy your web application files (HTML, CSS, JavaScript, etc.)
into the htdocsdirectory of your XAMPP installation. For example, if you created a folder
named mywebapp, the path might look like C:\xampp\htdocs\mywebapp.
 Access Your Web Application: Open a web browser and navigate
to http://localhost/mywebapp to ensure your web application is running properly.
WebView and Web App in Localhost

 Step 2: Configure Android Studio Project

1. Create or Open Your Android Project: Start a new project or open an existing one in
Android Studio.

2. Add Internet Permission: In your AndroidManifest.xml, add the following permission to


allow your app to access the internet:
 <uses-permission android:name="android.permission.INTERNET"/>
WebView and Web App in Localhost

3. Set Up WebView in Layout: In your layout XML file (e.g., activity_main.xml), add
a WebView component:
 xml

 Copy code

 <WebView

 android:id="@+id/webView"
 android:layout_width="match_parent"
 android:layout_height="match_parent"/>
WebView and Web App in Localhost

4. Load Your Web Application in WebView: In super.onCreate(savedInstanceState)


your MainActivity, set up the WebView to load your local
setContentView(R.layout.activity_main)
web application. Here's an example:

import android.os.Bundle
webView = findViewById(R.id.webView)
import android.webkit.WebView
webView.webViewClient = WebViewClient() // To
import android.webkit.WebViewClient
handle navigation
import androidx.appcompat.app.AppCompatActivity

// Load your local web application


class MainActivity : AppCompatActivity() {
webView.loadUrl("http://10.0.2.2/myapp") // Use
private lateinit var webView: WebView 10.0.2.2 to access localhost

override fun onCreate(savedInstanceState: }


Bundle?) {
WebView and Web App in Localhost

 Step 3: Test Your Application

1. Run Your Android App: Connect your Android device or start an emulator and run your
application from Android Studio.

2. Access the Web Application: The WebView should load your web application from
XAMPP using the URL http://192.168.0.2/mywebapp. The IP address 192.168.0.2 is a
special alias that points to localhost when running on an Android emulator.
WebView and Web App in Localhost

 Additional Tips

 If you want to use a physical device, ensure that the device is on the same network as
your computer, and replace 192.168.0.2 with your computer's local IP address (you can
find it using ipconfig on Windows or ifconfig on macOS/Linux).
 If you're accessing the web application via a physical device, make sure your firewall is
configured to allow incoming connections to the Apache server.
 Always check for errors in logcat if the WebView does not load your application as
expected.
AutoCompleteTextView

 In the Palette>Text drag and drop an


AutoCompleteTextView
 Declare two variables in class MainActivity:
 private lateinit var
actView:AutoCompleteTextView

val cities = arrayOf(


"San Carlos",
"Dagupan",
"Alaminos",
"Urdaneta"
)
 arrayOf(...): This is a function used to create an
array in Kotlin. Inside the parentheses, we list
the elements we want to include in the array. In
this case, we have a list of city names as strings.
AutoCompleteTextView Application

 In OnCreate function write the following codes:


 actView = findViewById(R.id.autoCompleteTextView)
val adapter = ArrayAdapter(this, android.R.layout.select_dialog_item, cities)
actView.threshold = 1
actView.setAdapter(adapter)

 val adapter = ArrayAdapter(this, android.R.layout.select_dialog_item, cities)


 Here, we create an ArrayAdapter named adapter.
 It is used to adapt the data from the cities array (or any data source) to the AutoCompleteTextView.
 this refers to the current context, often the activity or fragment where this code is executed.
 android.R.layout.select_dialog_item specifies the layout for each item in the dropdown list.
 cities is the data source you are providing to the adapter.
AutoCompleteTextView Application

 actView.threshold = 1
 This line sets the threshold for showing autocomplete suggestions to 1 character.
 In other words, the autocomplete suggestions will appear when the user types at least one character
in the AutoCompleteTextView.
 actView.setAdapter(adapter)
 This sets the adapter you created earlier as the adapter for the AutoCompleteTextView.
 The adapter is responsible for providing suggestions as the user types in the AutoCompleteTextView.
DatePicker

 Drag a Button and change the text property to “Date Picker”


 Declare the following variables in the class MainActivity:
 private lateinit var btnDatePicker:Button
var yearx: Int = 0
var monthx: Int = 0
var dayx: Int = 0
DatePicker

 Create a method with a listener for the  Create a method to show the DatePicker
event button click:  private fun showDatePickerDialog() {
 private fun showDialogOnButtonClick() { val calendar = Calendar.getInstance()
btnDatePicker.setOnClickListener { val datePickerDialog =
showDatePickerDialog() DatePickerDialog(this, dpickerListener,
} calendar.get(Calendar.YEAR),
} calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
)
datePickerDialog.show()
}
DatePicker

 val calendar = Calendar.getInstance()


 This line creates an instance of the Calendar class and initializes it with the current date and
time. The calendar object is used to configure the initial date for the DatePickerDialog.
 val datePickerDialog = DatePickerDialog(this, dpickerListener, ... )
 This line creates a DatePickerDialog instance, which is a dialog for selecting a date. The
parameters provided include the this reference (which refers to the current Activity or Context),
a listener for when a date is set (dpickerListener), and the initial year, month, and day values.
 datePickerDialog.show()
 This line displays the date picker dialog to the user.
 The selected date will be processed by the dpickerListener, which is defined next to
handle the selected date.
DatePicker

 Create another variable listener to display the selected date into a Toast:
 private val dpickerListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear,
dayOfMonth ->
yearx = year
monthx = monthOfYear
dayx = dayOfMonth
Toast.makeText(this@MainActivity, "$yearx/$monthx/$dayx", Toast.LENGTH_LONG).show()
}

 Write the following codes in OnCreate method:


 btnDatePicker = findViewById(R.id.button3)
showDialogOnButtonClick()
DatePicker

 DatePickerDialog.OnDateSetListener { ... }
 This code initializes the property with a lambda expression. The lambda expression serves as the implementation for
the DatePickerDialog.OnDateSetListener interface.
 Inside the lambda expression:
 { _, year, monthOfYear, dayOfMonth -> ... } : This defines the lambda function. It takes four parameters:
 _ : An underscore, which is a convention to ignore a parameter that you don't intend to use. In this case, it's used to
ignore the first parameter.
 year: The selected year.
 monthOfYear: The selected month (0-based, where 0 is January).
 dayOfMonth: The selected day of the month.
 yearx = year, monthx = monthOfYear, and dayx = dayOfMonth: These lines set the values of the yearx, monthx, and
dayx variables based on the selected date.
 Toast.makeText(this@MainActivity, "$yearx/$monthx/$dayx", Toast.LENGTH_LONG).show(): This line creates a
toast message to display the selected date in the format "YYYY/MM/DD" (year, month, and day) and shows it to
the user. this@MainActivity refers to the current Activity or Context.
Fragment

 In Android development, a "fragment" is a modular and reusable portion of a user interface


(UI) or behavior within an activity. Fragments were introduced to make it easier to create
flexible and responsive user interfaces, particularly for larger screens like tablets, where
multiple UI components may be displayed side by side.
 Fragments in Android provide a way to create modular, reusable, and flexible components for
building user interfaces. They are particularly useful in situations where you need to create
responsive layouts for various screen sizes and orientations.
Here are some key points about
fragments in Android:

1. Modularity: Fragments represent a portion of an activity's UI or behavior. By breaking the UI into


smaller, independent fragments, you can create more modular and maintainable code.
2. Reusability: Fragments can be reused in multiple activities. This allows developers to create
components that can be shared across different parts of an application.
3. Lifecycle: Fragments have their own lifecycle, similar to activities. They go through states such as
onCreate(), onStart(), onResume(), etc. This allows developers to manage UI and behavior
independently within the fragment.
4. Interaction with Activities: Fragments can be dynamically added or removed from an activity at
runtime. They can also communicate with the hosting activity, enabling a flexible and responsive
user interface.
5. Layout: Fragments have their own layout files, defining the UI components they contain. These
layouts can be combined to create the overall UI of the activity.
6. Back Stack: Fragments can be managed on a back stack, allowing for easy navigation and transition
between different states of the UI within a single activity.
Fragment
Fragment Application

 fun changeFragment(view: View){


var fragment: Fragment
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()

if(view == findViewById(R.id.button)){
fragment = FragmentOne()
fragmentTransaction.replace(R.id.fragmentContainerView, fragment)
fragmentTransaction.commit()
}
if(view == findViewById(R.id.button2)){
fragment = FragmentTwo()
fragmentTransaction.replace(R.id.fragmentContainerView, fragment)
fragmentTransaction.commit()
}
}
Fragment Application

Variable Declaration:
1. var fragment: Fragment
- Declares a variable to hold a reference to the fragment that will be displayed.
2. val fragmentManager = supportFragmentManager
- Retrieves the FragmentManager associated with the hosting activity. The
supportFragmentManager is used for activities that extend AppCompatActivity.
3. val fragmentTransaction = fragmentManager.beginTransaction()
- Begins a new fragment transaction. This transaction will be used to replace the current
fragment.
Fragment Application

Fragment Replacement:
1. If the first button is clicked (R.id.button), it creates an instance of FragmentOne,
replaces the current fragment in the specified container
(R.id.fragmentContainerView) with FragmentOne, and commits the transaction.
2. If the second button is clicked (R.id.button2), it creates an instance of
FragmentTwo, replaces the current fragment in the specified container with
FragmentTwo, and commits the transaction.

You might also like