Let's Create an Android AnnouncemnetView with ViewFlipper

| Page Views: 92

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:

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
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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 xmlns:android="http://schemas.android.com/apk/res/android">
    <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 xmlns:android="http://schemas.android.com/apk/res/android">
    <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

You can download the full source code below or watch the video from the link provided.

No. Location Link
1. GitHub Direct Download
2. GitHub Browse
3. YouTube Video Tutorial
4. YouTube ProgrammingWizards TV Channel

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.




Recommendations


What do You Think


Previous Post Next Post