Let’s Create an Android AnnouncemnetView with ViewFlipper

Android AnnouncementView Creation Tutorial using ViewFlipper class

How to create an announcemnet ticker view using ViewFlipper class. That announcementView flips the announcements at
an interval you can set. You simply pass it an arraylist of announcements.

 

This type of view can be very useful if you want a whole of notices or announcements or anything really that you want to show at quick intervals but within a small space. You pass it an arraylist and it just flips them over and over.

Demo

Here’s the gif demo of the project:

AnnouncementsView

AnnouncementsView

Video Tutorial(Recommended)

Our video tutorials contain step by step procedure and explanation. It’s easier to learn visually than reading through text.

Gradle Scripts

(a) Build.gradle

Nothing special. No third party dependency. As usual we only add appcompat support library.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support:appcompat-v7:28.0.0'
}

Layouts

Lets start by exploring the layouts in this project.

We have seven layouts:

(a). activity_main.xml

Here’s our activity_main layout. At the root we have a LinearLayout with vertical orientation. Then a textview to show our header text.

At the center we have our AnnouncementView which will flip our announcements.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    
    
    android_id="@+id/activity_main"
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_orientation="vertical"
    android_background="#009688"
    tools_context=".MainActivity">

    <TextView
        android_id="@+id/headerTxt"
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_text="Announcements View"
        android_textAlignment="center"
        android_fontFamily="casual"
        android_textStyle="bold"
        android_textAppearance="@style/TextAppearance.AppCompat.Large"
        android_textColor="@color/white" />

    <LinearLayout
        android_layout_width="match_parent"
        android_layout_height="56dp"
        android_layout_marginLeft="16dp"
        android_layout_marginRight="16dp"
        android_layout_marginTop="150dp"
        android_gravity="center_vertical">

        <info.camposha.mrannouncementview.AnnouncementView
            android_id="@+id/announcemnet_view"
            android_layout_width="match_parent"
            android_layout_height="wrap_content"/>

    </LinearLayout>

</LinearLayout>

Animations

We will jave two animations.

1. in.xml

This animation will flip our announcements in.

<?xml version="1.0" encoding="utf-8"?>
<set >
    <translate
        android_duration="@android:integer/config_mediumAnimTime"
        android_fromYDelta="50%p"
        android_toYDelta="0"/>
    <alpha
        android_duration="@android:integer/config_mediumAnimTime"
        android_fromAlpha="0.0"
        android_toAlpha="1.0"/>
</set>
2. out.xml

This animation will flip our announcements out.

<?xml version="1.0" encoding="utf-8"?>
<set >
    <translate
        android_duration="@android:integer/config_mediumAnimTime"
        android_fromYDelta="0"
        android_toYDelta="-50%p"/>
    <alpha
        android_duration="@android:integer/config_mediumAnimTime"
        android_fromAlpha="1.0"
        android_toAlpha="0.0"/>
</set>

Java Code.

We have the following java classes for this project:

  1. AnnouncementView.java
  2. MainActivity.java
(a). AnnouncementView.java

This is our custom view to show our announcements. We are extending the ViewFlipper class from the android.widget package. This announcement view will receive announcements as an arraylist and flip them.

package info.camposha.mrannouncementview;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.ViewFlipper;

import java.util.List;

/**
 * Let's extend the ViewFlipper class. This class normally animates between two
 * or more views that have been added to it.
 */
public class AnnouncementView extends ViewFlipper implements View.OnClickListener {

    private Context mContext;
    private List<String> mAnnouncements;

    /**
     * Let's supply two overrides of our constructor
     * @param context
     */
    public AnnouncementView(Context context) { super(context);}
    public AnnouncementView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    /**
     * Let's receive context, set flip interval,padding then set in and
     * out animation
     * @param context
     */
    private void init(Context context) {
        mContext = context;
        setFlipInterval(3000);
        setPadding(dp2px(5f), dp2px(5f), dp2px(5f), dp2px(5f));
        setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.in));
        setOutAnimation(AnimationUtils.loadAnimation(mContext, R.anim.out));
    }

    /**
     * Next thing is for us to create a method that will first receive a list
     * of announcements then flip through them via our AnnouncementView.
     * @param announcements
     */
    public void addAnnouncement(List<String> announcements) {
        //let's remove all child views from the ViewGroup.
        removeAllViews();
        mAnnouncements = announcements;
        for (int i = 0; i < announcements.size(); i++) {
            String currentAnnouncement = announcements.get(i);
            // Let's Build a Tetview based on the content of the announcement
            TextView textView = new TextView(mContext);
            textView.setMaxLines(3);
            textView.setText(currentAnnouncement);
            textView.setTextSize(20f);
            textView.setEllipsize(TextUtils.TruncateAt.END);
            textView.setTextColor(Color.parseColor("#ffffff"));
            textView.setGravity(Gravity.CENTER_VERTICAL);
            // Let's set the location of the announcement to the textView tag.
            textView.setTag(i);
            textView.setOnClickListener(this);
            // Let's add the announcement to the ViewFlipper
            AnnouncementView.this.addView(textView, new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        }
    }

    @Override
    public void onClick(View v) {
        int position = (int) v.getTag();
        String announcement = mAnnouncements.get(position);
        if (mOnAnnouncementClickListener != null) {
            mOnAnnouncementClickListener.onAnnouncementClick(position, announcement);
        }
    }

    /**
     * Notification click monitor interface
     */
    public interface OnAnnouncementClickListener {
        void onAnnouncementClick(int position, String announcement);
    }

    private OnAnnouncementClickListener mOnAnnouncementClickListener;

    /**
     * Set notification click listener
     *
     * @param onAnnouncementClickListener Notification click listener
     */
    public void setOnAnnouncementClickListener(OnAnnouncementClickListener
    onAnnouncementClickListener) {
        mOnAnnouncementClickListener = onAnnouncementClickListener;
    }

    private int dp2px(float dpValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpValue,
                mContext.getResources().getDisplayMetrics());
    }
}
(b). MainActivity.java

Our main activity class. This is where we use our announcement view we created.

package info.camposha.mrannouncementview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    AnnouncementView announcementView;

    /**
     * Let's add and return our announcements
     * @return
     */
    private List<String> getAnnouncements(){
        List<String> announcements = new ArrayList<>();
        announcements.add("First Years come with your ID cards please.");
        announcements.add("Law Students meet me at Dr Sagini Hall 8pm ");
        announcements.add("Good Doctor SN2 on in ABC.Don't miss it.");
        announcements.add("Free snacks for all at the Sadhguru event.");
        announcements.add("College site under maintenance till evening.");
        announcements.add("Betelguese goes supernova. Hey, joking");
        announcements.add("Free dental checkup sponsored by College.");
        announcements.add("One who tried hacking college site.Please STOP.");
        announcements.add("Python wins TIOBE language of Year. Java still top");

        return announcements;
    }

    /**
     * Let's now initialize our AnnouncementView
     */
    private void initializeAnnouncementView() {
        announcementView = findViewById(R.id.announcemnet_view);
        announcementView.addAnnouncement(getAnnouncements());
        announcementView.startFlipping();
    }

    private void handleAnnouncementClick(){
        announcementView.setOnAnnouncementClickListener(new AnnouncementView.OnAnnouncementClickListener() {
            @Override
            public void onAnnouncementClick(int position, String announcement) {
                Toast.makeText(MainActivity.this, announcement, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.initializeAnnouncementView();
        this.handleAnnouncementClick();
    }
}
//end
Download

Below are the download links.

[download id=”7884″ template=”pmpro_button”]

[download id=”7880″ template=”pmpro_button”]

 

Share



Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )