tag:blogger.com,1999:blog-75802378167350713242024-03-27T18:33:08.927-07:00AndroidA plat with simple tutorial for native android developers.Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.comBlogger66125tag:blogger.com,1999:blog-7580237816735071324.post-56279175825756233102020-06-29T00:12:00.004-07:002021-08-29T08:34:34.068-07:00Exploring LayoutInflater#inflate method | Android | V4ALL<h2>Good day!!!</h2>
<br />
<div>
As a Android developer we all have experienced
<a
href="https://developer.android.com/reference/android/view/LayoutInflater#inflate(int,%20android.view.ViewGroup,%20boolean)"
>LayoutInflater#inflate</a
>
at some point. But we maynot know clearly what this function will do. Come on,
stay attention, Let's explore this in this blog with simple examples!!!
</div>
<br />
<div>Let's assume you have a layout named fragment_first.xml as following</div>
<pre class="prettyprint lang-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"
tools:context=".FirstFragment">
<TextView
android:id="@+id/textView"
style="@style/TextAppearance.MaterialComponents.Headline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorAccent"
android:gravity="center"
android:text="@string/app_name"
android:textColor="@color/colorPrimary"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</pre>
<br />
<div>And you have test_layout.xml as following</div>
<pre class="prettyprint lang-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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/buttonTest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</pre>
<div>
As you know you can include the test_layout.xml programatically by following
way
</div>
<pre class="prettyprint lang-java">
val testLayout = LayoutInflater.from(requireContext()).inflate(R.layout.test_layout, view as ConstraintLayout, true)
</pre>
<div>If you run the app, you will get following output.</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a
href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2tJ2JqR5aNWA3oSzgO4dIRMkOAQdSnvGXPLGLQo91lJLwYUT9u6iSamz1nG5hWI4j0wiLeQrtN8huMYDJGq2T7brETSPTTrV7LiXUAgziHFdtRMW83tVeLpJ9ZhNghUOVL5_QgZ6apvBf/s2532/Inf1.png"
imageanchor="1"
><img
border="0"
data-original-height="2532"
data-original-width="1330"
height="320"
src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh2tJ2JqR5aNWA3oSzgO4dIRMkOAQdSnvGXPLGLQo91lJLwYUT9u6iSamz1nG5hWI4j0wiLeQrtN8huMYDJGq2T7brETSPTTrV7LiXUAgziHFdtRMW83tVeLpJ9ZhNghUOVL5_QgZ6apvBf/s320/Inf1.png"
/></a>
</div>
<br />
<div>
As per
<a
href="https://developer.android.com/reference/android/view/LayoutInflater#inflate(int,%20android.view.ViewGroup,%20boolean)"
>LayoutInflater#inflate</a
>
recieves following parameters.
<dl style="background-color: #030303; color: #bdb76b; padding: 10px; border-radius: 8px;">
<dt>resource</dt>
<dd>
- int:ID for an XML layout resource to load (e.g., R.layout.main_page)
</dd>
<dt>root</dt>
<dd>
- ViewGroup: Optional view to be the parent of the generated hierarchy (if
attachToRoot is true), or else simply an object that provides a set of
LayoutParams values for root of the returned hierarchy (if attachToRoot is
false.) This value may be null
</dd>
<dt>attachToRoot</dt>
<dd>
- boolean: Whether the inflated hierarchy should be attached to the root
parameter? If false, root is only used to create the correct subclass of
LayoutParams for the root view in the XML.
</dd>
</dl>
and returns
<dl style="background-color: #030303; color: #bdb76b; padding: 10px; border-radius: 8px;">
<dt>View</dt>
<dd>
- The root View of the inflated hierarchy. If root was supplied and
attachToRoot is true, this is root; otherwise it is the root of the
inflated XML file.
</dd>
</dl>
Ofcourse, the first parameter <b>resource</b> is easily understable and we
know why this parameter is required and what should we passed. <br />But the
second and third parameters are bit confusing, we are not clear what should we
pass, in each condition what will happen. Let's explore this. <br /><br />
They are saying second parameter is optional, if third parameter is true, the
first parameter will be child of second parameter. That's all, the second
parameter is depend on third parameter, but its not necessory at all, but you
can pass either true/false in third parameter at the same time you can pass
rootview/null in second parameter, nothing will happen, app will not get
crashed, no exception will be thrown.
</div>
<div>
But if you know this clearly, you can code easily on your requirement. If you
want the first paramenter as child of your second parameter, note that the
first parameter will be added based on your second parameter's
<a
href="https://developer.android.com/reference/android/view/ViewGroup.LayoutParams"
>LayoutParams</a
>
For example, in the above layouts, both are constraint layout, and both has
width and height as <b>match_parent</b>.<br />
<br />
Let's set some background color for test_layout, ex:
<pre class="prettyprint lang-xml">
android:background="@android:color/holo_orange_light"</pre
>
<div>Run the app, you will get following output.</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a
href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzRkR_6-dkjhvYxuO_9YUpvbojmSy-jeRgktef6hqh5_dxCJmwOKvGlZ5EoXqw-DcYzzfLbVvI0lpEice2Hrd9nxUP6CpD3Q9IJKrtF095SZ57TGumDwPSMc1G-IM1GF_Hub2mjcXQyH1G/s2532/inf2.png"
imageanchor="1"
style="margin-left: 1em; margin-right: 1em;"
><img
border="0"
data-original-height="2532"
data-original-width="1330"
height="320"
src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzRkR_6-dkjhvYxuO_9YUpvbojmSy-jeRgktef6hqh5_dxCJmwOKvGlZ5EoXqw-DcYzzfLbVvI0lpEice2Hrd9nxUP6CpD3Q9IJKrtF095SZ57TGumDwPSMc1G-IM1GF_Hub2mjcXQyH1G/s320/inf2.png"
/></a>
</div>
Ofcourse the TextView is not visible in output, but note that, its accessible,
see the toast which appeared tap on TextView.
</div>
<div>
Another example, let's change fragment_first.xml to LinearLayout and set
orientation as vertical.
<pre class="prettyprint lang-java">
val testLayout = LayoutInflater.from(requireContext()).inflate(R.layout.test_layout, view as LinearLayout, true)</pre
>
Run the app, you will get following output.<br /><br />
<div class="separator" style="clear: both; text-align: center;">
<a
href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-qvtT4N1dnNfvnt9Sr4_9UWA9Le4hg5WOSMUWU4ZW1QVCfzHk9VMUvchgSJBAxfHaNtcIDxiwi1FiHwi-N5He67ly1LjFLwwwI9ZFNQZbF1NGLiRZ2SpYi_UAsHGQsKdJY3rAvhhPqUZm/s2532/inf3.png"
imageanchor="1"
style="margin-left: 1em; margin-right: 1em;"
><img
border="0"
data-original-height="2532"
data-original-width="1330"
height="320"
src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-qvtT4N1dnNfvnt9Sr4_9UWA9Le4hg5WOSMUWU4ZW1QVCfzHk9VMUvchgSJBAxfHaNtcIDxiwi1FiHwi-N5He67ly1LjFLwwwI9ZFNQZbF1NGLiRZ2SpYi_UAsHGQsKdJY3rAvhhPqUZm/s320/inf3.png"
/></a>
</div>
</div>
<div>
I hope, now you understand, why the second and third parameters required and
what they are doing. If you have any doubts, please share as comment. <br /><br />Also
note that
<a
href="https://developer.android.com/reference/android/view/LayoutInflater#inflate(int,%20android.view.ViewGroup,%20boolean)"
>LayoutInflater#inflate</a
>
returns a View, this is nothing but, if you pass second one as a layout and
third parameter as true then its the current root view. <br /><br />If you pass second one as null or third one as false, it is the
root view of currently inflated layout, you can use it in
<a href="https://developer.android.com/guide/topics/ui/layout/recyclerview"
>RecyclerView</a
>,
<a
href="https://developer.android.com/reference/android/widget/PopupWindow#PopupWindow(android.view.View,%20int,%20int)"
>PopupWindow</a
>
or some other component which expcets rootview as parameter.
</div>
<br />
<div style="text-align: center;">Thank You, Share your thought as comments. <br /></div>Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com1tag:blogger.com,1999:blog-7580237816735071324.post-81091845990548914662020-06-26T01:35:00.021-07:002020-06-26T23:48:06.996-07:00Exploring Kotlin's LiveData | Part I | Android | V4ALL<h2>Good day!!!</h2><br />
<div>As Per <a href="https://developer.android.com/topic/libraries/architecture/livedata.html" rel="nofollow" target="_blank">Android Developer</a> documentation, <a href="https://developer.android.com/reference/androidx/lifecycle/LiveData" rel="nofollow" target="_blank">LiveData</a> is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.</div>
<div><br /></div>
<div>Let's explore this statement with an simple example.</div>
<div><br /></div>
<div>Create our own observer which notifies if any changes available in an <span style="color:tomato;"><b>username</b>.</span></div><div><br /></div>
<div>Create a Basic Application in Android Studio using <b style="color:tomato;">File → New → New Project</b> and Choose <b style="color:tomato;">Basic Activity</b> template. <span style="color:tomato;">[I used Android Studio 4.0]</span>, and finish project setup.</div>
<div><span style="background-color: white; color: #202124; font-family: roboto, "noto sans", "noto sans jp", "noto sans kr", "noto naskh arabic", "noto sans thai", "noto sans hebrew", "noto sans bengali", sans-serif; font-size: 16px;"><br /></span></div>
<div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh89TZh8gNrLvI5tf4asbvn2a0rYvsHM-5nhd7r1q5Ccho8m2WmSAXqTi5LYqtP-EL_WOhX7M301AJVfbXdxNnymQp73VLCwJZsAjpufhYZT-Q6vR9ISveTZ6D2rY2yfvRr0XXvK_lXz5Vm/s902/Basic+Application.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="646" data-original-width="902" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh89TZh8gNrLvI5tf4asbvn2a0rYvsHM-5nhd7r1q5Ccho8m2WmSAXqTi5LYqtP-EL_WOhX7M301AJVfbXdxNnymQp73VLCwJZsAjpufhYZT-Q6vR9ISveTZ6D2rY2yfvRr0XXvK_lXz5Vm/s320/Basic+Application.png" width="320" /></a></div></div>
<div><br /></div>
<div>Create a kotlin file and name it as <span style="color:tomato;"><b>UserModel.kt</b></span> and copy paste following codes,</div>
<pre class="prettyprint lang-java">package com.example.basicapplication
interface UserObserver {
fun onUsernameChanged(username: String)
}
object UserHolder {
private var username: String = ""
private val userObservers = mutableSetOf<userobserver>()
fun addObservers(observer: UserObserver) {
userObservers.add(observer)
}
fun setUsername(username: String) {
this.username = username
userObservers.forEach { it.onUsernameChanged(username) }
}
}</pre>
<div>Replace the <span style="color:tomato;"><b>first_fragment.xml</b></span> with following content,</div>
<pre class="prettyprint lang-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"
tools:context=".FirstFragment">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/tlUsername"
app:errorEnabled="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/username"
app:layout_constraintBottom_toTopOf="@id/btnSet"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="@+id/btnSet"
style="@style/Widget.MaterialComponents.Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/set_value"
app:layout_constraintBottom_toTopOf="@+id/button_first"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/tlUsername" />
<Button
android:id="@+id/button_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/next"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/btnSet" />
</androidx.constraintlayout.widget.ConstraintLayout>
</pre>
Replace the <span style="color: tomato;"><b>FirstFragment.kt</b></span> with following content,
<pre class="prettyprint lang-java">package com.example.basicapplication
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import kotlinx.android.synthetic.main.fragment_first.*
class FirstFragment : Fragment(), UserObserver {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_first, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
UserHolder.addObservers(this)
btnSet.setOnClickListener {
val userName = tlUsername.editText?.text.toString()
if (userName.isEmpty()) {
tlUsername.error = "Please enter username"
return@setOnClickListener
}
UserHolder.setUsername(userName)
}
button_first.setOnClickListener {
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
}
}
override fun onUsernameChanged(username: String) {
val userName = tlUsername.editText?.text.toString()
if (userName.isEmpty()) {
tlUsername.error = "Please enter username"
return
}
Toast.makeText(requireContext(), "$userName : From FirstFragment", Toast.LENGTH_LONG).show()
}
}
</pre>
Replace the <span style="color: tomato;"><b>second_fragment.xml</b></span> with following content,
<pre class="prettyprint lang-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"
tools:context=".SecondFragment">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/tlUsername"
app:errorEnabled="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/username"
app:layout_constraintBottom_toTopOf="@id/btnSet"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="@+id/btnSet"
style="@style/Widget.MaterialComponents.Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/set_value"
app:layout_constraintBottom_toTopOf="@+id/button_second"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/tlUsername" />
<Button
android:id="@+id/button_second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/previous"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/btnSet" />
</androidx.constraintlayout.widget.ConstraintLayout>
</pre>
Replace the <span style="color: tomato;"><b>SecondFragment.kt</b></span> with following content,
<pre class="prettyprint lang-java">package com.example.basicapplication
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import kotlinx.android.synthetic.main.fragment_second.*
import kotlinx.android.synthetic.main.fragment_second.btnSet
import kotlinx.android.synthetic.main.fragment_second.tlUsername
class SecondFragment : Fragment(), UserObserver {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_second, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
UserHolder.addObservers(this)
btnSet.setOnClickListener {
val userName = tlUsername.editText?.text.toString()
if (userName.isEmpty()) {
tlUsername.error = "Please enter username"
return@setOnClickListener
}
UserHolder.setUsername(userName)
}
button_second.setOnClickListener {
findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
}
}
override fun onUsernameChanged(username: String) {
val userName = tlUsername.editText?.text.toString()
if (userName.isEmpty()) {
tlUsername.error = "Please enter username"
return
}
Toast.makeText(requireContext(), "$userName : From FirstFragment", Toast.LENGTH_LONG).show()
}
}
</pre>
Now run your app, and if you test like following video, app will get crashed with report <span style="color: tomato;"><b>java.lang.IllegalStateException: tlUsername must not be null on FirstFragment</b></span>, because our observer notifies FirstFragment which is dead while we are in SecondFragment,
<div><br /></div>
<div> <iframe allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/e1oA7EajjCU" width="560"></iframe> </div><div><br /></div><div><br /></div>
Ofcourse we can handle this manually in several ways, but we can simply fix this crash by using LiveData as following way,
<br />
Just Replace the <span style="color: tomato;"><b>UserModel.kt</b></span> with following content,
<pre class="prettyprint lang-java">import androidx.lifecycle.MutableLiveData
var username = MutableLiveData<String>()
get() = field
set(value) {field = value}
</pre>
And Your <span style="color: tomato;"><b>FirstFragment.kt</b></span> will be
<pre class="prettyprint lang-java">package com.example.basicapplication
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import kotlinx.android.synthetic.main.fragment_first.*
class FirstFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_first, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btnSet.setOnClickListener {
val userName = tlUsername.editText?.text.toString()
if (userName.isEmpty()) {
tlUsername.error = "Please enter username"
return@setOnClickListener
}
username.value = userName
}
username.observe(viewLifecycleOwner, Observer {
Toast.makeText(requireContext(), "$it : From FirstFragment", Toast.LENGTH_LONG).show()
})
button_first.setOnClickListener {
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
}
}
}
</pre>
And Your <span style="color: tomato;"><b>SecondFragment.kt</b></span> will be
<pre class="prettyprint lang-java">package com.example.basicapplication
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import kotlinx.android.synthetic.main.fragment_second.*
import kotlinx.android.synthetic.main.fragment_second.btnSet
import kotlinx.android.synthetic.main.fragment_second.tlUsername
class SecondFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_second, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btnSet.setOnClickListener {
val userName = tlUsername.editText?.text.toString()
if (userName.isEmpty()) {
tlUsername.error = "Please enter username"
return@setOnClickListener
}
username.value = userName
}
username.observe(viewLifecycleOwner, Observer {
Toast.makeText(requireContext(), "$it : From SecondFragment", Toast.LENGTH_LONG).show()
})
button_second.setOnClickListener {
findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
}
}
}
</pre>
Run the application now, and you will see the output without any crash like following video.
<div><br /></div>
<div>
<iframe allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/nszOGOzbS44" width="560"></iframe>
</div>
<div><br /></div>
<div style="text-align: center;">Thank You, Share your thought as comments. <br /></div>Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com1tag:blogger.com,1999:blog-7580237816735071324.post-74027079326024523192018-11-14T08:04:00.009-08:002020-06-24T03:26:01.220-07:00Simple example of heads-up notification in Android<div dir="ltr" style="text-align: left;" trbidi="on">
Beginning with Android 5.0, notifications can briefly appear in a floating window called a heads-up notification. This behavior is normally for important notifications that the user should know about immediately, and it appears only if the device is unlocked.<br /><br />
The heads-up notification appears the moment your app issues the notification and it disappears after a moment, but remains visible in the notification drawer as usual.<br /><br />
Example conditions that might trigger heads-up notifications include the following:
<ul>
<li>The user's activity is in fullscreen mode (the app uses <a href="https://developer.android.com/reference/android/app/Notification#fullScreenIntent">fullScreenIntent</a>).</li>
<li>The notification has high priority and uses ringtones or vibrations on devices running Android 7.1 (API level 25) and lower.</li>
<li>The notification channel has high importance on devices running Android 8.0 (API level 26) and higher.</li>
</ul>
Here is the sample code
<pre class="prettyprint lang-java">
private fun sendNotification() {
var notifyManager: NotificationManager? = null
val NOTIFY_ID = 1002
val name = "KotlinApplication"
val id = "kotlin_app"
val description = "kotlin_app_first_channel"
val intent: Intent
val pendingIntent: PendingIntent
val builder: NotificationCompat.Builder
if (notifyManager == null) {
notifyManager = activity!!.getSystemService(Context.NOTIFICATION_SERVICE)
as NotificationManager
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_HIGH
var mChannel = notifyManager.getNotificationChannel(id)
if (mChannel == null) {
mChannel = NotificationChannel(id, name, importance)
mChannel.description = description
mChannel.enableVibration(true)
mChannel.lightColor = Color.GREEN
mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
notifyManager.createNotificationChannel(mChannel)
}
}
builder = NotificationCompat.Builder(activity!!, id)
intent = Intent(activity, MainActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0)
builder.setContentTitle("Heads Up Notification") // required
.setSmallIcon(android.R.drawable.ic_popup_reminder) // required
.setContentText(getString(R.string.app_name)) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker("Notification")
.setVibrate(longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400))
val dismissIntent = Intent(activity, MainActivity::class.java)
dismissIntent.action = "DISMISS"
dismissIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
val pendingDismissIntent = PendingIntent.getActivity(activity, 0, dismissIntent,
PendingIntent.FLAG_UPDATE_CURRENT)
val dismissAction = NotificationCompat.Action(R.drawable.ic_baseline_notification_important_24px,
"DISMISS", pendingDismissIntent)
builder.addAction(dismissAction)
val notification = builder.build()
notifyManager.notify(NOTIFY_ID, notification)
}
</pre>
The above code will produce the following output.<br /><br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEipnefUNjbFQf2F9TqU_ZN2b67AtK_qDb8gyiCpptgBJ1HV6U3qdbCuw3cHG70hoMGoLHwqpqRMX0-QVSPxxI1eTRjLfTtruaMXtuA5DxUnb0hk0ei_DDGQKF39UDuPNoUAsih2yNO3MGAp/s1600/device-2018-11-30-141553.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEipnefUNjbFQf2F9TqU_ZN2b67AtK_qDb8gyiCpptgBJ1HV6U3qdbCuw3cHG70hoMGoLHwqpqRMX0-QVSPxxI1eTRjLfTtruaMXtuA5DxUnb0hk0ei_DDGQKF39UDuPNoUAsih2yNO3MGAp/s320/device-2018-11-30-141553.png" width="159" height="320" data-original-width="794" data-original-height="1600" /></a></div><br />
If you want add notification badge(Dot notification) to launcher icon like this, <br /><br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhY0-pBgFRwmZyGPwR-WvT6hN4wUB-5bXisFR6qylbYiuuzj637PlcS3pjN8BELCW3Z2BJ1ptWiBD3HyFXqvD_6vY4g1RqQ50RFMfSPIWnND8w4Z4sYb6ePYzHhtygoqPJ3Sz8yPkpCTwb3/s1600/device-2018-11-30-141640.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhY0-pBgFRwmZyGPwR-WvT6hN4wUB-5bXisFR6qylbYiuuzj637PlcS3pjN8BELCW3Z2BJ1ptWiBD3HyFXqvD_6vY4g1RqQ50RFMfSPIWnND8w4Z4sYb6ePYzHhtygoqPJ3Sz8yPkpCTwb3/s320/device-2018-11-30-141640.png" width="320" height="234" data-original-width="1194" data-original-height="872" /></a></div><br />
you have add following line before <b>createNotificationChannel</b>.
<pre class="prettyprint lang-java">
mChannel.setShowBadge(true)
</pre>
And Here is the full video tutorial.
<p align="center">
<iframe width="560" height="315" src="https://www.youtube.com/embed/xeCBZhfwbWY" frameborder="0" gesture="media" allowfullscreen></iframe>
</p>
<h3>Interesting right?</h3>
If you are really interested in this code, then please share this post with your friends and share your feedback as comments.
<h3 style="text-align: center;">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-15370438087270879982018-10-11T04:16:00.000-07:002018-10-12T03:19:09.438-07:00Simple example of DraggableTextView in Android | Kotlin<div dir="ltr" style="text-align: left;" trbidi="on">Hello All, By using simple onTouch event we make an DraggableTextView widget.
<br />Here is the code sample for you.
<br />
<pre class="prettyprint lang-java">
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
val x = event?.rawX?.toInt()!!
val y = event.rawY.toInt()
when (event.action) {
MotionEvent.ACTION_DOWN -> {
val layoutParams = layoutParams as ConstraintLayout.LayoutParams
xDelta = x - layoutParams.leftMargin
yDelta = y - layoutParams.topMargin
rect.set(0, 0, width, height)
isDragging = true
}
MotionEvent.ACTION_MOVE -> {
val layoutParams = layoutParams as ConstraintLayout.LayoutParams
layoutParams.leftMargin = x - xDelta
layoutParams.topMargin = y - yDelta
setLayoutParams(layoutParams)
}
MotionEvent.ACTION_UP -> {
isDragging = false
}
}
invalidate()
return true
}
</pre>
<br />Here is the full video tutorial.
<p align="center">
<iframe width="560" height="315" src="https://www.youtube.com/embed/Nbqrmx0CMsM" frameborder="0" gesture="media" allowfullscreen></iframe>
</p>
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then please share this post with your friends and share your feedback as comments.
<br />
<h3 style="text-align: center;">
<br />
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-5012755951390982052018-10-05T03:20:00.000-07:002018-10-05T03:20:42.417-07:00Using shuffle from Collections in Java | Android<div dir="ltr" style="text-align: left;" trbidi="on">
From <a href="https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)">Doc</a> shuffle is used to Randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.<br /><br />
Here is the simple example of shuffle from collections.
<pre class="brush: java">
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i <= 10; i++) {
numbers.add(i);
}
Log.v(TAG, "Original List: " + numbers.toString());
Collections.shuffle(numbers);
Log.v(TAG, "Shuffled List: " + numbers.toString());
</pre>
<b>Output:</b><br />
<pre class="brush: java">
Original List: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Shuffled List: [2, 10, 0, 3, 7, 5, 1, 9, 8, 6, 4]
</pre>
There is also <a href="https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List,%20java.util.Random)">public static void shuffle(List<?> list, Random rnd)</a> which will Randomly permute the specified list using the specified source of randomness.
<h3>
Interesting right?</h3>
If you are really interested in this example, then please share this post with your friends, also share your feedback as comment here.
<h3 style="text-align: center;">
<br />
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com1tag:blogger.com,1999:blog-7580237816735071324.post-56513301550211427042018-07-22T19:08:00.000-07:002018-07-22T19:08:04.203-07:00Simple example of using Firebase Cloud Messaging in Android | Kotlin<div dir="ltr" style="text-align: left;" trbidi="on">
Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost.<br /><br />
You can send notification messages to drive user re-engagement and retention.<br /><br />
To write your Firebase Cloud Messaging Android client app, use the <a href="https://firebase.google.com/docs/reference/android/com/google/firebase/messaging/package-summary?authuser=0">FirebaseMessaging</a> API and Android Studio 1.4 or higher with Gradle.<br /><br />
FCM clients require devices running Android 4.0 or higher that also have the Google Play Store app installed, or an emulator running Android 4.0 with Google APIs. Note that you are not limited to deploying your Android apps through Google Play Store.<br />
<h3>Set up Firebase and the FCM SDK</h3>
* If you haven't already, <a href="https://firebase.google.com/docs/android/setup?authuser=0">add Firebase to your Android project</a>.<br />
* In Android Studio, add the FCM dependency to your app-level build.gradle file:
<pre class="brush: java">implementation 'com.google.firebase:firebase-messaging:17.1.0'</pre><br />
Create a Service that extends FirebaseMessagingService.<br /><br />
Here is the full code of <b>FCMService.kt</b>
<pre class="brush: java">
class FCMService : FirebaseMessagingService() {
override fun onNewToken(s: String?) {
super.onNewToken(s)
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
}
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
super.onMessageReceived(remoteMessage)
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be: https://goo.gl/39bRNJ
Log.d(TAG, "From: " + remoteMessage!!.from!!)
// Check if message contains a data payload.
if (remoteMessage.data.size > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.data)
}
// Check if message contains a notification payload.
if (remoteMessage.notification != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.notification!!.body!!)
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
companion object {
private val TAG = "FCMService"
}
}
</pre>
Define this service in Manifest as follows.
<pre class="brush: xml">
<service android:name=".FCMService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
See README(https://goo.gl/l4GJaQ) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@mipmap/ic_launcher_round" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message. See README(https://goo.gl/6BKBk7) for more. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/colorAccent" />
</service>
</pre>
Get firebase tokan as follows in your MainActivity.
<pre class="brush: java">
FirebaseInstanceId.getInstance().instanceId
.addOnCompleteListener(OnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(TAG, "getInstanceId failed", task.exception)
return@OnCompleteListener
}
// Get new Instance ID token
val token = task.result.token
// Log and toast
val msg = getString(R.string.msg_token_fmt, token)
Log.d(TAG, msg)
Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
})
</pre>
By default, your app can be notified by package id, If you want to get notified by Topic something like, News, Cinema then subscribe for a topic like follows,
<pre class="brush: java">
//Subscription to the topic News
FirebaseMessaging.getInstance().subscribeToTopic("News")
.addOnCompleteListener { task ->
var msg = getString(R.string.msg_subscribed)
if (!task.isSuccessful) {
msg = getString(R.string.msg_subscribe_failed)
}
Log.d(TAG, msg)
Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()
}
<br /></div>
</pre>
<h3>Interesting right?</h3>
If you are really interested in this example, then please share this post with your friends, also share your feedback as comment here.
<br />
<h3 style="text-align: center;"><br />
<br /><br /><a href="https://github.com/GunaseelanArumaikkannu/FCMExample" target="_blank" class="btn">Source code on GitHub</a><br /><br />
<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="83SNHDTB99JP8">
<input type="submit" name="submit" value="Donate" class="btn"/>
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b><span style="color: blue;">Thank You</span></b></h3>Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com1tag:blogger.com,1999:blog-7580237816735071324.post-90944155927663258422018-07-11T01:30:00.003-07:002021-05-21T19:59:34.976-07:00Simple example of using BottomSheetDialog in Android | Kotlin<div dir="ltr" style="text-align: left;" trbidi="on">
<a href="https://developer.android.com/reference/com/google/android/material/bottomsheet/BottomSheetDialog">BottomSheetDialog</a> is simple dialog styled as bottom sheet.<br /><br />
BottomSheetDialog implementation is quite simpler and easier than normal Dilaogs. You can just attach view for it and then display it.
<br /><br />
Here is simple example. This tutorial is developed using kotlin. <br />
<b>MainActivity.kt</b>
<pre class="prettyprint lang-java">
val dialog = BottomSheetDialog(this)
val bottomSheet = layoutInflater.inflate(R.layout.bottom_sheet, null)
bottomSheet.buttonSubmit.setOnClickListener { dialog.dismiss() }
dialog.setContentView(bottomSheet)
dialog.show()
</pre>
<b>bottom_sheet.xml</b>
<pre class="prettyprint lang-xml">
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/bottomSheet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="@+id/textMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is the BottomSheetDialog, you can use this instead of normal Dialogs."
android:textColor="#000"
android:textSize="16sp"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/buttonSubmit"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="OKAY"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textMessage" />
</android.support.constraint.ConstraintLayout>
</pre>
<b>Screenshots</b><br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1tF_Iuoot_WSRqsiMloaSlxmpMgapQUkly7TGrY4GteGcbPxDVF5YfrQvw7NbiqFl9lta9xfH6IsSOxdg8ynnBKBlIvX-QlWJc7iOnvym7j2e0cw4DBIV6DZ2Eh4UGRRUJl5i8IgS-hLN/s1600/device-2018-07-11-135833.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1tF_Iuoot_WSRqsiMloaSlxmpMgapQUkly7TGrY4GteGcbPxDVF5YfrQvw7NbiqFl9lta9xfH6IsSOxdg8ynnBKBlIvX-QlWJc7iOnvym7j2e0cw4DBIV6DZ2Eh4UGRRUJl5i8IgS-hLN/s320/device-2018-07-11-135833.png" width="159" height="320" data-original-width="794" data-original-height="1600" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj1H9l6L0fHwxSW181-IVvZNAIBwFoa-PKWnElwrWtIS2sl3F31nW2K_A-9BSX5i3AqY9L4R_-8L1QCNE6OvG4oHaOa4btXN-hCX3K-DgZw7iwUi-VSTxKGhs2sMPTY3sDa5Y-RlPB7Y1Oz/s1600/device-2018-07-11-135915.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj1H9l6L0fHwxSW181-IVvZNAIBwFoa-PKWnElwrWtIS2sl3F31nW2K_A-9BSX5i3AqY9L4R_-8L1QCNE6OvG4oHaOa4btXN-hCX3K-DgZw7iwUi-VSTxKGhs2sMPTY3sDa5Y-RlPB7Y1Oz/s320/device-2018-07-11-135915.png" width="159" height="320" data-original-width="794" data-original-height="1600" /></a></div>
<h3>Interesting right?</h3>
<br />
If you are really interested in this example, then please share this post with your friends, also share your feedback as comment here.
<br />
<h3 style="text-align: center;"><br />
<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="83SNHDTB99JP8">
<input type="submit" name="submit" value="Donate" class="btn"/>
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com5tag:blogger.com,1999:blog-7580237816735071324.post-41397915492994163192018-07-10T23:31:00.001-07:002018-07-10T23:31:56.754-07:00Simple example of using BottomSheetBehavior in Android | Kotlin<div dir="ltr" style="text-align: left;" trbidi="on">
BottomSheetBehavior is An interaction behavior plugin for a child view of CoordinatorLayout to make it work as a bottom sheet. Bottom sheet is something like sliding a view from bottom to top, you may already seen this design in Google Play Music or VLC media player app. <br />
Here is the simple example of using <a href="https://developer.android.com/reference/android/support/design/widget/BottomSheetBehavior">BottomSheetBehavior</a> in Android, code is developed in Kotlin.
<b>MainActivity.kt</b><br />
<pre class="brush: java">
val bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet)
bottomSheetBehavior.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
override fun onStateChanged(bottomSheet: View, newState: Int) {
when (newState) {
BottomSheetBehavior.STATE_EXPANDED -> {
textBottom.text = getString(R.string.slide_down)
//textFull.visibility = View.VISIBLE
}
BottomSheetBehavior.STATE_COLLAPSED -> {
textBottom.text = getString(R.string.slide_up)
//textFull.visibility = View.GONE
}
}
}
override fun onSlide(bottomSheet: View, slideOffset: Float) {
}
})
</pre>
Bottom sheet view should be one of the child of CoordinatorLayout like following code sample.<br />
<b>activity_main.xml</b>
<pre class="brush: xml">
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
<include layout="@layout/bottom_sheet" />
</android.support.design.widget.CoordinatorLayout>
</pre>
<b>content_main.xml</b>
<pre class="brush: xml">
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</pre>
<b>bottom_sheet.xml</b>
<pre class="brush: xml">
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:id="@+id/bottomSheet"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:behavior_hideable="false"
app:behavior_peekHeight="58dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
tools:showIn="@layout/activity_main">
<TextView
android:id="@+id/textBottom"
android:layout_width="match_parent"
android:layout_height="58dp"
android:background="#f1f1f1"
android:gravity="center"
android:text="Slide Up"
android:textColor="@color/colorAccent"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textFull"
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="#e1e1e1"
android:gravity="center"
android:text="Full View"
android:textColor="@color/colorAccent"
android:textSize="22sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textBottom" />
</android.support.constraint.ConstraintLayout>
</pre>
Here is the video output of this source code<br />
<iframe width="560" height="315" src="https://www.youtube.com/embed/NvvUPAGZRLw" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe><br /><br />
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then please share this post with your friends, also share your feedback as comment here.
<br />
<h3 style="text-align: center;"><br />
<br /><br /><a href="https://github.com/GunaseelanArumaikkannu/BottomSheetExample" target="_blank" class="btn">Source code on GitHub</a><br /><br />
<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="83SNHDTB99JP8">
<input type="submit" name="submit" value="Donate" class="btn"/>
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-22743497746347193002018-07-09T22:17:00.000-07:002018-07-09T22:18:22.754-07:00Dynamic Grid Count in GridLayoutManager using RecyclerView | Android | Kotlin<div dir="ltr" style="text-align: left;" trbidi="on">
Sometime we need RecyclerView filled with dynamic row count. For example, some row has 3 columns, and some has 2 columns, and some should have only one column like that.<br />
Here is the simple example of dynamic grid count using GridLayoutManager in RecyclerView.
<br />
<pre class="brush: java">
val layoutManager = GridLayoutManager(this, 6)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
when (position) {
0, 1, 2, 6, 7, 8, 12, 13, 14, 18, 19, 20 -> return 2
3, 4, 9, 10, 15, 16, 21, 22, 24, 25 -> return 3
5, 11, 17, 23 -> return 6
else -> return 2
}
}
}
recyclerView.layoutManager = layoutManager
</pre>
<b>Screenshot:</b>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4Lm7YD7motfb78LLJXZHBfO4InyC_-oK02yhmom_wvb5o0T_jrNuPR0jyA46EqhVwOPcbyxC-9VnLUwL84bGGi0I3UlI8zIIypBlepC3OCNnjM8gtRCoVR4CuoGeD4Bhht7rmqMvGjjTN/s1600/Screenshot_1531199591.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi4Lm7YD7motfb78LLJXZHBfO4InyC_-oK02yhmom_wvb5o0T_jrNuPR0jyA46EqhVwOPcbyxC-9VnLUwL84bGGi0I3UlI8zIIypBlepC3OCNnjM8gtRCoVR4CuoGeD4Bhht7rmqMvGjjTN/s320/Screenshot_1531199591.png" width="180" height="320" data-original-width="900" data-original-height="1600" /></a></div>
<h3>Interesting right?</h3>
If you are really interested in this code, then please share this post with your friends, also share your feedback as comment here.
<br />
<h3 style="text-align: center;">
<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="83SNHDTB99JP8">
<!--<input type="submit" name="submit" value="Donate" class="btn"/>-->
<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
<b><span style="color: blue;">Thank You</span></b></h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com3tag:blogger.com,1999:blog-7580237816735071324.post-21972465383521042292018-05-03T09:30:00.000-07:002018-07-05T01:18:47.190-07:00Simple example of using firestore in Android | Kotlin<div dir="ltr" style="text-align: left;" trbidi="on">
Here is the simple example of maintaining database using <a href="https://firebase.google.com/">Firebase</a> instead of <a href="https://www.sqlite.org/index.html">SQLite</a> in <a href="https://kotlinlang.org/">Kotlin Programming Language</a>.
<h3>Step 1.</h3>
Login into <a href="https://console.firebase.google.com/">Firebase Console</a> and create your project.
<h3>Step 2.</h3>
Navigate into Database and follow the steps given there.
<h3>Step 3.</h3>
Create your Android project and add the following classpath into root of the project's build.gradle.<br />
<pre class="brush: java">
classpath 'com.google.gms:google-services:3.1.1'
</pre>
<h3>Step 4.</h3>
And then add the following plugin into your module's build.gradle.<br />
<pre class="brush: java">
apply plugin: 'com.google.gms.google-services'
</pre>
<h3>Step 5.</h3>
And then add the following dependency into your module's build.gradle.<br />
<pre class="brush: java">
implementation 'com.firebaseui:firebase-ui-firestore:3.3.1'
</pre>
That's all you wanted to access the Firebase's Firestore API in your project.<br />
Here is the methods to create document(Like table in SQLite), Add data to document, edit data from document, delete data from document.
<br />
<h3>Add data to document using Hashmap.</h3>
<pre class="brush: java">
//Create employee using hashmap
val employee = HashMap<String, Any>()
employee.put("name", "Guna")
employee.put("phoneNumber", "1144778855")
employee.put("email", "Guna@gmail.com")
//Add a new document with a generated ID
mFirestore.collection("employees")
.add(employee)
.addOnSuccessListener({ documentReference -> Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.id) })
.addOnFailureListener({ e -> Log.w(TAG, "Error adding document", e) })
</pre>
<h3>Add data to document using entity.</h3>
<pre class="brush: java">
//Create employee using entity
val employee = Employee("Guna", "1144778855", "Guna@gmail.com")
//Add a new document with a generated ID
mFirestore.collection("employees")
.add(employee)
.addOnSuccessListener({ documentReference -> Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.id) })
.addOnFailureListener({ e -> Log.w(TAG, "Error adding document", e) })
</pre>
<h3>Edit data from document using entity.</h3>
<pre class="brush: java">
//Create employee using entity
val employee = Employee("Gunaseelan", "1144778866", "Gunaseelan@gmail.com")
//Edit document with a generated ID
mFirestore.collection("employees")
.document(documentReference.id)//Generated while adding employee
.addOnSuccessListener({ documentReference -> Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.id) })
.addOnFailureListener({ e -> Log.w(TAG, "Error adding document", e) })
</pre>
<h3>Delete data from document</h3>
<pre class="brush: java">
//Add a new document with a generated ID
mFirestore.collection("employees")
.document(documentReference.id)//Generated while adding employee
.delete()
</pre>
<br />
Here is the video output of this source code<br />
<iframe width="560" height="315" src="https://www.youtube.com/embed/E_YXs3VYXLc" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe><br /><br />
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then please share this post with your friends, also share your feedback as comment here.
<br />
<h3 style="text-align: center;"><br /><a href="https://github.com/GunaseelanArumaikkannu/FirebaseDatabase" target="_blank" class="btn">Source code on GitHub</a>
<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="83SNHDTB99JP8">
<!--<input type="submit" name="submit" value="Donate" class="btn"/>-->
<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
<b><span style="color: blue;">Thank You</span></b></h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-12376777209094286202018-04-19T10:57:00.000-07:002018-04-19T22:56:11.110-07:00Simple Example of Firebase Authentication in Kotlin<div dir="ltr" style="text-align: left;" trbidi="on">
Here is the simple example of Authentication process using <a href="https://firebase.google.com/">Firebase</a> in <a href="https://kotlinlang.org/">Kotlin Programming Language</a>.
<br /><br />
<h3>Step 1.</h3>
Login into <a href="https://console.firebase.google.com/">Firebase Console</a> and create your project.
<br /><br />
<h3>Step 2.</h3>
Navigate into Authentication and enable your preferred login methods.
<br /><br />
<h3>Step 3.</h3>
Create your Android project and add the following classpath into root of the project's build.gradle.<br />
<pre class="brush: java">
classpath 'com.google.gms:google-services:3.1.1'
</pre>
<h3>Step 4.</h3>
And then add the following plugin into your module's build.gradle.<br />
<pre class="brush: java">
apply plugin: 'com.google.gms.google-services'
</pre>
<h3>Step 5.</h3>
And then add the following dependency into your module's build.gradle.<br />
<pre class="brush: java">
implementation 'com.firebaseui:firebase-ui-auth:3.3.1'
</pre>
That's you wanted to access the Firebase's Authentication API in your project.<br />
Here is the methods to Sign In, Sign Out and delete the account.
<h3>Sign In</h3>
<pre class="brush: java">
private fun signIn() {
// Choose authentication providers
val providers = Arrays.asList(AuthUI.IdpConfig.GoogleBuilder().build(),
AuthUI.IdpConfig.PhoneBuilder().build(),
AuthUI.IdpConfig.EmailBuilder().build())
// Create and launch sign-in intent
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.build(),
RC_SIGN_IN);
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val response = IdpResponse.fromResultIntent(data)
if (resultCode == RESULT_OK) {
// Successfully signed in
} else {
// Sign in failed, check response for error code
}
}
}
</pre>
<h3>Sign Out</h3>
<pre class="brush: java">
private fun signOut() {
AuthUI.getInstance()
.signOut(this)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(activity, getString(R.string.signed_out), LENGTH_LONG).show()
}
}
}
</pre>
<h3>Delete</h3>
<pre class="brush: java">
private fun delete() {
AuthUI.getInstance()
.delete(this)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(activity, getString(R.string.deleted), LENGTH_LONG).show()
}
}
}
</pre>
<br />
<h3>Screenshot</h3><br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiVoLV02leoKbq1S-iGn13Y0blIPyxvoe8NsHaHwXABAhWlEq9bR1GZLxyEII8eQ0Z4GLcp2q0tUnTUUm0xyqyPq-xHx4VLmrmlFzXL0in7dIMt7d4OqGXn-g9cP94TmjomCxAdLB-NCgKb/s1600/device-2018-04-20-112229.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiVoLV02leoKbq1S-iGn13Y0blIPyxvoe8NsHaHwXABAhWlEq9bR1GZLxyEII8eQ0Z4GLcp2q0tUnTUUm0xyqyPq-xHx4VLmrmlFzXL0in7dIMt7d4OqGXn-g9cP94TmjomCxAdLB-NCgKb/s320/device-2018-04-20-112229.png" width="157" height="320" data-original-width="783" data-original-height="1600" /></a></div><br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwr-xAK1PdHQ3eWDPa11IM_lwOJcAnOjwcrhhAAFgQW0jNloGTw-XqCNmC3inSUoKXOTFErMQBehsw1b73e3CIm5XTGzvve2lwzf0mua-8_g5XJfKiNxolgeGhDmO2GhRcHdMFFVzkuC08/s1600/device-2018-04-20-112159.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwr-xAK1PdHQ3eWDPa11IM_lwOJcAnOjwcrhhAAFgQW0jNloGTw-XqCNmC3inSUoKXOTFErMQBehsw1b73e3CIm5XTGzvve2lwzf0mua-8_g5XJfKiNxolgeGhDmO2GhRcHdMFFVzkuC08/s320/device-2018-04-20-112159.png" width="157" height="320" data-original-width="783" data-original-height="1600" /></a></div>
<br /><br />
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then please share this post with your friends, also share your feedback as comment here.
<br />
<h3 style="text-align: center;"><br /><br /><a href="https://github.com/GunaseelanArumaikkannu/FirebaseAuthentication" target="_blank" class="btn">Source code on GitHub</a><br /><br />
<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="83SNHDTB99JP8">
<input type="submit" name="submit" value="Donate" class="btn"/>
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-10889111416534056722018-03-20T19:17:00.000-07:002018-04-03T22:09:53.775-07:00Simple example of OCRReader in Android.<div dir="ltr" style="text-align: left;" trbidi="on">
Hi Friends, Maybe you all heard/used text scanning using camera feature or extracting text from Image. But this sample made it very easy for you. You can made it in very simple line of code.
<br /><br />
You can download the source code from <a href="https://github.com/GunaseelanArumaikkannu/OCRSample">OCRSample</a> and import the library as a module into your project. <br /><br />
Example usage : <b>MainActivity.java</b>
<pre class="brush: java">
public class MainActivity extends AppCompatActivity {
private TextView textView;
private final int CAMERA_SCAN_TEXT = 0;
private final int LOAD_IMAGE_RESULTS = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.actionCamera:
//Scan text from camera.
OCRCapture.Builder(this)
.setUseFlash(true)
.setAutoFocus(true)
.buildWithRequestCode(CAMERA_SCAN_TEXT);
break;
case R.id.actionPhoto:
Intent intentGallery = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intentGallery, LOAD_IMAGE_RESULTS);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
if (requestCode == CAMERA_SCAN_TEXT) {
if (resultCode == CommonStatusCodes.SUCCESS) {
textView.setText(data.getStringExtra(TextBlockObject));
}
} else if (requestCode == LOAD_IMAGE_RESULTS) {
Uri pickedImage = data.getData();
try {
//Extract text from image.
String text = OCRCapture.Builder(this).getTextFromUri(pickedImage);
//You can also use getTextFromBitmap(Bitmap bitmap) or getTextFromImage(String imagePath) buplic APIs from ibrary.
textView.setText(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
</pre>
<br />
Here is the video output of this source code<br />
<iframe width="560" height="315" src="https://www.youtube.com/embed/-ijmdLL1yBI" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe><br /><br />
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then please share this post with your friends, also share your feedback as comment here.
<br />
<h3 style="text-align: center;"><br /><a href='https://play.google.com/store/apps/details?id=com.guna.ocrreader&pcampaignid=MKT-Other-global-all-co-prtnr-py-PartBadge-Mar2515-1'><img alt='Get it on Google Play' src='https://developer.android.com/images/brand/en_generic_rgb_wo_45.png'/></a>
<br /><br /><a href="https://github.com/GunaseelanArumaikkannu/OCRSample" target="_blank" class="btn">Source code on GitHub</a><br /><br />
<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="83SNHDTB99JP8">
<input type="submit" name="submit" value="Donate" class="btn"/>
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com13tag:blogger.com,1999:blog-7580237816735071324.post-70310165637967494982018-02-20T13:21:00.000-08:002018-02-20T13:24:11.125-08:00Simple example of using RadioGroup, RadioButton in Kotlin | Android<div dir="ltr" style="text-align: left;" trbidi="on">
Here is the simple example of using RadioGroup, RadioButton in Android Kotlin.
<br /><br />
<pre class="brush: xml">
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.guna.kotlinapplication.BlankFragment">
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/male" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/female" />
</RadioGroup>
</pre><br />
<b>OnCheckedChangeListener</b><br />
<pre class="brush: java">
radioGroup.setOnCheckedChangeListener({ group, checkedId ->
val radioButton = view.findViewById<RadioButton>(checkedId)
Toast.makeText(activity, radioButton.text.toString() + " is checked", Toast.LENGTH_LONG).show()
})
</pre><br />
<br />
Here is the full video tutorial<br />
<iframe width="560" height="315" src="https://www.youtube.com/embed/cvGZoTr6ZzM" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe><br /><br />
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then please share this post with your friends.
<br />
<h3 style="text-align: center;">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b>Text WhatsApp message to <span style="color: blue;">+91-99654 70689</span> To join Android Developers WhatsApp group.</b>
<br /><a href="https://chat.whatsapp.com/1y5gLQAUGZdBYByaN2Ia6o">Join WhatsApp group by this link</a><br />
<b><span style="color: blue;">Thank You</span></b>
</h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-73857643893513517122018-02-19T07:57:00.000-08:002018-02-19T07:57:57.572-08:00Simple example of using Fragments in Kotlin | Android<div dir="ltr" style="text-align: left;" trbidi="on">
Here is the simple example of using Fragments with Activity in Android.
<br /><br />
<b>MainActivity.kt</b><br />
<pre class="brush: java">
class MainActivity : AppCompatActivity(), BlankFragment.OnFragmentInteractionListener {
override fun onFragmentInteraction(uri: Uri) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction().
add(R.id.fragment, BlankFragment.newInstance("Param1", "Param2"), "Second").commit()
}
fab.setOnClickListener { view ->
//Here we will replace the BlanckFragment with SecondFragment.
supportFragmentManager.beginTransaction().replace(R.id.fragment, SecondFragment(), "Second").commit()
}
}
}
</pre><br />
<b>activity_main.xml</b><br />
<pre class="brush: xml">
<android.support.design.widget.CoordinatorLayout 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="com.guna.kotlinapplication.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
</pre><br />
<b>content_main.xml</b><br />
<pre class="brush: xml">
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment"
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.guna.kotlinapplication.MainActivity"
tools:showIn="@layout/activity_main"/>
</pre><br />
We can add static fragment like this.
<b>content_main.xml</b><br />
<pre class="brush: xml">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment"
class="com.guna.kotlinapplication.BlankFragment"
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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.guna.kotlinapplication.MainActivity"
tools:showIn="@layout/activity_main"/>
</pre><br />
<b>BlankFragment.kt</b>
<pre class="brush: java">
/**
* A simple [Fragment] subclass.
* Activities that contain this fragment must implement the
* [BlankFragment.OnFragmentInteractionListener] interface
* to handle interaction events.
* Use the [BlankFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class BlankFragment : Fragment() {
// TODO: Rename and change types of parameters
private var mParam1: String? = null
private var mParam2: String? = null
private var mListener: OnFragmentInteractionListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
mParam1 = arguments!!.getString(ARG_PARAM1)
mParam2 = arguments!!.getString(ARG_PARAM2)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false)
}
// TODO: Rename method, update argument and hook method into UI event
fun onButtonPressed(uri: Uri) {
if (mListener != null) {
mListener!!.onFragmentInteraction(uri)
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnFragmentInteractionListener) {
mListener = context
} else {
throw RuntimeException(context!!.toString() + " must implement OnFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
mListener = null
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information.
*/
interface OnFragmentInteractionListener {
// TODO: Update argument type and name
fun onFragmentInteraction(uri: Uri)
}
companion object {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private val ARG_PARAM1 = "param1"
private val ARG_PARAM2 = "param2"
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
fun newInstance(param1: String, param2: String): BlankFragment {
val fragment = BlankFragment()
val args = Bundle()
args.putString(ARG_PARAM1, param1)
args.putString(ARG_PARAM2, param2)
fragment.arguments = args
return fragment
}
}
}// Required empty public constructor
</pre><br />
<b>fragment_blank.xml</b><br />
<pre class="brush: xml">
<FrameLayout 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:background="@color/colorPrimary"
tools:context="com.guna.kotlinapplication.BlankFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/hello_blank_fragment"
android:textColor="#fff" />
</FrameLayout>
</pre><br />
<b>SecondFragment.kt</b>
<pre class="brush: java">
/**
* A simple [Fragment] subclass.
*/
class SecondFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_second, container, false)
}
}// Required empty public constructor
</pre><br />
<b>fragment_second.xml</b><br />
<pre class="brush: xml">
<FrameLayout 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:background="#567891"
tools:context="com.guna.kotlinapplication.SecondFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/hello_blank_fragment"
android:textColor="#fff" />
</FrameLayout>
</pre><br />
<br />
Here is the full video tutorial<br />
<iframe width="560" height="315" src="https://www.youtube.com/embed/DTTwSdZymW4" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe><br /><br />
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then please share this post with your friends.
<br />
<h3 style="text-align: center;">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b>Text WhatsApp message to <span style="color: blue;">+91-99654 70689</span> To join Android Developers WhatsApp group.</b>
<br /><a href="https://chat.whatsapp.com/1y5gLQAUGZdBYByaN2Ia6o">Join WhatsApp group by this link</a><br />
<b><span style="color: blue;">Thank You</span></b>
</h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-63302513660532871972017-12-22T06:19:00.002-08:002017-12-22T06:23:00.623-08:00Simple example of SeekBarPreference in Android<div dir="ltr" style="text-align: left;" trbidi="on">
There is no predefined SeekBarPreference in Android. But we can make our own SeekBarPreference very simply. Here is simple example of making and using SeekBarPreference in Android.
<br /><br />
<b>SeekBarPreference.java</b><br />
<pre class="brush: java">
public class SeekBarPreference extends Preference implements SeekBar.OnSeekBarChangeListener {
private TextView textValue;
public SeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public SeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public SeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SeekBarPreference(Context context) {
super(context);
}
@Override
protected View onCreateView(ViewGroup parent) {
super.onCreateView(parent);
View view = LayoutInflater.from(getContext()).inflate(R.layout.seekbar, parent, false);
textValue = view.findViewById(R.id.textValue);
TextView textTitle = view.findViewById(R.id.textTitle);
textTitle.setText(getTitle());
SeekBar seekBar = view.findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(this);
SharedPreferences preferences = getSharedPreferences();
int value = preferences.getInt(getKey(), 0);
textValue.setText(String.format(Locale.getDefault(), "%d", value));
seekBar.setProgress(value);
return view;
}
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
textValue.setText(String.format(Locale.getDefault(), "%d", i));
SharedPreferences.Editor editor = getEditor();
editor.putInt(getKey(), i);
editor.apply();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
</pre>
<b>seekbar.xml</b><br />
<pre class="brush: xml">
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="match_parent"
android:paddingBottom="5dp"
android:paddingTop="5dp">
<TextView
android:id="@+id/textTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textColor="#000"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/textTitle" />
<TextView
android:id="@+id/textValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:textColor="#000"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/seekBar" />
</android.support.constraint.ConstraintLayout>
</pre>
<br />
Here is the <b>settings.xml</b> used in <b>SettingsActivityFragment</b>.
<pre class="brush: xml">
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<com.guna.testapplication.widgets.SeekBarPreference
android:defaultValue="50"
android:key="seekBar"
android:title="Seek Bar" />
</PreferenceScreen>
</pre>
<b>SettingsActivity.java</b><br />
<pre class="brush: java">
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
</pre>
<b>SettingsActivityFragment.java</b><br />
<pre class="brush: java">
public class SettingsActivityFragment extends PreferenceFragment {
public SettingsActivityFragment() {
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
</pre>
<br />
Here is the full video tutorial<br />
<iframe width="560" height="315" src="https://www.youtube.com/embed/_dwZfcwELTQ" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe><br /><br />
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then please share this post with your friends.
<br />
<h3 style="text-align: center;">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b>Text WhatsApp message to <span style="color: blue;">+91-99654 70689</span> To join Android Developers WhatsApp group.</b>
<br /><a href="https://chat.whatsapp.com/1y5gLQAUGZdBYByaN2Ia6o">Join WhatsApp group by this link</a><br />
<b><span style="color: blue;">Thank You</span></b>
</h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-81372901319844550142017-12-20T07:14:00.002-08:002017-12-20T07:23:43.717-08:00Simple example of Using JobScheduler in Android<div dir="ltr" style="text-align: left;" trbidi="on">
JobScheduler is the Android framework API for scheduling tasks or work. It first became available in Android 5.0 (API level 21), and remains under active development. Notably, Android 7.0 (API level 24) added the ability to trigger jobs based on ContentProvider changes.<br /><br />
If your app targets Android 5.0 (API level 21), we recommend that you use the JobScheduler to execute background tasks.<br /><br />
Here is the simple example of Scheduling and Cancelling the scheduled job.
<b>MainActivity.java</b><br />
<pre class="brush: java">
public class MainActivity extends AppCompatActivity {
int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public void addJob(View view) {
count++;
JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
ComponentName componentName = new ComponentName(this, MyJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(count, componentName);
builder.setMinimumLatency(15000);//Start after 15 seconds
PersistableBundle bundle = new PersistableBundle();
bundle.putString("Title", "Job " + count);
builder.setExtras(bundle);
if (scheduler != null) {
int result = scheduler.schedule(builder.build());
if (result == JobScheduler.RESULT_SUCCESS) {
showToast("Job scheduled successfully");
} else {
showToast("Job scheduling failed");
}
}
}
private void showToast(String s) {
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
public void allJobs(View view) {
startActivity(new Intent(this, AllJobsActivity.class));
}
}
</pre><br /><br />
<b>content_main.xml</b><br />
<pre class="brush: xml">
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="@layout/activity_main">
<Button
android:id="@+id/buttonAddJob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addJob"
android:text="Add Job"
app:layout_constraintBottom_toTopOf="@id/buttonShowAllJob"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/buttonShowAllJob"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="allJobs"
android:text="All Jobs"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/buttonAddJob" />
</android.support.constraint.ConstraintLayout>
</pre><br /><br />
<b>MyJobService.java</b><br />
<pre class="brush: java">
public class MyJobService extends JobService {
private static final String TAG = MyJobService.class.getSimpleName();
@Override
public boolean onStartJob(JobParameters jobParameters) {
PersistableBundle bundle = jobParameters.getExtras();
Log.v(TAG, bundle.getString("Title") + " started");
jobFinished(jobParameters, false);
return true;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
Log.v(TAG, "Job completed");
return true;
}
}
</pre>
<b>MyJobService</b> should be registered in manifest as below.
<pre class="brush: xml">
<service
android:name=".MyJobService"
android:permission="android.permission.BIND_JOB_SERVICE" />
</pre>
<b>MyJobService.java</b><br />
<pre class="brush: java">
public class AllJobsActivity extends AppCompatActivity {
private List<JobInfo> pendingJobs = null;
private JobsAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_jobs);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
RecyclerView recyclerView = findViewById(R.id.myJobList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
final JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (scheduler != null) {
pendingJobs = scheduler.getAllPendingJobs();
adapter = new JobsAdapter(pendingJobs);
recyclerView.setAdapter(adapter);
}
ItemTouchHelper.SimpleCallback callback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
AlertDialog.Builder builder = new AlertDialog.Builder(AllJobsActivity.this);
builder.setTitle("Cancel Job");
builder.setMessage("Are you sure to cancel this Job");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
JobInfo info = pendingJobs.get(viewHolder.getAdapterPosition());
scheduler.cancel(info.getId());
pendingJobs.remove(viewHolder.getAdapterPosition());
dialogInterface.dismiss();
adapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
adapter.notifyDataSetChanged();
}
});
builder.create().show();
}
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
View view = viewHolder.itemView;
Paint p = new Paint();
p.setColor(Color.RED);
RectF rectF;
if (dX > 0) {
rectF = new RectF(view.getLeft(), view.getTop(), dX, view.getBottom());
} else {
rectF = new RectF(view.getRight() + dX, view.getTop(), view.getRight(), view.getBottom());
}
c.drawRect(rectF, p);
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
};
ItemTouchHelper helper = new ItemTouchHelper(callback);
helper.attachToRecyclerView(recyclerView);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
</pre>
<b>JobsAdapter.java</b><br />
<pre class="brush: java">
public class JobsAdapter extends RecyclerView.Adapter<JobsAdapter.ViewHolder> {
private List<JobInfo> pendingJobs;
public JobsAdapter(List<JobInfo> pendingJobs) {
this.pendingJobs = pendingJobs;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_list_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(position);
}
@Override
public int getItemCount() {
return pendingJobs.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text);
}
void bind(int position) {
JobInfo info = pendingJobs.get(position);
PersistableBundle bundle = info.getExtras();
textView.setText(bundle.get("Title").toString());
}
}
}
</pre>
<br />
Here is the full video tutorial<br />
<iframe width="560" height="315" src="https://www.youtube.com/embed/DtVBTgU6jjA" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe><br /><br />
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then please share this post with your friends.
<br />
<h3 style="text-align: center;">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b>Text WhatsApp message to <span style="color: blue;">+91-99654 70689</span> To join Android Developers WhatsApp group.</b>
<br /><a href="https://chat.whatsapp.com/1y5gLQAUGZdBYByaN2Ia6o">Join WhatsApp group by this link</a><br />
<b><span style="color: blue;">Thank You</span></b>
</h3>
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-19166732225660921402017-12-05T22:05:00.003-08:002017-12-05T23:35:07.310-08:00Simple example of using ViewPager in Kotlin | Android<div dir="ltr" style="text-align: left;" trbidi="on">
Though Kotlin has lot of massive features to speedup the development time, here is the simple example of using ViewPager in Android.
In Kotlin we don't need to declare and initialize Views. We can simply access the id of Views from xml.
<br /><br /><b>Ex:</b> <br />
<b>activity_main.xml</b>
<pre class="brush: xml">
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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="com.guna.kotlinapplication.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="@+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
</pre>
<b>MainActivity.kt</b><br />
<pre class="brush: java">
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
setupViewPager(pager)
tabs.setupWithViewPager(pager)
}
private fun setupViewPager(pager: ViewPager?) {
val adapter = Adapter(supportFragmentManager)
val f1 = BlankFragment.newInstance("One")
adapter.addFragment(f1, "TAB 1")
val f2 = BlankFragment.newInstance("Two")
adapter.addFragment(f2, "TAB 2")
val f3 = BlankFragment.newInstance("Three")
adapter.addFragment(f3, "TAB 3")
pager?.adapter = adapter
}
private class Adapter(manager: FragmentManager) : FragmentPagerAdapter(manager) {
val fragments = ArrayList<Fragment>()
val titles = ArrayList<String>()
override fun getItem(position: Int): Fragment = fragments.get(position)
override fun getCount(): Int = fragments.size
override fun getPageTitle(position: Int): CharSequence? = titles.get(position)
fun addFragment(fragment: Fragment, title: String) {
fragments.add(fragment)
titles.add(title)
}
}
}
</pre>
<b>BlankFragment.kt</b>
<pre class="brush: java">
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_blank.view.*
class BlankFragment : Fragment() {
var text = ""
companion object {
fun newInstance(text: String): BlankFragment {
val fragment = BlankFragment()
val bundle = Bundle()
bundle.putString("Text", text)
fragment.arguments = bundle
return fragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
text = arguments?.get("Text").toString()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_blank, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.textView.setText(text)
}
}
</pre>
<br />
Did you noticed, we never declare <b>pager</b> nor initialized, instead we directly accessed it from activity_main. <br />
In BlankFragment also, we didn't declare and initialize <b>textView</b> <br /><br />
And also, unless Java, default constructor will come with class name itself; like <b>Adapter(manager: FragmentManager)</b>.
<br /><br />
So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current <b>Activity</b> is java, don't worry, you can create your next <b>Activity</b> in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.
<br /><br />
Here is the full video tutorial
<iframe width="560" height="315" src="https://www.youtube.com/embed/ZVlYLd_nXlU" frameborder="0" gesture="media" allowfullscreen></iframe>
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then please share this post with your friends.
<br />
<h3 style="text-align: center;">
<br /><a href="http://v4all123.blogspot.com/2017/11/simple-example-of-using-recyclerview-in.html" target="_blank">Simple example of using RecyclerView in Kotlin | Android</a><br />
<br /><a href="http://v4all123.blogspot.com/2017/11/simple-example-of-using-spinner-in.html" target="_blank">Simple example of using Spinner in Kotlin | Android</a><br />
<br /><a href="http://v4all123.blogspot.com/2017/11/simple-example-of-using-checkbox-in.html" target="_blank">Simple example of using CheckBox in Kotlin | Android</a><br />
<br /><a href="http://v4all123.blogspot.com/2017/11/using-button-in-kotlin-android.html" target="_blank">Using Button in Kotlin | Android</a><br />
<br /><a href="http://v4all123.blogspot.com/2017/11/getting-started-on-kotlin.html" target="_blank">Getting Started on Kotlin</a><br />
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b>Text WhatsApp message to <span style="color: blue;">+91-99654 70689</span> To join Android Developers WhatsApp group.</b>
<br /><a href="https://chat.whatsapp.com/1y5gLQAUGZdBYByaN2Ia6o">Join WhatsApp group by this link</a><br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br />
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-42259501829664896392017-11-30T07:33:00.000-08:002017-11-30T07:35:21.160-08:00Simple example of using RecyclerView in Kotlin | Android<div dir="ltr" style="text-align: left;" trbidi="on">
Though Kotlin has lot of massive features to speedup the development time, here is the simple example of using RecyclerView in Android.
In Kotlin we don't need to declare and initialize RecyclerView. We can simply access the id of RecyclerView from xml.
<br /><br />
<b>Ex : </b>
<pre class="brush: xml">
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.guna.kotlinapplication.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.constraint.ConstraintLayout>
</pre>
<br /><br />
We can simply access id of RecyclerView from above xml in kotlin file.
<pre class="brush: java">
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
recyclerView.adapter = Adapter(myStrings, this)
</pre>
<br />
Here is the <b>Adapter.kt</b> class.
<pre class="brush: java">
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.item.view.*
/**
* Created by Guna on 30-11-2017.
*/
class Adapter(val strings: Array<String>, val activity: MainActivity) : RecyclerView.Adapter<Adapter.ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
holder?.bind(strings[position], activity)
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder =
ViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.item, parent, false))
override fun getItemCount(): Int = strings.size
class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
fun bind(string: String, activity: MainActivity) {
itemView.textView.setText(string)
itemView.setOnClickListener{
view -> activity.fromAdapter(string)
}
}
}
}
</pre>
<br />
And Here is the <b>MainActivity.kt</b> class.
<pre class="brush: java">
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
val myStrings = arrayOf("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten",
"Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen")
val paint = Paint()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
recyclerView.adapter = Adapter(myStrings, this)
val callback = object : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, target: RecyclerView.ViewHolder?): Boolean {
val fromPosition = viewHolder!!.adapterPosition
val toPosition = target!!.adapterPosition
val fromString = myStrings[fromPosition]
val toString = myStrings[toPosition]
myStrings[fromPosition] = toString
myStrings[toPosition] = fromString
recyclerView?.adapter?.notifyItemMoved(fromPosition, toPosition)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder?, direction: Int) {
if (direction == ItemTouchHelper.LEFT) {
Toast.makeText(this@MainActivity, myStrings[viewHolder!!.adapterPosition] + " Left Swiped", LENGTH_LONG).show()
} else if (direction == ItemTouchHelper.RIGHT) {
Toast.makeText(this@MainActivity, myStrings[viewHolder!!.adapterPosition] + " Right Swiped", LENGTH_LONG).show()
}
recyclerView.adapter.notifyDataSetChanged()
}
override fun onChildDraw(c: Canvas?, recyclerView: RecyclerView?, viewHolder: RecyclerView.ViewHolder?, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
if (dX > 0) {
paint.color = Color.GREEN
val rect = Rect(viewHolder!!.itemView!!.left, viewHolder.itemView.top, dX.toInt(), viewHolder.itemView.bottom)
c?.drawRect(rect, paint)
} else if (dX < 0) {
paint.color = Color.RED
val rect = Rect(viewHolder!!.itemView.right.plus(dX).toInt(), viewHolder.itemView.top, viewHolder.itemView.right, viewHolder.itemView.bottom)
c?.drawRect(rect, paint)
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
}
val helper = ItemTouchHelper(callback)
helper.attachToRecyclerView(recyclerView)
}
fun fromAdapter(string: String) {
Toast.makeText(this, string, LENGTH_LONG).show()
}
}
</pre>
<br />
Did you noticed, we never declare <b>recyclerView</b> nor initialized, instead we directly accessed it from activity_main. <br />
In ViewHolder also, we didn't declare and initialize <b>textView</b> <br /><br />
And also, unless Java, default constructor will come with class name itself; like <b>Adapter(val strings: Array<String>, val activity: MainActivity)</b>.
<br /><br />
So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current <b>Activity</b> is java, don't worry, you can create your next <b>Activity</b> in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.
<br /><br />
Here is the full video tutorial
<iframe width="560" height="315" src="https://www.youtube.com/embed/IN3sYIF4VBg" frameborder="0" allowfullscreen></iframe>
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then please share this post with your friends.
<br />
<h3 style="text-align: center;">
<br /><a href="http://v4all123.blogspot.com/2017/11/simple-example-of-using-spinner-in.html" target="_blank">Simple example of using Spinner in Kotlin | Android</a><br />
<br /><a href="http://v4all123.blogspot.com/2017/11/simple-example-of-using-checkbox-in.html" target="_blank">Simple example of using CheckBox in Kotlin | Android</a><br />
<br /><a href="http://v4all123.blogspot.com/2017/11/using-button-in-kotlin-android.html" target="_blank">Using Button in Kotlin | Android</a><br />
<br /><a href="http://v4all123.blogspot.com/2017/11/getting-started-on-kotlin.html" target="_blank">Getting Started on Kotlin</a><br />
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b>Text WhatsApp message to <span style="color: blue;">+91-99654 70689</span> To join Android Developers WhatsApp group.</b>
<br /><a href="https://chat.whatsapp.com/1y5gLQAUGZdBYByaN2Ia6o">Join WhatsApp group by this link</a><br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br />
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-9930678981169927592017-11-28T21:25:00.003-08:002020-06-24T04:59:33.950-07:00Simple example of using Spinner in Kotlin | Android<div dir="ltr" style="text-align: left;" trbidi="on">
Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Spinner in Android.
In Kotlin we don't need to declare and initialize Spinner. We can simply access the id of Spinner from xml.
<br /><br />
<b>Ex : </b>
<pre class="prettyprint lang-java">
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//String array.
val myStrings = arrayOf("One", "Two", "Three", "Four", "Five")
//Adapter for spinner
mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, myStrings)
//item selected listener for spinner
mySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
Toast.makeText(this@MainActivity, myStrings[p2], LENGTH_LONG).show()
}
}
}
}
</pre>
<br />
Did you noticed, we never declare <b>myCheckBox</b> nor initialized, instead we directly accessed it from activity_main.
<br />
And also there is no new keyword while ArrayAdapter or implementing OnItemSelectedListener.
<br /><br />
So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current <b>Activity</b> is java, don't worry, you can create your next <b>Activity</b> in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.
<br /><br />
Here is the full video tutorial
<iframe width="560" height="315" src="https://www.youtube.com/embed/Mp4DjL8L-aI" frameborder="0" gesture="media" allowfullscreen></iframe>
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then share this post with your friends.
<br />
<h3 style="text-align: center;">
<br /><a href="http://v4all123.blogspot.com/2017/11/simple-example-of-using-checkbox-in.html" target="_blank">Simple example of using CheckBox in Kotlin | Android</a><br /><br />
<br /><a href="http://v4all123.blogspot.com/2017/11/using-button-in-kotlin-android.html" target="_blank">Using Button in Kotlin | Android</a><br /><br />
<br /><a href="http://v4all123.blogspot.com/2017/11/getting-started-on-kotlin.html" target="_blank">Getting Started on Kotlin</a><br /><br />
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b>Text WhatsApp message to <span style="color: blue;">+91-99654 70689</span> To join Android Developers WhatsApp group.</b>
<br /><a href="https://chat.whatsapp.com/1y5gLQAUGZdBYByaN2Ia6o">Join WhatsApp group by this link</a><br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br />
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com152tag:blogger.com,1999:blog-7580237816735071324.post-60405555389220155862017-11-27T21:02:00.000-08:002017-11-27T21:02:16.638-08:00Simple example of using CheckBox in Kotlin | Android<div dir="ltr" style="text-align: left;" trbidi="on">
Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Button in Android.
In Kotlin we don't need to declare and initialize CheckBox. We simply access the id of CheckBox from Kotlin file.
<br /><br />
<b>Ex : </b>
<pre class="brush: java">
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myCheckBox.setOnCheckedChangeListener { view, isChecked ->
Toast.makeText(this, isChecked.toString(), LENGTH_LONG).show()
}
}
}
</pre>
<br />
Did you noticed, we never declare <b>myCheckBox</b> nor initialized, instead we directly accessed it from activity_main.
<br />
And inside <b>setOnCheckedChangeListener</b> method, we didn't implement `onCheckedChanged` interface.
<br /><br />
So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current <b>Activity</b> is java, don't worry, you can create your next <b>Activity</b> in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.
<br /><br />
Here is the full video tutorial
<iframe width="560" height="315" src="https://www.youtube.com/embed/qv9A6CS3E8k" frameborder="0" gesture="media" allowfullscreen></iframe>
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then share this post with your friends.
<br />
<h3 style="text-align: center;">
<br /><a href="http://v4all123.blogspot.com/2017/11/using-button-in-kotlin-android.html" target="_blank">Using Button in Kotlin | Android</a><br /><br />
<br /><a href="http://v4all123.blogspot.com/2017/11/getting-started-on-kotlin.html" target="_blank">Getting Started on Kotlin</a><br /><br />
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b>Text WhatsApp message to <span style="color: blue;">+91-99654 70689</span> To join Android Developers WhatsApp group.</b>
<br /><a href="https://chat.whatsapp.com/1y5gLQAUGZdBYByaN2Ia6o">Join WhatsApp group by this link</a><br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br />
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-30176076032834045062017-11-16T05:19:00.000-08:002017-11-16T05:21:13.501-08:00Basic data types of KOTLIN and simple examples.<div dir="ltr" style="text-align: left;" trbidi="on">
In this section we describe the basic types used in Kotlin: numbers, characters, booleans, arrays, and strings.
<br />
<h1>Numbers</h1>
Kotlin handles numbers in a way close to Java, but not exactly the same. For example, there are no implicit widening conversions for numbers, and literals are slightly different in some cases.
<br />
<br />
Kotlin provides the following built-in types representing numbers (this is close to Java): <br /><br />
<table style="font-family: arial, sans-serif; border-collapse: collapse; width: 100%;">
<tr>
<th style="border: 1px solid #dddddd;text-align: left;padding: 8px;">Type</th>
<th style="border: 1px solid #dddddd;text-align: left;padding: 8px;">Bit width</th>
</tr>
<tr style="background-color: #dddddd;">
<td style="border: 1px solid #dddddd;text-align: left;padding: 8px;">Double</td>
<td style="border: 1px solid #dddddd;text-align: left;padding: 8px;">64</td>
</tr>
<tr>
<td style="border: 1px solid #dddddd;text-align: left;padding: 8px;">Float</td>
<td style="border: 1px solid #dddddd;text-align: left;padding: 8px;">32</td>
</tr>
<tr style="background-color: #dddddd;">
<td style="border: 1px solid #dddddd;text-align: left;padding: 8px;">Long</td>
<td style="border: 1px solid #dddddd;text-align: left;padding: 8px;">64</td>
</tr>
<tr>
<td style="border: 1px solid #dddddd;text-align: left;padding: 8px;">Int</td>
<td style="border: 1px solid #dddddd;text-align: left;padding: 8px;">32</td>
</tr>
<tr style="background-color: #dddddd;">
<td style="border: 1px solid #dddddd;text-align: left;padding: 8px;">Short</td>
<td style="border: 1px solid #dddddd;text-align: left;padding: 8px;">16</td>
</tr>
<tr>
<td style="border: 1px solid #dddddd;text-align: left;padding: 8px;">Byte</td>
<td style="border: 1px solid #dddddd;text-align: left;padding: 8px;">8</td>
</tr>
</table>
<br />
<br />
We can declare data types in KOTLIN as following way.
<pre class="brush: java">
var a: Int = 0 //int var, we can reassign at runtime or anywhere in the code.
val a:Int =0 //int val, val cannot reassign.
var a = 0 //int var
val a = 0 //int val
var a = 10.10 //Double
var a = 10.10f //Float
var a = 10.10F //Float
var a = 10L //Long
//You can use underscores to make number constants more readable:
val oneMillion=1_000_000
</pre>
<br />
Every number type supports the following conversions:
<br />
<br />
toByte(): Byte
<br />
<br />
toShort(): Short
<br />
<br />
toInt(): Int
<br />
<br />
toLong(): Long
<br />
<br />
toFloat(): Float
<br />
<br />
toDouble(): Double
<br />
<br />
toChar(): Char
<br />
<br />
<h1>Operations</h1>
<br />
Here is the complete list of bitwise operations (available for Int and Long only):<br />
<ol style="background-color: #F1F1F1; padding-top: 10px; padding-bottom: 10px;">
<li>shl(bits) – signed shift left (Java's <<)</li>
<li>shr(bits) – signed shift right (Java's >>)</li>
<li>ushr(bits) – unsigned shift right (Java's >>>)</li>
<li>and(bits) – bitwise and</li>
<li>or(bits) – bitwise or</li>
<li>xor(bits) – bitwise xor</li>
<li>inv() – bitwise inversion</li>
</ol>
<h3>Ex:</h3>
var x = 1 shl 2 <br />
var x = 1 shr 2 <br />
var x = 1 ushr 2 <br />
var x = 1 and 2 <br />
var x = 1 or 2 <br />
var x = 1 xor 2 <br />
var x = 1.inv() <br />
<br />
Also we have <b>int()</b> instead of <b>++</b> and <b>dec()</b> instead of <b>--</b>.
<br /><h3>Ex:</h3>
var x = a.inc()
<h1>Characters</h1>
Characters are represented by the type <b>Char</b><br />
var c = 'a'.
<h1>Booleans</h1>
The type Boolean represents booleans, and has two values: true and false.<br />
var b = true
<h1>Strings</h1>
Strings are represented by the type String. Strings are immutable.
var s = "Hello Kotlin"
<br /><br /><h3>Interesting right?</h3>
<br />
If you are really interested in this code, then share this post with your friends.
<br /><br />
<h3 style="text-align: center;">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b>Text WhatsApp message to <span style="color: blue;">+91-99654 70689</span> To join Android Developers WhatsApp group.</b>
<br /><a href="https://chat.whatsapp.com/1y5gLQAUGZdBYByaN2Ia6o">Join WhatsApp group by this link</a><br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br />
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-52265836462775429362017-11-09T03:27:00.003-08:002017-11-16T05:21:28.740-08:00Using Button in Kotlin | Android<div dir="ltr" style="text-align: left;" trbidi="on">
Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Button in Android.
<pre class="brush: java">
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private var count: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myButton.setOnClickListener({
count = count.inc()
Toast.makeText(this, "Clicked Count " + count, LENGTH_LONG).show()
myButton.setText("Click again")
})
}
}
</pre>
<br />
Did you noticed, Here we used colon(:) instead of <b>extends</b> keyword, but here we used parentheses at end of the <b>AppCompatActivity</b>.
<br />
And we initialized count as Int var, where <b>Int</b> is one of the data type in Kotlin used to declare <b>int</b> variable from <b>Java</b>, and <b>var</b> defines count as variable, means, can be reinitialized at run time.
<br />
And we never declare <b>myButton</b> nor initialized, instead we directly accessed it from activity_main.
<br />
And inside <b>setOnClickListener</b> method, we didn't implement `OnClickListener` interface.
<br /><br />
So, in simple accessing of button itself, we omitted near 10 lines of code. So imagine about full length project, near 40% of time is saved right?
<br />
So, If you think this is the right time to start with Kotlin, then start alongside with your current project. Yes, you can use Java and Kotlin in same project. If your current <b>Activity</b> is java, don't worry, you can create your next <b>Activity</b> in kotlin. Or you can convert your current Activity also to Kotlin and then continue learning Kotlin in same Activity.
<br /><br />
Here is the full video tutorial
<iframe width="560" height="315" src="https://www.youtube.com/embed/NBTySzzVMe0" frameborder="0" gesture="media" allowfullscreen></iframe>
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then share this post with your friends.
<br />
<h3 style="text-align: center;">
<br /><a href="http://v4all123.blogspot.com/2017/11/getting-started-on-kotlin.html" target="_blank">Getting Started on Kotlin</a><br /><br />
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b>Text WhatsApp message to <span style="color: blue;">+91-99654 70689</span> To join Android Developers WhatsApp group.</b>
<br /><a href="https://chat.whatsapp.com/1y5gLQAUGZdBYByaN2Ia6o">Join WhatsApp group by this link</a><br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br />
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-15115983563516804112017-11-02T06:25:00.000-07:002017-11-16T05:21:48.673-08:00Getting Started on Kotlin<div dir="ltr" style="text-align: left;" trbidi="on">
Kotlin is now an official language on Android. Kotlin is expressive, concise, extensible, powerful, and a joy to read and write. It has wonderful safety features in terms of nullability and immutability.
<br /><br />
If you're interested in using Kotlin, it's easy to get started because it works side by side with Java and C++ on Android. So you can keep your existing code, continue to use the various Android libraries, and incrementally add Kotlin code to your project. Unlike almost any other language, Kotlin is a drop-in replacement you can use bi-directionally—you can call into the Java language from Kotlin, and you can call into Kotlin from the Java language.
<br /><br />
Of course, IDE support is also crucial, and we have it. Android Studio is built upon IntelliJ IDEA, an IDE built by JetBrains—the same company that created the Kotlin language. The JetBrains team has been working for years to make sure Kotlin works great with IntelliJ IDEA. So we're inheriting all their hard work. Starting with Android Studio 3.0, tooling support for Kotlin is bundled directly into Android Studio.
<br /><br />
<h1>Create a new project with Kotlin</h1>
Using Kotlin with a new project requires just one extra click in the New Project wizard:
<ol style="background-color: #F1F1F1; padding-top: 10px; padding-bottom: 10px;">
<li>In Android Studio, click <b>File > New > New Project</b>. Or if you've just opened Android Studio and see the <b>Welcome to Android Studio</b> window, click <b>Start a new Android Studio project</b>.</li>
<li>On the first screen, check <b>Include Kotlin support</b>. That's the only difference.</li>
<li>Click <b>Next</b> and continue through the wizard until you're done.</li>
</ol>
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXXqevCjeXzwZilIVjTyc_jXIJKeDQpUT9VlLpTYUyEfTahIBQL85tpsYEEwoCESVT5jqQ5eKx-eowCElPHLKrqPWBrMq63tuxPVb9gPfC-wXJPzW0ygpqtzSqLjrdBCfAE9GbH69Rq1XO/s1600/Kotlin.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXXqevCjeXzwZilIVjTyc_jXIJKeDQpUT9VlLpTYUyEfTahIBQL85tpsYEEwoCESVT5jqQ5eKx-eowCElPHLKrqPWBrMq63tuxPVb9gPfC-wXJPzW0ygpqtzSqLjrdBCfAE9GbH69Rq1XO/s320/Kotlin.png" width="320" height="229" data-original-width="902" data-original-height="646" /></a></div>
<br /><br />
<h1>Add Kotlin to an existing project</h1>
If you want to add Kotlin code to an existing project, simply click <b>File > New</b> and select one of the various Android templates. If you don't see the list of templates in this menu, first open the <b>Project</b> window and select your app module.
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhW-hLgXtCXsC4hP0Jm9J-11hWoOdSjOwCkLeitbl6b84XKowbKvmfXhuDjOyHpn4-UF8g_C-0D3r3a8uNjiJ1wAHE0NQwqLqMHnCLz7O_guiqHtRq18Mni4-ExyjpeoLN2M2r5RPmJY3D6/s1600/kotlin2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhW-hLgXtCXsC4hP0Jm9J-11hWoOdSjOwCkLeitbl6b84XKowbKvmfXhuDjOyHpn4-UF8g_C-0D3r3a8uNjiJ1wAHE0NQwqLqMHnCLz7O_guiqHtRq18Mni4-ExyjpeoLN2M2r5RPmJY3D6/s320/kotlin2.png" width="320" height="258" data-original-width="802" data-original-height="646" /></a></div>
<br />
<h1>Convert existing Java code to Kotlin code</h1>
In Android Studio 3.0, open a Java file and select <b>Code > Convert Java File to Kotlin File</b>.
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgu3ARoVtpfOk8e3Ff4LvgD7i5Oct897pZ7ClaS-hdC_X_EHpX4kocSV7Ew2u4ENXYm7JNQGIkRTWdEYpxje0dsvF1ruDBhgMUkHs3xTxiG1_DKM9GbtAh6O5fLcK60jfkjoO4XEnDu-gip/s1600/kotlin3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgu3ARoVtpfOk8e3Ff4LvgD7i5Oct897pZ7ClaS-hdC_X_EHpX4kocSV7Ew2u4ENXYm7JNQGIkRTWdEYpxje0dsvF1ruDBhgMUkHs3xTxiG1_DKM9GbtAh6O5fLcK60jfkjoO4XEnDu-gip/s320/kotlin3.png" width="320" height="171" data-original-width="1366" data-original-height="728" /></a></div>
<br />
Or, create a new Kotlin file (<b>File > New > Kotlin File/Class</b>), and then paste your Java code into that file—when prompted, click <b>Yes</b> to convert the code to Kotlin. You can check <b>Don't show this dialog next time</b>, which makes it easy to dump Java code snippets into your Kotlin files.
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJiDAamuJ97TvxzH136YL-mysFQNvC2ojCCiet-Ggzct4AwATfh9H85rq0aBBEeffSQukJzsnxUm9Rz9r2XsaDK1jq-J_5O4yrM8F7POAag09VWfpGsHOcrXb2dRBEOFyJCbI1n2lVZeuz/s1600/Kotlin4.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJiDAamuJ97TvxzH136YL-mysFQNvC2ojCCiet-Ggzct4AwATfh9H85rq0aBBEeffSQukJzsnxUm9Rz9r2XsaDK1jq-J_5O4yrM8F7POAag09VWfpGsHOcrXb2dRBEOFyJCbI1n2lVZeuz/s320/Kotlin4.png" width="320" height="171" data-original-width="1366" data-original-height="728" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikyjuMmRNnT6hYgvJ_A5iwK4aHy5vzB0OOUdi0i3beBtCq78WLjIsOIGL4C4FL0qkvMkwiKhd9i1_bZinFO99D_EOK6bROwNGwUUt-Ku8vI4R_g9Iq7_Mvhkli2ycaRXgXAB9WOSRfzC0B/s1600/Kotlin5.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikyjuMmRNnT6hYgvJ_A5iwK4aHy5vzB0OOUdi0i3beBtCq78WLjIsOIGL4C4FL0qkvMkwiKhd9i1_bZinFO99D_EOK6bROwNGwUUt-Ku8vI4R_g9Iq7_Mvhkli2ycaRXgXAB9WOSRfzC0B/s320/Kotlin5.png" width="320" height="99" data-original-width="456" data-original-height="141" /></a></div>
<h1>Use Android APIs with Kotlin</h1>
Kotlin provides complete <a href="https://kotlinlang.org/docs/reference/java-interop.html">interoperability with the Java language</a>, so calling the Android APIs often looks exactly like the matching Java code. Except now you can combine those method calls with Kotlin's syntax features. <br /><br />
Here are a few examples of what it looks like to call Android APIs in Kotlin, compared to the same code in Java language:
<h3>Declare Activity in Java</h3>
<pre class="brush: java">
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
}
}
</pre>
<br />
<h3>Declare Activity in Kotlin</h3>
<pre class="brush: java">
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity)
}
}
</pre>
<br />
<h3>On-click listener in Java</h3>
<pre class="brush: java">
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//TODO: Do your code
}
});
</pre>
<br />
<h3>On-click listener in Kotlin</h3>
<pre class="brush: java">
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener {
//TODO: Do your code
}
</pre>
<br />
<h3>Item click listener in Java</h3>
<pre class="brush: java">
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
return true;
}
return false;
}
};
</pre>
<br />
<h3>Item click listener in Kotlin</h3>
<pre class="brush: java">
private val mOnNavigationItemSelectedListener
= BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
mTextMessage.setText(R.string.title_home)
return@OnNavigationItemSelectedListener true
}
R.id.navigation_dashboard -> {
mTextMessage.setText(R.string.title_dashboard)
return@OnNavigationItemSelectedListener true
}
}
false
}
</pre>
<br />
Here is the Get Started with Kotlin video.<br />
<iframe width="560" height="315" src="https://www.youtube.com/embed/hYeNFC8NG6A" frameborder="0" gesture="media" allowfullscreen></iframe>
<br /><h3>Interesting right?</h3>
<br />
If you are really interested in this code, then share this post with your friends.
<br /><br />
<h3 style="text-align: center;">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b>Text WhatsApp message to <span style="color: blue;">+91-99654 70689</span> To join Android Developers WhatsApp group.</b>
<br /><a href="https://chat.whatsapp.com/1y5gLQAUGZdBYByaN2Ia6o">Join WhatsApp group by this link</a><br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br />
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-5508070176282114472017-10-30T01:12:00.001-07:002017-10-30T01:12:23.792-07:00Simple ConstraintLayout tutorial in Android.<div dir="ltr" style="text-align: left;" trbidi="on">
A ConstraintLayout is a ViewGroup which allows you to position and size widgets in a flexible way.
<br /><br />
There are currently various types of constraints that you can use:
<ul style="list-style-type: circle; background-color: #F1F1F1; padding-top: 10px; padding-bottom: 10px;">
<li>Relative positioning</li>
<li>Margins</li>
<li>Centering positioning</li>
<li>Circular positioning</li>
<li>Visibility behavior</li>
<li>Dimension constraints</li>
<li>Chains</li>
<li>Virtual Helpers objects</li>
</ul>
<br />
In this tutorial we will look about <b>Relative positioning</b> more detailly.
<br /><br />
<h3>Relative positioning</h3>
<br />
Relative positioning is one of the basic building block of creating layouts in ConstraintLayout. Those constraints allow you to position a given widget relative to another one. You can constrain a widget on the horizontal and vertical axis:
<ul style="list-style-type: circle; background-color: #F1F1F1; padding-top: 10px; padding-bottom: 10px;">
<li>Horizontal Axis: left, right, start and end sides</li>
<li>Vertical Axis: top, bottom sides and text baseline</li>
</ul>
Here is the list of available constraints.
<ul style="list-style-type: circle; background-color: #F1F1F1; padding-top: 10px; padding-bottom: 10px;">
<li style="color:green">layout_constraintLeft_toLeftOf</li>
<li style="color:green">layout_constraintLeft_toRightOf</li>
<li style="color:green">layout_constraintRight_toLeftOf</li>
<li style="color:green">layout_constraintRight_toRightOf</li>
<li style="color:green">layout_constraintTop_toTopOf</li>
<li style="color:green">layout_constraintTop_toBottomOf</li>
<li style="color:green">layout_constraintBottom_toTopOf</li>
<li style="color:green">layout_constraintBottom_toBottomOf</li>
<li style="color:green">layout_constraintBaseline_toBaselineOf</li>
<li style="color:green">layout_constraintStart_toEndOf</li>
<li style="color:green">layout_constraintStart_toStartOf</li>
<li style="color:green">layout_constraintEnd_toStartOf</li>
<li style="color:green">layout_constraintEnd_toEndOf</li>
</ul>
They all take a reference id to another widget, or the parent (which will reference the parent container, i.e. the ConstraintLayout):
<br />
For example
<pre class="brush: xml">
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="match_parent">
<View
android:id="@+id/view1"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@android:color/holo_green_dark"
app:layout_constraintBottom_toTopOf="@+id/view3"
app:layout_constraintEnd_toStartOf="@+id/view2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="@+id/view2"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@android:color/holo_orange_dark"
app:layout_constraintBottom_toTopOf="@+id/view3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/view1"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="@+id/view3"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@android:color/holo_blue_dark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/view1" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Constraint Layout"
android:textColor="@android:color/holo_red_dark"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</pre>
This xml will create following output.
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiVzUvwHDfwl8ygyeYBHk_TM3v0Uknh_e2VmlH_eEOm_ei6tSHNlPAIo-qpQRDrNG8pt_OUOsiJ1sRBcpaUfhwz3HRosamkmhVlpzgX_MWrK_2hnTqP-9sJSkoWbsWZXoez4Ta0Wjdl-gEI/s1600/device-2017-10-30-130621.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiVzUvwHDfwl8ygyeYBHk_TM3v0Uknh_e2VmlH_eEOm_ei6tSHNlPAIo-qpQRDrNG8pt_OUOsiJ1sRBcpaUfhwz3HRosamkmhVlpzgX_MWrK_2hnTqP-9sJSkoWbsWZXoez4Ta0Wjdl-gEI/s320/device-2017-10-30-130621.png" width="206" height="320" data-original-width="1031" data-original-height="1600" /></a></div>
<h3>Explaination</h3>
<pre class="brush: xml">
<View
android:id="@+id/view1"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@android:color/holo_green_dark"
app:layout_constraintBottom_toTopOf="@+id/view3"
app:layout_constraintEnd_toStartOf="@+id/view2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</pre>
this code block indicates the system to align this view's bottom should be top of the <b>view3</b>, End should be start of the <b>view2</b>, Start should be start of the <b>parent</b> layout and Top should be top of the <b>parent</b> layout.
<br />
<pre class="brush: xml">
<View
android:id="@+id/view2"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@android:color/holo_orange_dark"
app:layout_constraintBottom_toTopOf="@+id/view3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/view1"
app:layout_constraintTop_toTopOf="parent" />
</pre>
this code block indicates the system to align this view's bottom should be top of the <b>view3</b>, End should be end of the <b>parent</b>, Start should be end of the <b>view1</b> layout and Top should be top of the <b>parent</b> layout.
<br />
<pre class="brush: xml">
<View
android:id="@+id/view3"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@android:color/holo_blue_dark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/view1" />
</pre>
this code block indicates the system to align this view's bottom should be bottom of the <b>parent</b>, End should be end of the <b>parent</b>, Start should be start of the <b>parent</b> layout and Top should be bottom of the <b>view1</b>.
<br />
<pre class="brush: xml">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Constraint Layout"
android:textColor="@android:color/holo_red_dark"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</pre>
this code block indicates the system to align this view's bottom should be bottom of the <b>parent</b> layout , End should be end of the <b>parent</b> layout , Start should be start of the <b>parent</b> layout and Top should be bottom of the <b>parent</b> layout, this is center alignment of the parent vertically and horizontally.
<br /></br />
If you want to align center of parent horizontally only, then you should use
<ul style="list-style-type: circle; background-color: #F1F1F1; padding-top: 10px; padding-bottom: 10px;">
<li style="color:green">app:layout_constraintEnd_toEndOf="parent"</li>
<li style="color:green">app:layout_constraintStart_toStartOf="parent"</li>
</ul>
If you want to align center of parent vertically only, then you should use
<ul style="list-style-type: circle; background-color: #F1F1F1; padding-top: 10px; padding-bottom: 10px;">
<li style="color:green">app:layout_constraintBottom_toBottomOf="parent"</li>
<li style="color:green">app:layout_constraintTop_toTopOf="parent"</li>
</ul>
And also you can use
<ul style="list-style-type: circle; background-color: #F1F1F1; padding-top: 10px; padding-bottom: 10px;">
<li style="color:green">layout_constraintHorizontal_bias</li>
<li style="color:green">layout_constraintVertical_bias</li>
</ul>
For example the following will make the left side with a 30% bias instead of the default 50%, such that the left side will be shorter, with the widget leaning more toward the left side
<pre class="brush: xml">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Constraint Layout"
android:textColor="@android:color/holo_red_dark"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintHorizontal_bias="0.3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</pre>
<br />
<br /><br />
Here is the full video tutorial
<iframe width="560" height="315" src="https://www.youtube.com/embed/QLRXXGXSqZA" frameborder="0" gesture="media" allowfullscreen></iframe>
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then share this post with your friends.
<br /><br />
<h3 style="text-align: center;">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br />
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0tag:blogger.com,1999:blog-7580237816735071324.post-69483412601727563292017-10-25T04:59:00.000-07:002017-10-25T05:12:11.588-07:00Simple way to show menu items on list item get selected<div dir="ltr" style="text-align: left;" trbidi="on">
Here is the most easier way to showing menu items on list items get selected.
Your Activity will look like this
<pre class="brush: java">
public class MainActivity extends AppCompatActivity {
private RecyclerView myList;
private int selectedCount;
private ArrayList<Item> list;
private MyListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
myList = (RecyclerView) findViewById(R.id.myList);
myList.setHasFixedSize(true);
myList.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
list.add(new Item("Row " + (i + 1)));
}
adapter = new MyListAdapter(list, this);
myList.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return selectedCount > 0;
}
public void onLongClicked(int adapterPosition) {
list.get(adapterPosition).isSelected = true;
selectedCount++;
adapter.notifyDataSetChanged();
invalidateOptionsMenu();
}
public void onClicked(int adapterPosition) {
if (selectedCount > 0) {
Item item = list.get(adapterPosition);
if (item.isSelected) {
selectedCount--;
} else {
selectedCount++;
}
item.setSelected(!item.isSelected);
adapter.notifyDataSetChanged();
invalidateOptionsMenu();
}
}
}
</pre>
And your adapter will look like,
<pre class="brush: java">
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ViewHolder> {
private ArrayList<Item> myList;
private MainActivity activity;
public MyListAdapter(ArrayList<Item> myList, MainActivity mainActivity) {
this.myList = myList;
activity = mainActivity;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_list_item, parent, false));
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.textView.setText(myList.get(position).text);
if (myList.get(position).isSelected) {
holder.view.setBackgroundColor(ContextCompat.getColor(activity, R.color.colorAccent));
}else {
holder.view.setBackgroundColor(Color.WHITE);
}
holder.view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
activity.onLongClicked(holder.getAdapterPosition());
return true;
}
});
holder.view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
activity.onClicked(holder.getAdapterPosition());
}
});
}
@Override
public int getItemCount() {
return myList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
View view;
TextView textView;
public ViewHolder(View itemView) {
super(itemView);
view = itemView;
textView = itemView.findViewById(R.id.text);
}
}
}
</pre>
And your Item class will look like,
<pre class="brush: java">
public class Item {
boolean isSelected;
String text;
public Item(String text) {
this.text = text;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
</pre>
And your activity_main layout will look like,
<pre class="brush: xml">
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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="com.guna.testapplication.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
</pre>
And your content_main layout will look like,
<pre class="brush: xml">
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.guna.testapplication.MainActivity"
tools:showIn="@layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="@+id/myList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
</pre>
And your menu_main will look like,
<pre class="brush: xml">
<menu 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"
tools:context="com.guna.testapplication.MainActivity">
<item
android:id="@+id/action_share"
android:title="@string/share"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_delete"
android:orderInCategory="100"
android:title="@string/delete"
app:showAsAction="never" />
</menu>
</pre>
And your my_list_item layout will look like
<pre class="brush: xml">
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="1dp"
android:background="#fff"
android:orientation="vertical">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp" />
</LinearLayout>
</pre>
<br /><br />
Here is the full video tutorial
<iframe width="560" height="315" src="https://www.youtube.com/embed/k2GPuS-qwlo" frameborder="0" gesture="media" allowfullscreen></iframe>
<br />
<h3>Interesting right?</h3>
<br />
If you are really interested in this code, then share this post with your friends.
<br /><br />
<h3 style="text-align: center;">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input name="cmd" type="hidden" value="_s-xclick" />
<input name="hosted_button_id" type="hidden" value="83SNHDTB99JP8" />
<input class="btn" name="submit" type="submit" value="Donate" />
<!--<input type="image" src="https://www.paypalobjects.com/en_GB/i/btn/btn_cart_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">-->
</form>
<br />
<b><span style="color: blue;">Thank You</span></b></h3>
<br />
<br /></div>
Gunaseelan Ahttp://www.blogger.com/profile/01344239526874962371noreply@blogger.com0