android电视机开发

前言:
本质和移动端开发没有什么区别,只是要处理遥控器的按键以及焦点。目前我知道有两种技术路径一种使用leanback,一种使用普通移动端的开发方式只不过焦点需要自己处理。

1、页面隐藏状态栏

参考:Android沉浸式状态栏,看完这篇就够了

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

2、组件放大动画

package com.fangtao.widget;

import android.animation.ValueAnimator;
import android.view.View;
import android.view.animation.DecelerateInterpolator;

public class FocusUtil {

    private final static int duration = 140;

    private final static float startScale = 1.0f;

    //private final static float endScale = 1.14f;

    public static final float SCALE_RATE = 1.045f;//一

   // public static final float SCALE_RATE = 1.0571f;

    /**
     * 当焦点发生变化
     *
     * @param view
     * @param gainFocus
     */
    public static void onFocusChange(View view, boolean gainFocus) {
        if (gainFocus) {
            onFocusIn(view,SCALE_RATE);
        } else {
            onFocusOut(view,SCALE_RATE);
        }
    }

    /**
     * 当view获得焦点
     *
     * @param view
     */
    public static void onFocusIn(final View view,float endScale) {
        ValueAnimator animIn = ValueAnimator.ofFloat(startScale, endScale);
        animIn.setDuration(duration);
        animIn.setInterpolator(new DecelerateInterpolator());
        animIn.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (Float) animation.getAnimatedValue();
                view.setScaleX(value);
                view.setScaleY(value);
            }
        });
        animIn.start();

    }

    /**
     * 当view失去焦点
     *
     * @param view
     */
    public static void onFocusOut(final View view,float endScale) {
        ValueAnimator animOut = ValueAnimator.ofFloat(endScale, startScale);
        animOut.setDuration(duration);
        animOut.setInterpolator(new DecelerateInterpolator());
        animOut.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (Float) animation.getAnimatedValue();
                view.setScaleX(value);
                view.setScaleY(value);
            }
        });

        animOut.start();
    }

}

//使用
 FocusUtil.onFocusIn(view, 1.28f);

3、实现基础布局的圆角

在drawable中编写对应的xml来实现

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/greed" /> <!-- 背景颜色,这里设置为透明 -->
    <!-- 边框宽度 -->
    <!-- 边框颜色 -->
<!--    <stroke-->
<!--        android:width="2dp"-->
<!--        android:color="#9CFFFFFF" />-->
    <corners
        android:radius="20dp" /> <!-- 圆角半径,根据需要进行调整 -->
</shape>

4、实现轮播功能

开源组件:Android轮播(banner)组件的使用 - 简书

5、实现基础布局的渐变色背景

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:angle="90"
        android:endColor="@color/colorPrimary"
        android:startColor="@color/colorAccent" />
</shape>

获取焦点和失去焦点改变透明度

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true">
        <shape>
            <solid android:color="#FF000000" /> <!-- 完全不透明 -->
        </shape>
    </item>
    <item>
        <shape>
            <solid android:color="#B2000000" /> <!-- 半透明 -->
        </shape>
    </item>
</selector>

6、实现videoView组件圆角显示

①使用cardView,这种方式四个角都是圆角,无法单独设置每一个圆角

   <androidx.cardview.widget.CardView
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    app:cardCornerRadius="5dp"
                                    app:cardElevation="0dp"
                                    app:contentPadding="0dp"
                                    >
                                    <VideoView
                                        android:id="@+id/video"
                                        android:layout_width="match_parent"
                                        android:layout_height="match_parent" />
                                </androidx.cardview.widget.CardView>

②其他方式,暂时没有

7、实现图片圆角

①使用第三方图片组件
参考:Android的ImageView必知必会 - 简书

②使用Glide

 RequestOptions options = new RequestOptions()
                    .placeholder(R.drawable.cache)
                    .circleCropTransform();

  GlideApp.with(FangTaoTvApplication.getInstance())
                    .load(merchantInfoModel.getPicture())
                    .placeholder(R.drawable.pic_loading)
                    .apply(options)
                    .into(logoImg);

8、布局

参考:约束布局ConstraintLayout看这一篇就够了 - 简书

9、本地缓存工具

参考:Android本地保存实用工具SpUtil 对SharedPreferences的简单封装_android开发中sp工具类

public class SpUtil{

    private final SharedPreferences sharedPreferences;
    private final SharedPreferences.Editor editor;
    private final Gson gson;
    private static SpUtil spUtil;

    private SpUtil(Context context){
        sharedPreferences = context.getSharedPreferences("sp_data",Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        gson = new Gson();
    }

    public static SpUtilgetInstance (Context context){
        if (spUtil == null){
            spUtil = new SpUtil(context);
        }
        return spUtil;
    }
}

    //保存
   public void putInt(String key, int num){
        editor.putInt(key, num);
        editor.apply();
    }

    public void putString(String key, String content){
        editor.putString(key, content);
        editor.apply();
    }

    public void putBoolean(String key, boolean value){
        editor.putBoolean(key, value);
        editor.apply();
    }

    public void putLong(String key, long value){
        editor.putLong(key, value);
        editor.apply();
    }
    
    //读取
    public int getInt(String key){
        return sharedPreferences.getInt(key, 0);
    }

    public String getString(String key){
        return sharedPreferences.getString(key,"");
    }

    public boolean getBoolean(String key){
        return sharedPreferences.getBoolean(key,false);
    }

    public long getLong(String key){
        return sharedPreferences.getLong(key,0);
    }

    //保存对象
    public void putObject(String key, Object obj){
        String json = gson.toJson(obj);
        putString(key, json);
    }
    
    //获取对象
    public <T> T getObject(String key, Class<T> clazz){
        String json = getString(key);
        if (TextUtils.isEmpty(json)){
            return null;
        }
        return gson.fromJson(json, clazz);
    }
    
    //删除对象
    public void removeObject(String key){
        editor.remove(key);
        editor.apply();
    }

    //保存列表
    public void putObjList(String key, List objectList){
        String json = gson.toJson(objectList);
        putString(key, json);
    }
    
    //获取列表
    public <T> List<T> getObjList(String key){
        List<T> list;
        String json = getString(key);
        if (TextUtils.isEmpty(json)){
            return null;
        }
        list = gson.fromJson(json, new TypeToken<List<T>>(){}.getType());
        return list;
    }

 /**
     * 将map集合转化为json数据保存在sharePreferences中
     *
     * @param key key sharePreferences数据Key
     * @param map map数据
     * @return 保存结果
     */
    public <K,V> boolean putMap(String key , Map<K,V> map){
        boolean result;
        try {
            String json = gson.toJson(map);
            editor.putString(key , json);
            editor.apply();
            result = true;
        }catch (Exception e){
            result = false;
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 从本地获取保存的map数据
     * 缺点:将Integer默认转化为Double
     * */
    public <K,V> HashMap<K,V> getMap(String key){
        String mapJson = getString(key);
        if (TextUtils.isEmpty(mapJson)){
            return null;
        }
        return gson.fromJson(mapJson, new TypeToken<HashMap<K,V>>(){}.getType());
    }

基本使用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        SpUtil spUtil= SpUtil.getInstance(this);
        //简单类型存取
        spUtil.putInt("first", 1);  
        spUtil.getInt("first");
    
        //hashMap存取
        HashMap<String , Integer> map = new HashMap<>();
        map.put("铁柱",30);
        map.put("小凤",28);
        map.put("阿珍",26);
        map.put("阿强",27);
        if (spUtil.putMap("MAP_DATA",map)){
            HashMap<String , Integer> hashMap = spUtil.getMap("MAP_DATA");
            if (hashMap != null ){
                spUtil.showMapData(hashMap);
            }
        }else {
            Log.e(TAG, "1111" );
        }
   }

10、常用监听

①焦点监听

        //搜索
        flTopSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(b) { //选中图片
                    GlideApp.with(MainActivity.getActivity()).asDrawable()
                            .load(R.drawable.home_search_icon_select_v6)
                            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                            .into(new ImageViewTarget<Drawable>(ivSearchIcon) {
                                @Override
                                    protected void setResource(@Nullable Drawable resource) { if(resource!=null) {
                                    ivSearchIcon.setImageDrawable(resource);
                                    }
                                }
                            });
                }else{ //未选中图片
                    GlideApp.with(MainActivity.getActivity()).asDrawable()
                            .load(R.drawable.home_search_icon_unselect_v6)
                            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                            .into(new ImageViewTarget<Drawable>(ivSearchIcon) {
                                @Override
                                protected void setResource(@Nullable Drawable resource) { if(resource!=null) {
                                    ivSearchIcon.setImageDrawable(resource);
                                }
                                }
                            });
                }
            }
        });

②遥控器按键监听

 cflVideo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    switch (keyCode) {
                        case KeyEvent.KEYCODE_DPAD_LEFT:
                            View view1 = findViewById(R.id.cfl_banner);
                            view1.requestFocus();
                            view1.setFocusable(true);
                            view1.setFocusableInTouchMode(true);
                            return true;
                        case  KeyEvent.KEYCODE_DPAD_RIGHT:
                            CustomFrameLayout layout = findViewById(R.id.qcode);
                            layout.requestFocus();
                            layout.setFocusable(true);
                            layout.setFocusableInTouchMode(true);
                            return true;
                        case KeyEvent.KEYCODE_DPAD_UP:
                            TextView button = findViewById(R.id.cfl_my_top_day_update);
                            button.requestFocus();
                            button.setFocusable(true);
                            button.setFocusableInTouchMode(true);
                            return true;
                        case KeyEvent.KEYCODE_DPAD_DOWN:
                            CustomFrameLayout layout1 = findViewById(R.id.cfl_all_commodity);
                            layout1.requestFocus();
                            layout1.setFocusable(true);
                            layout1.setFocusableInTouchMode(true);
                            return true;
                        case KeyEvent.KEYCODE_DPAD_CENTER:
                            if(MusicService.getService().getStatus()){
                                MusicService.getService().pause();
                            }
                            Intent intent = new Intent(MainActivity.this, FullVideoActivity.class);
                            intent.putExtra("videoUrl",re);
                            intent.putExtra("type", type);
                            startActivity(intent);
                            return true;
                        case KeyEvent.KEYCODE_BACK:
                            break;
                    }
                }
                return false;
            }
        });

11、代码中选中组件

cflAllGoods.requestFocus();
cflAllGoods.setFocusable(true); //可以被按键选中
cflAllGoods.setFocusableInTouchMode(true); //可以被触摸选中
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,135评论 6 514
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,317评论 3 397
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,596评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,481评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,492评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,153评论 1 309
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,737评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,657评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,193评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,276评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,420评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,093评论 5 349
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,783评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,262评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,390评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,787评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,427评论 2 359

推荐阅读更多精彩内容