How to create ImageView, TextView or other views with transparent effect dynamically on button click.
Changing Alpha of a view makes the view transparent and display the view behind smoothly with gesture effect. So in android application we can easily programmatically set any view’s Alpha like ImageView, TextView, Button ..etc using ObjectAnimator class. This class allows us to manage decreasing opacity using timing effect so it looks like a animation. You can also set the Alpha timing. So here is the complete step by step tutorial for Change view Alpha/Opacity in android programmatically.
How to Change view Alpha/Opacity in android programmatically.
Code for MainActivity.java file.
package com.changeviewalpha_android_examples.com; import android.animation.ObjectAnimator; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { TextView txt; Button btn; ObjectAnimator objectanimator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txt = (TextView)findViewById(R.id.textView1); btn = (Button)findViewById(R.id.button1); objectanimator = ObjectAnimator.ofFloat(txt,"Opacity",0.6f); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { objectanimator.setDuration(4000); objectanimator.start(); } }); } }
Code for activity_main.xml layout file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.changeviewalpha_android_examples.com.MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="fill_parent" android:layout_height="100dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="86dp" android:background="#011ffd" android:gravity="center" android:text="TextView" android:textAppearance="?android:attr/textAppearanceLarge" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="48dp" android:text="Click here to set view Alpha/Opacity of in android programmatically" /> </RelativeLayout>
Screenshot: