In this article, ElasticView is added in android. The ElasticView is a regular CardView, which can flex from user touches. OnClickListener and other various important methods can also be added to the child view of ElasticView. It makes the user interface more attractive thereby enhancing the user experience.
Approach:
Step 1: Add the support library in build.gradle file and add the dependency in the dependencies section. It will allow us to add the ElasticView directly in the XML file.
XML
dependencies {
implementation 'com.github.armcha:ElasticView:0.2.0'
}
|
Step 2: Add the following code in the activity_main.xml file. In this file, Elastic View with its child view as ImageView is added to the layout.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent" >
< io.armcha.elasticview.ElasticView
app:flexibility = "7"
android:layout_margin = "20dp"
android:layout_gravity = "center"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
app:cardCornerRadius = "10dp"
app:cardElevation = "5dp" >
< ImageView
android:id = "@+id/imageView"
android:src = "@drawable/gfg"
android:layout_width = "match_parent"
android:layout_height = "wrap_content" />
</ io.armcha.elasticview.ElasticView >
</ LinearLayout >
|
Step 3: Add the following code in the MainActivity.kt file. In this file, OnClickListener is added to ImageView so whenever the user clicks on it, the OnClickListener function gets invoked automatically.
Kotlin
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
var imageView: ImageView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
imageView = findViewById(R.id.imageView);
imageView.setOnClickListener(View.OnClickListener {
Toast.makeText( this , "Click" , Toast.LENGTH_SHORT).show()
})
}
}
|
Java
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
@Override
protected void
onCreate( @Nullable Bundle savedInstanceState)
{
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
imageView.setOnClickListener(
new View.OnClickListener() {
@Override public void onClick(View view)
{
Toast.makeText( this , "Click" ,
Toast.LENGTH_SHORT)
.show();
}
});
}
}
|
Output:
Refer to the official documentation for more information.
Last Updated :
06 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...