Android TV壁纸库之GridView使用及焦点处理

Android TV GridView中Item焦点处理及滚动条无法滚动的解决方案 在Android TV应用开发中,GridView是常用的布局控件之一,它可以用于展示一组项目,并提供焦点处理和滚动功能。在GridView中,每个Item都应该能够正确地获取和失去焦点。有时候,在Android TV中使用GridView时,可能会遇到滚动条无法滚动的问题。这通常是由于焦点处理不正确导致的。通过以上两个步骤,您应该能够正确处理Android TV GridView中的Item焦点,并解决滚动条无法滚动的问题。在上述代码中,我们通过为GridView设置焦点属性来解决滚动条无法滚动的问题。 阅读详情

首先,给出整个代码的效果图:




这是整个壁纸库应用的效果图,项目地址在这里

一、GridView的介绍:

官网地址


Gridview是一个ViewGroup,它展示的是一个二维的,可滑动的表格.这个表格的item是自动插入的布局,默认使用一个ListAdapter容器。

1.GridView填充数据,这个东西网上的内容太多了,这里不再赘述,只是有一个点需要注意一下:

gridview在笔者实现放大和缩小动画效果的过程中,为了保持选中的item属于最后执行的效果,重写了一下Gridview的getChildDrawingOrder()方法;同时为了避免Gridview在测量item的时候过渡绘制,导致界面卡顿,重写了onMeasure()方法,这里对此作出解释。

代码如下:

/**
 * Created by fengjw on 2018/3/12.
 */

public class MyGridView extends GridView {

    public boolean isOnMeasure;

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setChildrenDrawingOrderEnabled(true); //这里设置为true才能调用getChildDrawingOrder()方法
    }

    @Override
    public void setSelection(int position) {
        Constants.debug("MyGridView setSelection position : " + position);
        Constants.position = position;
        super.setSelection(position);
    }



    @Override
    protected void setChildrenDrawingOrderEnabled(boolean enabled) {
        super.setChildrenDrawingOrderEnabled(enabled);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        isOnMeasure = true;
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        isOnMeasure = false;
        super.onLayout(changed, l, t, r, b);
    }



    @Override
    protected int getChildDrawingOrder(int childCount, int i) {
        if (this.getSelectedItemPosition() != -1){ //不选中默认为-1(INVALID_POSITION),一般从0开始
            if (i + this.getFirstVisiblePosition() == this.getSelectedItemPosition()){//getFirstVisiblePosition获得的是第一个item的位置
                return childCount - 1;
            }
            if (i == childCount - 1){
                return this.getSelectedItemPosition() - this.getFirstVisiblePosition();
            }
        }
        return i;
    }
}
【关于避免过度测绘的问题, 请看这里】

一般来说,GridView的绘制顺序是自上而下的,这样会导致后面的item覆盖了前面的item,所以我们就重写getChildDrawingOrder()方法来改变绘制的顺序。

实现的逻辑是这样的:当我们选中某个item的时候,当前item 也就是i+this.getFirstVisiblePosition的值如果等于选中的position,那么就return childCount -1;也就是最后一个item;不然的话就返回当前的item。这样就会让最后一个绘制的item是我们选择的item。

2.GridView的常用方法介绍:

常用参数:

columnWidth:设置每列固定宽度

gravity:设置每个item的中心

horizontalSpacing:定义水平行间距

numColumns:设置每列显示的数目

stretchMode:定义如何使用多余的空空间.

verticalSpacing:定义垂直行间距

get常用方法:

getNumColumns:得到grid每列的数目

set常用方法:

setNumColumns:设置每列显示的数目

setOnKeyListener:gridview作为一个view的按键监听

setOnItemClickListener:gridview内部item的点击监听

setOnItemSelectedListener:gridview内部选中的监听

setAdapter:设置adapter

setFocusable:设置gridview是否获得焦点

另一个是gridview的刷新:

gridview的刷新主要通过两种方式:

a.setAdapter来刷新容器内容

b.使用容器依赖的Adapter的notifyDataSetChanged().

二、GridView的使用:

1.首先设置一个GridView在资源文件中,并使用自定义MyGridView来extends GridView,重写一些方法。

scrollbars:设置为none,不让侧边的滚动条出现。

listSelector设置的目的是为了消除选中的item的背景黄色。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
     <item android:state_selected="true">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="#00000000"/>
        </shape>
    </item>
    <item android:state_pressed="true">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="#00000000"/>
        </shape>
    </item>
    <item android:state_focused="true">
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <solid android:color="#00000000"/>
        </shape>
    </item>
</selector>

2.在onCreate中设置Gridiveiw的属性,因为是TV开发,我们这里主要注意焦点的位置及处理。

private void initGridView() {
        mGridAdapter = new GridAdapter(this, mList, gridview);
        gridview.setAdapter(mGridAdapter);
        gridview.setOnKeyListener(new GridViewOnKeyListener());
        gridview.setOnItemClickListener(new GridViewOnItemClickListener());
        gridview.setOnItemSelectedListener(new GridViewOnItemSelectedListener());
    }

如最开始的UI效果图,我们在离开gridview和进入gridview的时候,要手动进行focus的设置。为了记录原来离开时Focus的位置,我们定义一个全局的变量,如图:


在onItemSelectedListener中,我们每次进行一次改变当前item的操作,都记录一下position:

private class GridViewOnItemSelectedListener implements AdapterView.OnItemSelectedListener{
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Constants.debug("onItemSelected position : " + position);
            Constants.position = position;
            currentSelectPosition = position;
            mGridAdapter.setSelection(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            Constants.debug("onNothingSelected");
            mGridAdapter.setSelection(-2);
        }
    }

而每次按键的时候,都会响应onKey()操作,我们在GridView的onkey监听中做一下position的处理:

private class GridViewOnKeyListener implements View.OnKeyListener{

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            Constants.debug("GridViewOnKeyListener onKey()");
            if (event.getAction() == KeyEvent.ACTION_DOWN){
                if (keyCode == KeyEvent.KEYCODE_DPAD_UP ){//这里是按键向上的操作
                    if (currentSelectPosition == 3){ //当前选中的position
                        mGridAdapter.setSelection(-2);
                        mMainTopMarketRlRoot.setFocusable(false);
                        mMainTopHomeRlRoot.setFocusable(false);
                        mMainArrowUpRlRoot.setVisibility(View.INVISIBLE);
                        mMainArrowDownRlRoot.setVisibility(View.INVISIBLE);
                        wifiFg.getView().setFocusable(true);
                    }
                    if (currentSelectPosition >= 0 && currentSelectPosition <= 2){
                        Constants.debug(".........");
//                        Constants.position = -2;
//                        currentSelectPosition = -2;
                        mGridAdapter.setSelection(-2);
                        mMainTopMarketRlRoot.setFocusable(true);
                        mMainTopHomeRlRoot.setFocusable(false);
                        mMainArrowUpRlRoot.setVisibility(View.INVISIBLE);
                        mMainArrowDownRlRoot.setVisibility(View.INVISIBLE);
                    }else if (currentSelectPosition > 11){
                        mMainArrowUpRlRoot.setVisibility(View.VISIBLE);
                        mMainArrowDownRlRoot.setVisibility(View.INVISIBLE);
                    }else if (currentSelectPosition >= 8 && currentSelectPosition <=11){
                        mMainArrowUpRlRoot.setVisibility(View.VISIBLE);
                        mMainArrowDownRlRoot.setVisibility(View.VISIBLE);
                    }else if (currentSelectPosition >= 4 && currentSelectPosition <=7){
                        mMainArrowUpRlRoot.setVisibility(View.INVISIBLE);
                        mMainArrowDownRlRoot.setVisibility(View.VISIBLE);
                    }

                }

                if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN){
                    if (currentSelectPosition >= 8 && currentSelectPosition <= 11){
                        mMainArrowUpRlRoot.setVisibility(View.VISIBLE);
                        mMainArrowDownRlRoot.setVisibility(View.INVISIBLE);
                    }else if (currentSelectPosition >= 4 && currentSelectPosition <= 7){
                        mMainArrowUpRlRoot.setVisibility(View.VISIBLE);
                        mMainArrowDownRlRoot.setVisibility(View.VISIBLE);
                    }
                }

            }
            return false;
        }
    }

同时,我们要更新GridView内容,通过在GridAdapter中设置一个方法体来实现:

public void setSelection(int position){
        selectItem = position;
        Constants.debug("selectItem : " + selectItem);
        settingPosition = mPreference.loadSharedPreferences("settingPosition", -2);
        Constants.debug("----------------------");
        Constants.debug("settingPosition : " + settingPosition);
        Constants.debug("----------------------");
        super.notifyDataSetChanged();//刷新adapter
    }

刷新adapter会调用getView方法,从而实现数据的改变操作。


同理,当我们在进入GridView的时候,设置GridView的setFocusable为true,并调用GridAdapter的setSelection方法来达到更新效果。

三、fragment焦点改变的问题

UI效果图第一张的右上角的图标在获得焦点后无法通过监听key值来更改Focus,发现该控件为fragment有很大关系。

所以,我选择了一种方法,通过监听window层的onKeyDown事件来处理,并通过获得当前Focus的View Id方式来手动更改焦点的位置,代码如下:

public boolean onKeyDown(int keyCode, KeyEvent event) {
        Constants.debug("onKeyDown");
        View rootview = this.getWindow().getDecorView();
        int focusId = rootview.findFocus().getId();//这里是获得当前focus id的方法
        Constants.debug("focusId : " + focusId);
        if (focusId == R.id.root_main_top_wifi_fg){
            if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
                wifiFg.getView().setFocusable(false);
                mMainTopHomeRlRoot.setFocusable(false);
                mMainTopMarketRlRoot.setFocusable(true);
                gridview.setFocusable(false);
            }
            if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DPAD_DOWN){
                wifiFg.getView().setFocusable(false);
                mMainTopHomeRlRoot.setFocusable(false);
                mMainTopMarketRlRoot.setFocusable(false);
                gridview.setFocusable(true);
                gridview.requestFocus();
                currentSelectPosition = Constants.position;
                mGridAdapter.setSelection(Constants.position);
                mMainArrowUpRlRoot.setVisibility(View.INVISIBLE);
                mMainArrowDownRlRoot.setVisibility(View.VISIBLE);
            }
        }
        return super.onKeyDown(keyCode, event);//不阻断按键时间的传递
    }

总结:GridView不难,但是要快速上手,还是需要理解一些基础性的东西才行。

========================================

补充:2018.06.08

解决了onCreate gridview的时候,第一个item选中无法放大的方法:

执行onItemSelection的时候,选中第一个item默认会执行放大的动画,但是在第一次启动有Gridview的界面并默认让第一个item持有focus的时候,大多数情况下并不会有该动画,这其实是GridView设计上的一个缺陷。解决方法很简单:

我们调用Gridiview支持的方法会发现,每次当GridView第一次获得焦点的时候,都首次会执行一个onFocusChange的方法,那么我们在这里从新执行setSelection(0),并通过notifyDataSetChanged刷新adapter,来达到我们的目的。

如图:


Android TV,机顶盒Gridview 焦点 切换两个控件之间的焦点,TV、机顶盒用android自带的控件 例如listview或者gridview 是,因为需要适配手机等,所以控件某些方面(如每个控件的焦点,切换时的速度,位置等)是不会很匹配TV、机顶盒的.最好的方法是自己绘制一个gridview <GridView android:id="@+id/lv_main" android:layout_width="wrap_content" android:layout_height="wrap_ 阅读详情

相关推荐

安卓机顶盒相关-TV端GridView焦点移动事件处理.rar

TV端GridView焦点移动事件处理.rar,太多无法一一验证是否可用,程序如果跑不起来需要自调,部分代码功能进行参考学习。

android gridview滑动监听,Android GridView 滑动条设置一直显示状态(推荐)

Android GridView 滑动条设置一直显示状态(推荐)模拟GridView控件:android:id="@+id/picture_grid"android:layout_width="match_parent"android:layout_height="match_parent"android:columnWidth="100dp"android:numColumns="auto_fi...

weixin_42449311的博客 513

Android TV 焦点框移动的实现方法

本篇文章主要介绍了Android TV 焦点框移动的实现方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

Android智能电视焦点控制

随着国际市场上Google TV的发布和国内电视厂商纷纷推出定制Android TV的脚步,一时间智能电视平台成为了众多高科技企业争相抢占的新市场。较早的智能电视平台探索者有Google TV、Apple TV和Samsung Smart TV,还有传说中将要上市的iTV。 AD: 2013云计算架构师峰会精彩课程曝光 焦点控制 导航架构完后,就是焦点移动

那些年我们一起追的Android 2226

WindTerm 安装使用教程

WindTerm是一款Github上开源的 SSH 终端工具,它是完全可以比肩MobaXterm工具的。

m0_69576880的博客 4024

ComfyUI Impact Pack实战:如何用三大检测器打造高效人脸修复工作流(附2025最新模板)

本文详细解析了如何利用ComfyUI Impact Pack中的BBOX、Segm和SAM三大检测器构建高效人脸修复工作流。通过技术选型、参数优化和实战案例,帮助用户掌握从精准定位到细节修复的全流程技巧,特别适用于商业摄影和影视制作场景。文章还提供了2025年最新模板和性能优化方案,显著提升人脸精修效率。

weixin_29040367的博客 245

android 壁纸库,Android TV壁纸库之GridView使用及焦点处理

首先,给出整个代码的效果图:这是整个壁纸库应用的效果图,项目地址在这里一、GridView的介绍:官网地址 Gridview是一个ViewGroup,它展示的是一个二维的,可滑动的表格.这个表格的item是自动插入的布局,默认使用一个ListAdapter容器。1.GridView填充数据,这个东西网上的内容太多了,这里不再赘述,只是有一个点需要注意一下:gridview在笔者实现放大和缩小动画效...

weixin_39582708的博客 401

OSNet代码解析(普通卷积,分组卷积,深度可分离卷积,OSblock组成)

文章目录普通卷积和分组卷积普通卷积和深度可分离卷积用深度可分离卷积(LightConv3x3)代替普通卷积(Conv3x3)减少参数OSBlock (bottleneck)OSNet OSNet之所以轻量(2.2M)在于网络浅,使用深度可分离卷积代替传统卷积,但是很有效 普通卷积和分组卷积 所谓分组卷积,就是右图的input features分成一组一组,如上图groups=3,那么输入的特征分成3组,每组有12/3=4的通道的特征参与输出。然后根据输出通道的维度,得到每组的输入特征要计算两次(6/3=2

Mr_DaYang的博客 9801

android tv gridview,Android TV 重写GridView,实现焦点放大效果

关于缩放,使用了view.setScaleX/Y 方法,api11以上即可。重写dispatchDraw(),绘制选中项的焦点效果。(注意带阴影的焦点图需要微调偏移量)要将选中项绘制显示在顶层,所以要改变GridView的子View绘制顺序;所以要重写bringChildToFront、getChildDrawingOrder,同时要打开setChildrenDrawingOrderEnabled...

weixin_35836405的博客 475

EXCEL VBA从入门到精通 前言

本书通过丰富的实例和案例,帮助读者更好地理解和应用Excel VBA编程,同时也介绍了常用的工具、资源、社区和协作平台等,方便读者进行进一步的学习和开发。我强烈推荐这本书给所有希望学习和掌握Excel VBA编程的读者。多样化的资源和工具介绍:本书介绍了丰富的工具和资源,包括官方文档、在线教程、代码库、论坛、博客等,方便读者进行进一步的学习和开发。详细的讲解和丰富的示例:本书从语法和对象开始讲解,通过丰富的实例和案例,帮助读者更好地理解和应用Excel VBA编程。第一节:什么是VBA 5。

1728

【总目录】AUTOSAR精进之路专栏介绍及内容目录持续更新...

本专栏系统讲解AUTOSAR汽车电子开发技术,包含Eth/OS/Can/Lin等协议栈、MCAL驱动、功能安全等核心模块。内容基于实际项目经验,从概念原理到工程配置、特殊需求实现及问题排查进行深入剖析。重点涵盖TC3xx芯片平台开发、多核OS、网络管理、存储协议栈等难点问题,提供100+篇原创技术文章。专栏采用付费模式,保证内容完整性和持续更新,并提供专业答疑服务。适合汽车电子工程师系统学习AUTOSAR开发技术。

qq_36056498的博客 6505

Android最简单的GridView嵌套GridView,解决滑动冲突问题

gridview嵌套gridview,且内部的gridview不显示完,还能滑动,外部的也可以滑动,解决滑动冲突问题。

u013790519的专栏 1224

【华为OD机试真题 2025双机位A卷】958、 高效的任务规划 | 机试真题+思路参考+代码解析(C++、Java、Py、C语言、JS)

【华为OD机试真题 2025双机位A卷】958、 高效的任务规划 | 机试真题+思路参考+代码解析(C++、Java、Py、C语言、JS) 华为od机试,华为od机试真题,华为od机试E卷,华为odE卷,华为od机试真题E卷,华为OD,华为OD机试,华为OD机试真题,华为od机考,华为od机试D卷,华为od机试真题D卷,华为od手撕代码,华为od,华为od机试C卷,华为od e卷,华为2025e卷,od机试,2025E卷,华为OD机试E卷,什么是华为od,华为od介绍,全面了解华为od,2025华为od,

KJ.JK 1071

Android进阶篇之ListView、GridView以及ScrollView实现按钮控制滚动

这次还是一样,因为项目需要,需要对滚动视图需要手动控制,也就是点击上下左右按钮,能让滚动控件触发对应的操作 在android中,滚动View最基本的有三种,分别是:ListView、GridView和ScrollView 先看效果图:1、ListView的效果图,右下角放置滚动控制按钮 2、GridView的效果图 3、ScrollView 的效果图就不上传了,因为都差不多

ye_scofield 3562

智能汽车嘚啵嘚 --- 智能座舱第七稿:智能座舱的升级OTA

智能汽车嘚啵嘚 --- 智能座舱第七稿:智能座舱的升级OTA

Soly_kun的博客 414

YOLOv8实战教程:从模型训练到改进的全流程指南

回顾这段YOLOv8的实战历程,从最初的模型训练到后来的各种改进尝试,我深刻体会到目标检测技术的魅力与挑战。YOLOv8作为一款优秀的框架,不仅易用性强,而且具备很强的可扩展性,让我能在其基础上不断创新。未来,我计划在以下几个方向继续探索:一是将YOLOv8与多模态技术结合,尝试实现图像与文本的联合目标检测;二是深入研究自监督学习在YOLOv8中的应用,减少对标注数据的依赖;三是探索YOLOv8在更广泛场景的部署,如机器人、自动驾驶等。

LXY_LOVE36的博客 279

安卓TV中Gridview或listview获取不到焦点

子item处理无法点击或者无法获取焦点。

aijiameng的博客 1025

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Android TV开发 TCL电视开发实战 ui适配和焦点控制 Recyclerview自定义

1.常用的adb命令 2.ui适配方案 3.Leanback库简介 4.焦点处理 5.Listview GridView和recycler和自定义Recycler view动态添加view 6.按键失灵的解决办法,按键事件如何分发? 7.播放视频的功能 8.剧集控件绘制 9.Metro 10.和手机app开发的区别 1.调试盒子。 盒子的ip地址与电脑的ip地址保...

深南大盗的博客 2080

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

android实现界面左右滑动(GridView动态设置item,支持每个item按某个属性排序来显示在不同的界面)...

效果图 : 分别是第一页、第二页、第三页,随手截的图,不整齐,勿见怪。开始走了弯路,废了不少时间。 思路如下: 1、用ViewPager实现左右分页滑动,布局最下面远点标记页码是根据有多个item动态添加的。 2、每个页面的GridView的item的个数根据屏幕的宽度高度来动态设置。 3、每个界面的GridView的ada...

weixin_30376323的博客 283

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Android 横向列表GridView 实现横向滚动

Android 横向列表实现,可左右滑动,如下图   1.主界面布局代码:activity_main.xml a.包裹HorizontalScrollView控件是GirdView横向滚动的基本条件b.GirdView外包裹LinearLayout是java代码中参数设置的必要条件 android:layout_width="fill_parent"

水易人间的专栏 1351

Android TV 焦点移动飞框的实现

目前国内传统厂商和互联网厂商所开发的Android智能电视的UI都很类似,其中最常见的就是获得焦点的选中项飞框动画效果的实现了,看上去动画效果很炫酷,能够正确的指引使用者当前所选择的条目。Android电视和Android手机有很大的区别,Android手机带有触摸屏,一般不用特别指示用户所选中的项;而Android电视则不同,不带有触摸屏,一切操作都需要通过遥控或者手机(带红外线)来实现远程操控,

qq402164452的博客 3477

Android 可拖拽的GridView效果实现, 长按可拖拽和item实时交换位置

在Android开发中,我们常常用到ListView和GridView,而有的时候系统的ListView,GridView并不能满足我们的需求,所以我们需要自己定义一个ListView或者GridView,我的上一篇文章中就是自定义的一个左右滑动删除item的例子,大家有兴趣的可以去看看 Android 使用Scroller实现绚丽的ListView左右滑动删除Item效果,今天这篇文章就给大家来

mrleeapple的专栏 3212

android gridview 触摸事件,(源码分析)ScrollView嵌套ListView/GridView的滑动事件处理...

开发过程中经常会遇到使用scrollview嵌套listview或gridview的情况,这时由于scrollview拦截消费了滑动事件,所以在listview或gridview区域滑动时该区域无法滑动,而是scrollview整体滑动。正确的处理应该是当焦点在listview或gridview区域该区域滑动,在区域外则scrollview滑动。想要解决这个问题,加上如下代码即可:listView...

weixin_39796652的博客 232

Android TV 自定义Listview平滑滑动

由于在TV上面的操作不是通过手指来滑动,需要用遥控器来操作,所以Listview中item的焦点处理就显得很重要,但自带的listview会有一个缺点导致操作体验不是很好,那就是item的焦点会随着上下按键显示在最上方和最下方,而且也没有动画效果。

cike123_的博客 477

【Android实战】HorizontalScrollView实现可滑动GridView

HorizontalScrollView实现可滑动GridView

s003603u的专栏 3817

Android HorizontalScrollView结合GridView实现类似网易新闻那样的栏目滑动效果

今天无聊想实现一下网易新闻中栏目滑动的效果,想到了用HorizontalScrollView结合GridView来实现基础的功能: 最重要首先是的是布局: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/t

让创意的火花散落到屏幕的每一个dp 8641
上一篇: Android TV壁纸库之SharedPreferences 实现跨进程通信
下一篇: Android TV壁纸库之存储大小工具类及进度条显示
hacker_crazy
博客等级 码龄13年 58粉丝 114原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值