Android TV上下翻屏

Android TV上下翻屏

  • 效果
  • 控件类ScrollLinearLayout
  • ScrollLinearLayoutActivity代码
  • activity_scroll_linear_layout代码
  • 其它

效果

Android TV上下翻屏_第1张图片
初始化页面,用户将光标移动到BUTTON3上,并向上移动焦点。就切换屏幕,下图:
Android TV上下翻屏_第2张图片

控件类ScrollLinearLayout

继承LinearLayout,ScrollLinearLayout.java代码如下:


import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.Scroller;

public class ScrollLinearLayout extends LinearLayout {

    private Scroller scroller;

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

    public ScrollLinearLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        scroller = new Scroller(context);
    }

    public void startScroll(int y) {
        scroller.startScroll(0, getScrollY(), 0, y);
        invalidate();
    }

    @Override
    public void computeScroll() {
        //判断是否滚动完成
        if (scroller.computeScrollOffset()) {
            scrollTo(scroller.getCurrX(), scroller.getCurrY());
        }
    }
}

ScrollLinearLayoutActivity代码

ScrollLinearLayoutActivity.java代码如下:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.Button;

import com.cc.demo.R;


public class ScrollLinearLayoutActivity extends AppCompatActivity {

    private ScrollLinearLayout scrollLinearLayout;
    private Button btn2;
    private Button btn3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scroll_linear_layout);
        //按照720P的绝对值布局进行测试的。
        scrollLinearLayout = (ScrollLinearLayout) findViewById(R.id.svg);
        btn2 = (Button) findViewById(R.id.btn2);
        btn3 = (Button) findViewById(R.id.btn3);
        btn3.requestFocus();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_DPAD_UP:
                    if (btn3.isFocused()) {
                        scrollLinearLayout.startScroll(-600);
                    }
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    if (btn2.isFocused()) {
                        scrollLinearLayout.startScroll(600);
                    }
                    break;
            }
        }
        return super.dispatchKeyEvent(event);
    }

}

activity_scroll_linear_layout代码

activity_scroll_linear_layout.xml 代码如下:




    

其它

  • 根据具体的需求,TV上翻屏也可以用ScrollView来实现。
  • Android TV上的ScrollView和HorizontalScrollView是可以直接使用。和触摸屏上一样。
  • Android TV上也可以正常使用RecyclerView,焦点可能会存在小问题,上拉加载更多和下拉刷新需要自己实现。建议使用开源库TvRecyclerView。

你可能感兴趣的:(Android,TV)