1. 程式人生 > >Android開發之縱向跑馬燈效果實現

Android開發之縱向跑馬燈效果實現

我們看淘寶、京東等app軟體,首頁就會看到那廣告詞向上走。。。今天我給大家帶來兩種實現方式。效果圖就不上啦,直接上程式碼:
一,自定義view
1,之前經常用findViewById(),今天用另一種方式來找控制元件。在app/build.gradle的閉包中新增如下程式碼:

compile 'com.jakewharton:butterknife:7.0.1'

2,專案中會用到的佈局檔案:
1)activity_main.xml

<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" tools:context="com.gyq.marquee_vertical.MainActivity"> <com.gyq.marquee_vertical.view.LampView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/c12"
android:minHeight="40dp" /> </RelativeLayout>

2)item_lamp_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<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
="wrap_content" >
<TextView android:id="@+id/tv_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:ellipsize="end" android:gravity="center" android:singleLine="true" android:textColor="@color/c9" android:textSize="16sp" /> <TextView android:id="@+id/tv_info" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:ellipsize="end" android:gravity="center_vertical" android:singleLine="true" android:textColor="@color/c5" android:layout_toRightOf="@id/tv_title" android:layout_marginLeft="10dp" android:textSize="16sp" /> </RelativeLayout>

3)lamp_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="45dp"
    android:padding="10dp"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:background="@drawable/ic_launcher"/>

    <com.gyq.marquee_vertical.bean.VerticalLampView
        android:id="@+id/lamp_view"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginLeft="10dp"
        android:layout_gravity="center_vertical"
        android:background="@color/c12"
        />
</LinearLayout>

2,邏輯程式碼
a,AutoScrollData介面

package com.gyq.marquee_vertical.bean;

/**
 * ${DESC}
 * author: gyq
 * create at 2017/1/13 11:25
 */
public interface AutoScrollData<T> {
    String getTextTitle(T data);
    String getTextInfo(T data);
}

b,BaseAutoScrollTextView繼承ListView。

package com.gyq.marquee_vertical.bean;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyq.marquee_vertical.R;

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

/**
 * ${DESC}
 * author: gyq
 * create at 2017/1/13 11:30
 */
public abstract class BaseAutoScrollTextView<T> extends ListView implements AutoScrollData<T> {
    private List<T> mDataList = new ArrayList<>();
    private float mSize = 16;
    private int mMax ;
    private int position = -1;
    private int scroll_Y;
    private int mScrollY;
    private AutoScrollAdapter mAutoScrollAdapter = new AutoScrollAdapter();
    private Context mContext;
    private OnItemClickListener mOnItemClickListener;

    private long mTimer = 1000;

    private Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // 開啟輪播
            switchItem();
            handler.postDelayed(this, mTimer);
        }
    };

    public interface OnItemClickListener {
         void onItemClick(int position);
    }

    private void switchItem() {
        if (position == -1) {
            scroll_Y = 0;
        }else {
            scroll_Y = mScrollY;
        }

        smoothScrollBy(scroll_Y,2000);
        setSelection(position);
        position++;
    }


    public BaseAutoScrollTextView(Context context) {
        this(context,null);
    }

    public BaseAutoScrollTextView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public BaseAutoScrollTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        mScrollY = dp2px(getAdertisementHeight());
        init();
    }

    private void init(){
        this.setDivider(null);
        this.setDividerHeight(0);
        this.setFastScrollEnabled(false);
        this.setEnabled(false);
    }

    private int dp2px(int dipValue) {
        final float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    protected abstract int getAdertisementHeight();

    private class AutoScrollAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            final int count = mDataList == null ? 0 : mDataList.size();
            return count > 1 ? Integer.MAX_VALUE : count;
        }

        @Override
        public Object getItem(int position) {
            return mDataList.get(position % mMax);
        }

        @Override
        public long getItemId(int position) {
            return position % mMax;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (null == convertView) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_lamp_layout,null);

                viewHolder.mTitleView = (TextView)convertView.findViewById(R.id.tv_title);
                viewHolder.mInfoView = (TextView)convertView.findViewById(R.id.tv_info);
                convertView.setTag(viewHolder);
            }else {
                viewHolder = (ViewHolder)convertView.getTag();
            }

            T data = mDataList.get(position % mMax);
            initItemData(position,convertView,viewHolder,data);
            return convertView;
        }
    }

    private void initItemData(final int positions, View convertView, ViewHolder viewHolder, T data) {
        viewHolder.mTitleView.setLayoutParams(new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                dp2px(getAdertisementHeight())));
        viewHolder.mTitleView.setTextSize(mSize);
        viewHolder.mTitleView.setText(getTextTitle(data));

        viewHolder.mInfoView.setTextSize(mSize);
        viewHolder.mInfoView.setText(getTextInfo(data));

        convertView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
               // mOnItemClickListener.onItemClick(positions % mMax);
            }
        });
    }

    static class ViewHolder {
        TextView mTitleView;// 標題
        TextView mInfoView;// 內容
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return false;
    }

    public void setData(List<T> datas) {
        mDataList.clear();
        mDataList.addAll(datas);
        mMax = mDataList == null ? 0 : mDataList.size();
        this.setAdapter(mAutoScrollAdapter);
        mAutoScrollAdapter.notifyDataSetChanged();
    }

    public void setTextSize(float _size) {
        this.mSize = _size;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public void setTimer(long time) {
        this.mTimer = time;
    }

    public void start() {
        handler.postDelayed(runnable,1000);
    }

    public void stop() {
        handler.removeCallbacks(runnable);
    }
}

c.LampBean類

import java.io.Serializable;

/**
 * ${DESC}
 * author: gyq
 * create at 2017/1/13 13:53
 */
public class LampBean implements Serializable {
    public String title;
    public String info;
}

d,

import android.content.Context;
import android.util.AttributeSet;

/**
 * ${DESC}
 * author: gyq
 * create at 2017/1/13 13:54
 */
public class VerticalLampView extends BaseAutoScrollTextView<LampBean> {

    public VerticalLampView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public VerticalLampView(Context context) {
        super(context);
    }

    public VerticalLampView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 這裡面的高度應該和你的xml裡設定的高度一致
     * @return
     */
    @Override
    protected int getAdertisementHeight() {
        return 40;
    }

    @Override
    public String getTextTitle(LampBean data) {
        return data.title;
    }

    @Override
    public String getTextInfo(LampBean data) {
        return data.info;
    }
}

e,LampView 在這個類中,用到了第一步提到的:
第一步:

@Bind(R.id.lamp_view)
VerticalLampView lampView;

第二步:

inflate(getContext(), R.layout.lamp_layout, this);
ButterKnife.bind(this,this);
import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.gyq.marquee_vertical.R;
import com.gyq.marquee_vertical.bean.LampBean;
import com.gyq.marquee_vertical.bean.VerticalLampView;

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

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ${DESC}
 * author: gyq
 * create at 2017/1/13 13:59
 */
public class LampView extends FrameLayout {
    @Bind(R.id.lamp_view)
    VerticalLampView lampView;
    private Context mContext;
    private List<LampBean> list = new ArrayList<>();
    public LampView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        init();
    }

    private void init() {
        setView();
    }

    private void setView() {
        inflate(getContext(), R.layout.lamp_layout, this);
        ButterKnife.bind(this,this);
        initData();
        initView();
    }

    private void initView() {
        lampView.setData((ArrayList<LampBean>) list);
        lampView.setTextSize(15);
        lampView.setTimer(2000);
        lampView.start();
    }

    private void initData() {
        LampBean bean = new LampBean();
        bean.title = "爆款";
        bean.info = "踏青零食上京東,百萬零食1元秒";
        list.add(bean);

        bean = new LampBean();
        bean.title = "公告";
        bean.info = "看老劉中國行,滿129減50!";
        list.add(bean);

        bean = new LampBean();
        bean.title = "活動";
        bean.info = "高姿CC霜全渠道新品首發,領券199減50,點選檢視";
        list.add(bean);
    }
}

二、ViewFlipper
1,新建res/anim資料夾,然後看程式碼:
a.push_up_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="300"
        android:fromYDelta="100%p"
        android:toYDelta="0"/>
    <alpha
        android:duration="300"
        android:fromAlpha="0.0"
        android:toAlpha="1.0"/>
</set>

b.push_up_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="300"
        android:fromYDelta="0"
        android:toYDelta="-100%p"/>
    <alpha
        android:duration="300"
        android:fromAlpha="1.0"
        android:toAlpha="0.0"/>
</set>

2,activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.gyq.marquee_vertical.MainActivity">

    <ViewFlipper
        android:id="@+id/view_flipper"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:flipInterval="2000"/>
</RelativeLayout>

3,layout_item.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="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

4,MainActivity.java

package com.gyq.marquee_vertical;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewFlipper flipper = (ViewFlipper)findViewById(R.id.view_flipper);

        for (int i = 0; i < 5;i++) {
            final int y = i;
            View view = getLayoutInflater().inflate(R.layout.layout_item,null,false);

            //設定點選事件
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this, "快樂" + y, Toast.LENGTH_SHORT).show();
                }
            });

            TextView tv = (TextView) view.findViewById(R.id.tv_content);
            tv.setText("我很快樂" + i);
            flipper.addView(view);

        }

        flipper.setInAnimation(AnimationUtils.loadAnimation(this,R.anim.push_up_in));
        flipper.setOutAnimation(AnimationUtils.loadAnimation(this,R.anim.push_up_out));
        flipper.startFlipping();
    }
}

小結:縱向跑馬燈效果也是一種比較常見的,如果以後專案中用的著,拿去!不謝。