安卓开发之ListView(HorizontalListView)横向动态加载数据例子

 更新时间:2016年9月20日 19:53  点击:1950
android 用到一个HorizontalListView 可以实现横向加载数据了这里我们就一起来看一个HorizontalListView横向动态加载数据例子,具体如下所示。

这个自定义的控件可以实现横向的动态数据加载,话不多说,下面上代码。(使用方法和普通listview一致)

1、在布局里用HorizontalScrollView包含一个ListView;
2、利用GridView,把它的行数设为1行;

HorizontalListView.java:
package cn.zmit.xianneng.widget;

import java.util.LinkedList;
import java.util.Queue;

import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.Scroller;

public class HorizontalListView extends AdapterView<ListAdapter> {

public boolean mAlwaysOverrideTouch = true;
protected ListAdapter mAdapter;
private int mLeftViewIndex = -1;
private int mRightViewIndex = 0;
protected int mCurrentX;
protected int mNextX;
private int mMaxX = Integer.MAX_VALUE;
private int mDisplayOffset = 0;
protected Scroller mScroller;
private GestureDetector mGesture;
private Queue<View> mRemovedViewQueue = new LinkedList<View>();
private OnItemSelectedListener mOnItemSelected;
private OnItemClickListener mOnItemClicked;
private OnItemLongClickListener mOnItemLongClicked;
private boolean mDataChanged = false;
public HorizontalListView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}

private synchronized void initView() {
mLeftViewIndex = -1;
mRightViewIndex = 0;
mDisplayOffset = 0;
mCurrentX = 0;
mNextX = 0;
mMaxX = Integer.MAX_VALUE;
mScroller = new Scroller(getContext());
mGesture = new GestureDetector(getContext(), mOnGesture);
}

@Override
public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener listener) {
mOnItemSelected = listener;
}

@Override
public void setOnItemClickListener(AdapterView.OnItemClickListener listener){
mOnItemClicked = listener;
}

@Override
public void setOnItemLongClickListener(AdapterView.OnItemLongClickListener listener) {
mOnItemLongClicked = listener;
}

private DataSetObserver mDataObserver = new DataSetObserver() {

@Override
public void onChanged() {
synchronized(HorizontalListView.this){
mDataChanged = true;
}
invalidate();
requestLayout();
}

@Override
public void onInvalidated() {
reset();
invalidate();
requestLayout();
}

};

@Override
public ListAdapter getAdapter() {
return mAdapter;
}

@Override
public View getSelectedView() {
//TODO: implement
return null;
}

@Override
public void setAdapter(ListAdapter adapter) {
if(mAdapter != null) {
mAdapter.unregisterDataSetObserver(mDataObserver);
}
mAdapter = adapter;
mAdapter.registerDataSetObserver(mDataObserver);
reset();
}

private synchronized void reset(){
initView();
removeAllViewsInLayout();
requestLayout();
}

@Override
public void setSelection(int position) {
//TODO: implement
}

private void addAndMeasureChild(final View child, int viewPos) {
LayoutParams params = child.getLayoutParams();
if(params == null) {
params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}

addViewInLayout(child, viewPos, params, true);
child.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST));
}

@Override
protected synchronized void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);

if(mAdapter == null){
return;
}

if(mDataChanged){
int oldCurrentX = mCurrentX;
initView();
removeAllViewsInLayout();
mNextX = oldCurrentX;
mDataChanged = false;
}

if(mScroller.computeScrollOffset()){
int scrollx = mScroller.getCurrX();
mNextX = scrollx;
}

if(mNextX <= 0){
mNextX = 0;
mScroller.forceFinished(true);
}
if(mNextX >= mMaxX) {
mNextX = mMaxX;
mScroller.forceFinished(true);
}

int dx = mCurrentX – mNextX;

removeNonVisibleItems(dx);
fillList(dx);
positionItems(dx);

mCurrentX = mNextX;

if(!mScroller.isFinished()){
post(new Runnable(){
@Override
public void run() {
requestLayout();
}
});

}
}

private void fillList(final int dx) {
int edge = 0;
View child = getChildAt(getChildCount()-1);
if(child != null) {
edge = child.getRight();
}
fillListRight(edge, dx);

edge = 0;
child = getChildAt(0);
if(child != null) {
edge = child.getLeft();
}
fillListLeft(edge, dx);
}

private void fillListRight(int rightEdge, final int dx) {
while(rightEdge + dx < getWidth() && mRightViewIndex < mAdapter.getCount()) {

View child = mAdapter.getView(mRightViewIndex, mRemovedViewQueue.poll(), this);
addAndMeasureChild(child, -1);
rightEdge += child.getMeasuredWidth();

if(mRightViewIndex == mAdapter.getCount()-1) {
mMaxX = mCurrentX + rightEdge – getWidth();
}

if (mMaxX < 0) {
mMaxX = 0;
}
mRightViewIndex++;
}

}

private void fillListLeft(int leftEdge, final int dx) {
while(leftEdge + dx > 0 && mLeftViewIndex >= 0) {
View child = mAdapter.getView(mLeftViewIndex, mRemovedViewQueue.poll(), this);
addAndMeasureChild(child, 0);
leftEdge -= child.getMeasuredWidth();
mLeftViewIndex–;
mDisplayOffset -= child.getMeasuredWidth();
}
}

private void removeNonVisibleItems(final int dx) {
View child = getChildAt(0);
while(child != null && child.getRight() + dx <= 0) {
mDisplayOffset += child.getMeasuredWidth();
mRemovedViewQueue.offer(child);
removeViewInLayout(child);
mLeftViewIndex++;
child = getChildAt(0);

}

child = getChildAt(getChildCount()-1);
while(child != null && child.getLeft() + dx >= getWidth()) {
mRemovedViewQueue.offer(child);
removeViewInLayout(child);
mRightViewIndex–;
child = getChildAt(getChildCount()-1);
}
}

private void positionItems(final int dx) {
if(getChildCount() > 0){
mDisplayOffset += dx;
int left = mDisplayOffset;
for(int i=0;i<getChildCount();i++){
View child = getChildAt(i);
int childWidth = child.getMeasuredWidth();
child.layout(left, 0, left + childWidth, child.getMeasuredHeight());
left += childWidth + child.getPaddingRight();
}
}
}

public synchronized void scrollTo(int x) {
mScroller.startScroll(mNextX, 0, x – mNextX, 0);
requestLayout();
}

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean handled = super.dispatchTouchEvent(ev);
handled |= mGesture.onTouchEvent(ev);
return handled;
}

protected boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
synchronized(HorizontalListView.this){
mScroller.fling(mNextX, 0, (int)-velocityX, 0, 0, mMaxX, 0, 0);
}
requestLayout();

return true;
}

protected boolean onDown(MotionEvent e) {
mScroller.forceFinished(true);
return true;
}

private OnGestureListener mOnGesture = new GestureDetector.SimpleOnGestureListener() {

@Override
public boolean onDown(MotionEvent e) {
return HorizontalListView.this.onDown(e);
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return HorizontalListView.this.onFling(e1, e2, velocityX, velocityY);
}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {

synchronized(HorizontalListView.this){
mNextX += (int)distanceX;
}
requestLayout();

return true;
}

@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
for(int i=0;i<getChildCount();i++){
View child = getChildAt(i);
if (isEventWithinView(e, child)) {
if(mOnItemClicked != null){
mOnItemClicked.onItemClick(HorizontalListView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId( mLeftViewIndex + 1 + i ));
}
if(mOnItemSelected != null){
mOnItemSelected.onItemSelected(HorizontalListView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId( mLeftViewIndex + 1 + i ));
}
break;
}

}
return true;
}

@Override
public void onLongPress(MotionEvent e) {
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (isEventWithinView(e, child)) {
if (mOnItemLongClicked != null) {
mOnItemLongClicked.onItemLongClick(HorizontalListView.this, child, mLeftViewIndex + 1 + i, mAdapter.getItemId(mLeftViewIndex + 1 + i));
}
break;
}

}
}

private boolean isEventWithinView(MotionEvent e, View child) {
Rect viewRect = new Rect();
int[] childPosition = new int[2];
child.getLocationOnScreen(childPosition);
int left = childPosition[0];
int right = left + child.getWidth();
int top = childPosition[1];
int bottom = top + child.getHeight();
viewRect.set(left, top, right, bottom);
return viewRect.contains((int) e.getRawX(), (int) e.getRawY());
}
};

}

Eclipse编辑器是许多开发者会用到的一个编辑器了,我信下面来为各位介绍一篇关于Eclipse编辑器的安装操作步骤,具体如下所示。
重要,更新安卓SDK的时候要有梯子,需要滋备hosts文件
 
 
 
在windows安装Android的开发环境不简单也说不上算复杂,本文写给第一次想在自己Windows上建立Android开发环境投入Android浪潮的朋友们,为了确保大家能顺利完成开发环境的搭建,文章写的尽量详细,希望对准备进入Android开发的朋友有帮助。
 
本教程将分为五个步骤来完成Android开发环境的部署。
第一步:安装JDK。
第二步:配置Windows上JDK的变量环境 。
第三步: 下载安装Eclipse 。
第四步:下载安装Android SDK 。
第五步:为Eclipse安装ADT插件。

第一步:安装JDK

要下载Oracle公司的JDK可以百度“JDK”进入Oracle公司的JDK下载页面(当前下载页面地址为http://www.oracle.com/technetwork/java/javase/downloads/index.html),选择自己电脑系统的对应版本即可。
 
下载到本地电脑后双击进行安装。JDK默认安装成功后,会在系统目录下出现两个文件夹,一个代表jdk,一个代表jre。
 
JDK的全称是Java SE Development Kit,也就是Java 开发工具箱。SE表示标准版。JDK是Java的核心,包含了Java的运行环境(Java Runtime Environment),一堆Java工具和给开发者开发应用程序时调用的Java类库。
 
我们可以打开jdk的安装目录下的Bin目录,里面有许多后缀名为exe的可执行程序,这些都是JDK包含的工具。通过第二步讲到的配置JDK的变量环境,我们可以方便地调用这些工具及它们的命令。
 
 
JDK包含的基本工具主要有:
javac:Java编译器,将源代码转成字节码。
jar:打包工具,将相关的类文件打包成一个文件。
javadoc:文档生成器,从源码注释中提取文档。
jdb:debugger,调试查错工具。
java:运行编译后的java程序。
 
第二步:配置Windows上JDK的变量环境
 
很多刚学java开发的人按照网上的教程可以很轻松配置好Windows上JDK的变量环境,但是为什么要这么配置并没有多想。
 
我们平时打开一个应用程序,一般是通过桌面的应用程序图标双击或单击系统开始菜单中应用程序的菜单链接,无论是桌面的快捷图标还是菜单链接都包含了应用程序的安装位置信息,打开它们的时候系统会按照这些位置信息找到安装目录然后启动程序。
 
 
知道了一个应用程序的安装目录位置,我们也可以通过命令行工具打开,如QQ的位置为:C:\Program Files (x86)\Tencent\QQ\QQProtect\Bin,QQ的应用程序名为为QQProtect.exe,那么我们打开命令行工具,然后进入到“C:\Program Files (x86)\Tencent\QQ\QQProtect\Bin”目录,再输入“QQProtect”,即可运行qq。
 
 
如果我们希望打开命令行工具后,直接输入“QQProtect”就能启动qq程序,而不是每次都进入qq的安装目录再启动,这个时候可以通过配置系统环境变量Path来实现。右击“我的电脑”,选择“属性”,在打开窗口中点击左边的“高级系统设置”,出现“系统属性”窗口,在“高级”选项卡下面点击“环境变量”。
 
 
编辑系统变量名“Path”,在“Path”变量(字符串内容)的后面追加qq的安装目录:;C:\Program Files (x86)\Tencent\QQ\QQProtect\Bin 注意追加的时候要在目录字符串的前面加个英文的分号;,英文分号是用来区分Path里面不同的路径。
 
 
确定保存后,再回到命令窗口,不管在任何目录下,你只要输入qqprotect的命令,qq就会启动。
 
 
通过启动qq的例子,我们总结下:当要求系统启动一个应用程序时,系统会先在当前目录下查找,如果没有则在系统变量Path指定的路径去查找。前面我们说了JDK包含了一堆开发工具,这些开发工具都在JDK的安装目录下,为了方便使用这些开发工具,我们有必要把JDK的安装目录设置了系统变量。这就是为什么在Windows安装了JDK后需要设置JDK的bin目录为系统环境变量的原因。
 
为了配置JDK的系统变量环境,我们需要设置三个系统变量,分别是JAVA_HOME,Path和CLASSPATH。下面是这三个变量的设置防范。
 
JAVA_HOME
先设置这个系统变量名称,变量值为JDK在你电脑上的安装路径:C:\Program Files\Java\jdk1.8.0_20。创建好后则可以利用%JAVA_HOME%作为JDK安装目录的统一引用路径。
 
Path
PATH属性已存在,可直接编辑,在原来变量后追加:;%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin 。
 
CLASSPATH 
设置系统变量名为:CLASSPATH  变量值为:.;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar 。
注意变量值字符串前面有一个"."表示当前目录,设置CLASSPATH 的目的,在于告诉Java执行环境,在哪些目录下可以找到您所要执行的Java程序所需要的类或者包。
 
第三步: 下载安装Eclipse
 
Eclipse为Java应用程序及Android开发的IDE(集成开发环境)。Eclipse不需要安装,下载后把解压包解压后,剪切eclipse文件夹到你想安装的地方,打开时设置你的工作目录即可。
 
Eclipse的版本有多个,这里选择下载Eclipse IDE for Java EE Developers这个版本。
 
 
 
第四步:下载安装Android SDK
 
配置了JDK变量环境,安装好了Eclipse,这个时候如果只是开发普通的JAVA应用程序,那么Java的开发环境已经准备好了。我们要通过Eclipse来开发Android应用程序,那么我们需要下载Android SDK(Software Development Kit)和在Eclipse安装ADT插件,这个插件能让Eclipse和Android SDK关联起来。
 
Android SDK提供了开发Android应用程序所需的API库和构建、测试和调试Android应用程序所需的开发工具。
打开http://developer.android.com/sdk/index.html,我们发现google提供了集成了Eclipse的Android Developer Tools,因为我们这次是已经下载了Eclipse,所以我们选择单独下载Android SDK。
 
 
下载后双击安装,指定Android SDK的安装目录,为了方便使用Android SDK包含的开发工具,我们在系统环境变量中的Path设置Android SDK的安装目录下的tools目录。
 
在Android SDK的安装目录下,双击“SDK Manager.exe”,打开Android SDK Manager,Android SDK Manage负责下载或更新不同版本的SDK包,我们看到默认安装的Android SDK Manager只安装了一个版本的sdk tools。
 
 
打开Android SDK Manager,它会获取可安装的sdk版本,但是国内有墙,有时候会出现获取失败的情况。
 
 
从弹出的log窗口中,我们可以看到连接 “https://dl-ssl.google.com”失败了。我们通过ping命令,发现果然网络不通。
 
 
从万能的互联网上,我们找到了解决这个问题的方案,而且行之有效。
 
更改host文件
首先更改host文件,host文件在C:\Windows\System32\drivers\etc目录下,用记事本打开“hosts”文件,将下面两行信息追加到hosts文件末尾,保存即可。如果你的是windows8系统可能没有权限修改host文件,可以右击hosts文件,将Users组设置为可对hosts文件完全控制的权限即可。
 
203.208.46.146 dl.google.com
203.208.46.146 dl-ssl.google.com
 
上面两行放在host文件的意思是将本地访问dl.google.com和dl-ssl.google.com定向到ip地址为203.208.46.146的服务器上。
 
 
将Android SDK Manage上的https请求改成http请求
打开Android SDK Manager,在Tools下的 Options 里面,有一项 Force https://..sources to be fetched using http://... 将这一项勾选上,就可以了。
 
 
再打开Android SDK Manager.exe,正常情况下就可以下载Android的各个版本的sdk了。你只需要选择想要安装或更新的安装包安装即可。这里是比较耗时的过程,还会出现下载失败的情况,失败的安装包只需要重新选择后再安装就可以了。
 
 
如果通过更改DNS也无法下载Android SDK,还有两个方法,第一个是自备梯子FQ,第二个是从这个网站上下载,下载的地址是:http://www.androiddevtools.cn/
 
第五步:为Eclipse安装ADT插件
 
前面我们已经配置好了java的开发环境,安装了开发Android的IDE,下载安装了Android SDK,但是Eclipse还没有和Android SDK进行关联,也就是它们现在是互相独立的,就好比枪和子弹分开了。为了使得Android应用的创建,运行和调试更加方便快捷,Android的开发团队专门针对Eclipse IDE定制了一个插件:Android Development Tools(ADT)。
下面是在线安装ADT的方法:
启动Eclipse,点击 Help菜单 -> Install New Software… ?,点击弹出对话框中的Add… 按钮。
 
然后在弹出的对话框中的Location中输入:http://dl-ssl.google.com/android/eclipse/,Name可以输入ADT,点击“OK”按钮。
 
 
在弹出的对话框选择要安装的工具,然后下一步就可以了。
 
 
安装好后会要求你重启Eclipse,Eclipse会根据目录的位置智能地和它相同目录下Android sdk进行关联,如果你还没有通过sdk manager工具安装Android任何版本的的sdk,它会提醒立刻安装它们。
 
 
如果Eclipse没有自动关联Android sdk的安装目录,那么你可以在打开的Eclipse选择 Window -> Preferences ,在弹出面板中就会看到Android设置项,填上安装的SDK路径,则会出现刚才在SDK中安装的各平台包,按OK完成配置。
 
 
到这里,我们在windows上的Android上的开发环境搭建就完成了,这时候,你用Eclipse的File——》New——》Project...新建一个项目的时候,就会看到建立Android项目的选项了。
 
本文章来为各位介绍一个关于tableView 上添加Tableview 实现左右滑动功能例子,希望这个例子可以帮助到各位android开发者吧。

有时候我们在使用tableView 的时候不仅仅需要它能够上下滑动,而且还要做到左右滑动的效果.下面就介绍一种比较简单的实现方法.


zmitTableView = [[UITableView alloc] initWithFrame:CGRectMake(0 , 0, kScreenWidth, kScreenHeight)];

zmitTableView = [UIColor whiteColor];


secondTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,100, kScreenWidth, kScreenHeight)];

secondTableViewTableView.backgroundColor = [UIColor whiteColor];

secondTableView.scrollEnabled = NO;

secondTableView.userInteractionEnabled = YES;

[zmitTableView addSubview:secondTableView];

[self.view addSubview:  zmitTableView];

首先创建两个tableview ,然后给secondTableView加上拖动手势

UIPanGestureRecognizer   *panGestureRecognize = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];

-(void)handlePan:(UIPanGestureRecognizer *)sender

{

CGPoint translatin = [sender translationInView:secondTableView];

sender.view.center = CGPointMake(sender.view.center.x + translatin.x, sender.view.center.y);

[sender setTranslation:CGPointZero inView:self.YidaScrollView.scrollViewTableView];

}

这样的话就实现了第二个tableView的左右滑动效果,并且不影响第一个tableView的上下滑动.

本文章来为各位介绍一篇关于Android标准、固定和沉浸式状态栏的实现例子,希望这个例子能够帮助到各位更深入的理解Android标准、固定和沉浸式状态栏的用法。
今天总结了一下状态栏的颜色设置,常见的有固定的颜色或者沉浸式的实现,废话不多说,直接上图。
标准:
d
 
 
 
 
 
 
 
 
 
固定颜色:
2
 
 
 
 
 
 
 
 
 
沉浸式:
1
 
 我个人最新沉浸式的实现,但是这个功能只支持Android4.4以上的系统。
下面来说一下具体的实现过程。
首先,标准的就不说了,默认的就是。然后再说沉浸,最复杂的放后面。

沉浸很简单,两句代码搞定:

在Activity中的setContentView(R.layout.activity_main);之前加上:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    // 透明状态栏
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    // 透明导航栏
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
再说固定颜色的设置,需要一个依赖的java文件,先贴出来等会要用。还有一个要注意的地方,这种方式需要在当前activity的布局文件中的最外层加上android:fitsSystemWindows=”true”这个属性。

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout.LayoutParams;
import java.lang.reflect.Method;
@SuppressWarnings({ "unchecked", "rawtypes" })
public class SystemStatusManager
{
    static
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                Class c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Throwable e) {
                sNavBarOverride = null;
            }
        }
    }
    /**
     * The default system bar tint color value.
     */
    public static final int DEFAULT_TINT_COLOR = 0x99000000;
    private static String sNavBarOverride;
    private final SystemBarConfig mConfig;
    private boolean mStatusBarAvailable;
    private boolean mNavBarAvailable;
    private boolean mStatusBarTintEnabled;
    private boolean mNavBarTintEnabled;
    private View mStatusBarTintView;
    private View mNavBarTintView;
    /**
     * Constructor. Call this in the host activity onCreate method after its
     * content view has been set. You should always create new instances when
     * the host activity is recreated.
     *
     * @param activity The host activity.
     */
    @TargetApi(19)
    public SystemStatusManager(Activity activity) {
        Window win = activity.getWindow();
        ViewGroup decorViewGroup = (ViewGroup) win.getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // check theme attrs
            int[] attrs = {android.R.attr.windowTranslucentStatus,
                    android.R.attr.windowTranslucentNavigation};
            TypedArray a = activity.obtainStyledAttributes(attrs);
            try {
                mStatusBarAvailable = a.getBoolean(0, false);
                mNavBarAvailable = a.getBoolean(1, false);
            } finally {
                a.recycle();
            }
            // check window flags
            WindowManager.LayoutParams winParams = win.getAttributes();
            int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            if ((winParams.flags & bits) != 0) {
                mStatusBarAvailable = true;
            }
            bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
            if ((winParams.flags & bits) != 0) {
                mNavBarAvailable = true;
            }
        }
        mConfig = new SystemBarConfig(activity, mStatusBarAvailable, mNavBarAvailable);
        // device might not have virtual navigation keys
        if (!mConfig.hasNavigtionBar()) {
            mNavBarAvailable = false;
        }
        if (mStatusBarAvailable) {
            setupStatusBarView(activity, decorViewGroup);
        }
        if (mNavBarAvailable) {
            setupNavBarView(activity, decorViewGroup);
        }
    }
    /**
     * Enable tinting of the system status bar.
     *
     * If the platform is running Jelly Bean or earlier, or translucent system
     * UI modes have not been enabled in either the theme or via window flags,
     * then this method does nothing.
     *
     * @param enabled True to enable tinting, false to disable it (default).
     */
    public void setStatusBarTintEnabled(boolean enabled) {
        mStatusBarTintEnabled = enabled;
        if (mStatusBarAvailable) {
            mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
        }
    }
    /**
     * Enable tinting of the system navigation bar.
     *
     * If the platform does not have soft navigation keys, is running Jelly Bean
     * or earlier, or translucent system UI modes have not been enabled in either
     * the theme or via window flags, then this method does nothing.
     *
     * @param enabled True to enable tinting, false to disable it (default).
     */
    public void setNavigationBarTintEnabled(boolean enabled) {
        mNavBarTintEnabled = enabled;
        if (mNavBarAvailable) {
            mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
        }
    }
    /**
     * Apply the specified color tint to all system UI bars.
     *
     * @param color The color of the background tint.
     */
    public void setTintColor(int color) {
        setStatusBarTintColor(color);
        setNavigationBarTintColor(color);
    }
    /**
     * Apply the specified drawable or color resource to all system UI bars.
     *
     * @param res The identifier of the resource.
     */
    public void setTintResource(int res) {
        setStatusBarTintResource(res);
        setNavigationBarTintResource(res);
    }
    /**
     * Apply the specified drawable to all system UI bars.
     *
     * @param drawable The drawable to use as the background, or null to remove it.
     */
    public void setTintDrawable(Drawable drawable) {
        setStatusBarTintDrawable(drawable);
        setNavigationBarTintDrawable(drawable);
    }
    /**
     * Apply the specified alpha to all system UI bars.
     *
     * @param alpha The alpha to use
     */
    public void setTintAlpha(float alpha) {
        setStatusBarAlpha(alpha);
        setNavigationBarAlpha(alpha);
    }
    /**
     * Apply the specified color tint to the system status bar.
     *
     * @param color The color of the background tint.
     */
    public void setStatusBarTintColor(int color) {
        if (mStatusBarAvailable) {
            mStatusBarTintView.setBackgroundColor(color);
        }
    }
    /**
     * Apply the specified drawable or color resource to the system status bar.
     *
     * @param res The identifier of the resource.
     */
    public void setStatusBarTintResource(int res) {
        if (mStatusBarAvailable) {
            mStatusBarTintView.setBackgroundResource(res);
        }
    }
    /**
     * Apply the specified drawable to the system status bar.
     *
     * @param drawable The drawable to use as the background, or null to remove it.
     */
    @SuppressWarnings("deprecation")
    public void setStatusBarTintDrawable(Drawable drawable) {
        if (mStatusBarAvailable) {
            mStatusBarTintView.setBackgroundDrawable(drawable);
        }
    }
    /**
     * Apply the specified alpha to the system status bar.
     *
     * @param alpha The alpha to use
     */
    @TargetApi(11)
    public void setStatusBarAlpha(float alpha) {
        if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mStatusBarTintView.setAlpha(alpha);
        }
    }
    /**
     * Apply the specified color tint to the system navigation bar.
     *
     * @param color The color of the background tint.
     */
    public void setNavigationBarTintColor(int color) {
        if (mNavBarAvailable) {
            mNavBarTintView.setBackgroundColor(color);
        }
    }
    /**
     * Apply the specified drawable or color resource to the system navigation bar.
     *
     * @param res The identifier of the resource.
     */
    public void setNavigationBarTintResource(int res) {
        if (mNavBarAvailable) {
            mNavBarTintView.setBackgroundResource(res);
        }
    }
    /**
     * Apply the specified drawable to the system navigation bar.
     *
     * @param drawable The drawable to use as the background, or null to remove it.
     */
    @SuppressWarnings("deprecation")
    public void setNavigationBarTintDrawable(Drawable drawable) {
        if (mNavBarAvailable) {
            mNavBarTintView.setBackgroundDrawable(drawable);
        }
    }
    /**
     * Apply the specified alpha to the system navigation bar.
     *
     * @param alpha The alpha to use
     */
    @TargetApi(11)
    public void setNavigationBarAlpha(float alpha) {
        if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mNavBarTintView.setAlpha(alpha);
        }
    }
    /**
     * Get the system bar configuration.
     *
     * @return The system bar configuration for the current device configuration.
     */
    public SystemBarConfig getConfig() {
        return mConfig;
    }
    /**
     * Is tinting enabled for the system status bar?
     *
     * @return True if enabled, False otherwise.
     */
    public boolean isStatusBarTintEnabled() {
        return mStatusBarTintEnabled;
    }
    /**
     * Is tinting enabled for the system navigation bar?
     *
     * @return True if enabled, False otherwise.
     */
    public boolean isNavBarTintEnabled() {
        return mNavBarTintEnabled;
    }
    private void setupStatusBarView(Context context, ViewGroup decorViewGroup) {
        mStatusBarTintView = new View(context);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight());
        params.gravity = Gravity.TOP;
        if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) {
            params.rightMargin = mConfig.getNavigationBarWidth();
        }
        mStatusBarTintView.setLayoutParams(params);
        mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
        mStatusBarTintView.setVisibility(View.GONE);
        decorViewGroup.addView(mStatusBarTintView);
    }
    private void setupNavBarView(Context context, ViewGroup decorViewGroup) {
        mNavBarTintView = new View(context);
        LayoutParams params;
        if (mConfig.isNavigationAtBottom()) {
            params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getNavigationBarHeight());
            params.gravity = Gravity.BOTTOM;
        } else {
            params = new LayoutParams(mConfig.getNavigationBarWidth(), LayoutParams.MATCH_PARENT);
            params.gravity = Gravity.RIGHT;
        }
        mNavBarTintView.setLayoutParams(params);
        mNavBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
        mNavBarTintView.setVisibility(View.GONE);
        decorViewGroup.addView(mNavBarTintView);
    }
    /**
     * Class which describes system bar sizing and other characteristics for the current
     * device configuration.
     *
     */
    public static class SystemBarConfig {
        private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height";
        private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height";
        private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape";
        private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width";
        private static final String SHOW_NAV_BAR_RES_NAME = "config_showNavigationBar";
        private final boolean mTranslucentStatusBar;
        private final boolean mTranslucentNavBar;
        private final int mStatusBarHeight;
        private final int mActionBarHeight;
        private final boolean mHasNavigationBar;
        private final int mNavigationBarHeight;
        private final int mNavigationBarWidth;
        private final boolean mInPortrait;
        private final float mSmallestWidthDp;
        private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) {
            Resources res = activity.getResources();
            mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
            mSmallestWidthDp = getSmallestWidthDp(activity);
            mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME);
            mActionBarHeight = getActionBarHeight(activity);
            mNavigationBarHeight = getNavigationBarHeight(activity);
            mNavigationBarWidth = getNavigationBarWidth(activity);
            mHasNavigationBar = (mNavigationBarHeight > 0);
            mTranslucentStatusBar = translucentStatusBar;
            mTranslucentNavBar = traslucentNavBar;
        }
        @TargetApi(14)
        private int getActionBarHeight(Context context) {
            int result = 0;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TypedValue tv = new TypedValue();
                context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
                result = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
            }
            return result;
        }
        @TargetApi(14)
        private int getNavigationBarHeight(Context context) {
            Resources res = context.getResources();
            int result = 0;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                if (hasNavBar(context)) {
                    String key;
                    if (mInPortrait) {
                        key = NAV_BAR_HEIGHT_RES_NAME;
                    } else {
                        key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME;
                    }
                    return getInternalDimensionSize(res, key);
                }
            }
            return result;
        }
        @TargetApi(14)
        private int getNavigationBarWidth(Context context) {
            Resources res = context.getResources();
            int result = 0;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                if (hasNavBar(context)) {
                    return getInternalDimensionSize(res, NAV_BAR_WIDTH_RES_NAME);
                }
            }
            return result;
        }
        @TargetApi(14)
        private boolean hasNavBar(Context context) {
            Resources res = context.getResources();
            int resourceId = res.getIdentifier(SHOW_NAV_BAR_RES_NAME, "bool", "android");
            if (resourceId != 0) {
                boolean hasNav = res.getBoolean(resourceId);
                // check override flag (see static block)
                if ("1".equals(sNavBarOverride)) {
                    hasNav = false;
                } else if ("0".equals(sNavBarOverride)) {
                    hasNav = true;
                }
                return hasNav;
            } else { // fallback
                return !ViewConfiguration.get(context).hasPermanentMenuKey();
            }
        }
        private int getInternalDimensionSize(Resources res, String key) {
            int result = 0;
            int resourceId = res.getIdentifier(key, "dimen", "android");
            if (resourceId > 0) {
                result = res.getDimensionPixelSize(resourceId);
            }
            return result;
        }
        @SuppressLint("NewApi")
        private float getSmallestWidthDp(Activity activity) {
            DisplayMetrics metrics = new DisplayMetrics();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
            } else {
                activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
            }
            float widthDp = metrics.widthPixels / metrics.density;
            float heightDp = metrics.heightPixels / metrics.density;
            return Math.min(widthDp, heightDp);
        }
        /**
         * Should a navigation bar appear at the bottom of the screen in the current
         * device configuration? A navigation bar may appear on the right side of
         * the screen in certain configurations.
         *
         * @return True if navigation should appear at the bottom of the screen, False otherwise.
         */
        public boolean isNavigationAtBottom() {
            return (mSmallestWidthDp >= 600 || mInPortrait);
        }
        /**
         * Get the height of the system status bar.
         *
         * @return The height of the status bar (in pixels).
         */
        public int getStatusBarHeight() {
            return mStatusBarHeight;
        }
        /**
         * Get the height of the action bar.
         *
         * @return The height of the action bar (in pixels).
         */
        public int getActionBarHeight() {
            return mActionBarHeight;
        }
        /**
         * Does this device have a system navigation bar?
         *
         * @return True if this device uses soft key navigation, False otherwise.
         */
        public boolean hasNavigtionBar() {
            return mHasNavigationBar;
        }
        /**
         * Get the height of the system navigation bar.
         *
         * @return The height of the navigation bar (in pixels). If the device does not have
         * soft navigation keys, this will always return 0.
         */
        public int getNavigationBarHeight() {
            return mNavigationBarHeight;
        }
        /**
         * Get the width of the system navigation bar when it is placed vertically on the screen.
         *
         * @return The width of the navigation bar (in pixels). If the device does not have
         * soft navigation keys, this will always return 0.
         */
        public int getNavigationBarWidth() {
            return mNavigationBarWidth;
        }
        /**
         * Get the layout inset for any system UI that appears at the top of the screen.
         *
         * @param withActionBar True to include the height of the action bar, False otherwise.
         * @return The layout inset (in pixels).
         */
        public int getPixelInsetTop(boolean withActionBar) {
            return (mTranslucentStatusBar ? mStatusBarHeight : 0) + (withActionBar ? mActionBarHeight : 0);
        }
        /**
         * Get the layout inset for any system UI that appears at the bottom of the screen.
         *
         * @return The layout inset (in pixels).
         */
        public int getPixelInsetBottom() {
            if (mTranslucentNavBar && isNavigationAtBottom()) {
                return mNavigationBarHeight;
            } else {
                return 0;
            }
        }
        /**
         * Get the layout inset for any system UI that appears at the right of the screen.
         *
         * @return The layout inset (in pixels).
         */
        public int getPixelInsetRight() {
            if (mTranslucentNavBar && !isNavigationAtBottom()) {
                return mNavigationBarWidth;
            } else {
                return 0;
            }
        }
    }
}
好了,然后我把主activity贴出来吧。

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTranslucentStatus();
        setContentView(R.layout.activity_main);
    }
    private void setTranslucentStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            SystemStatusManager tintManager = new SystemStatusManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.red);//你要设置的颜色
            getWindow().getDecorView().setFitsSystemWindows(true);
        }
    }
}
好了,这就实现了上面效果图的第二张,固定的状态栏颜色。

下面我们来看一篇关于Android通过滑动控制ListView的高度的例子,希望这篇文章可以让各位同学更好的了解ListView的使用方法,具体如下。
首先上一下图:Screenshot_2016-01-20-20-07-08 Screenshot_2016-01-20-20-07-24
上下滑动上图红框标注的部位时,改变listView的高度,
start
1、获取ListView的LayoutParams:
LayoutParams params= listView.getLayoutParams();
2、为RelativeLayout设置手势监听:
mRlBus.setOnTouchListener(new View.OnTouchListener() {//mRlBus为红框处外层布局
float y=0;//在此处定义一个y,接收Y坐标
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
y=event.getY();//当手指按在RelativeLayout的某个地方时触发,获取当前纵坐标.
break;
case MotionEvent.ACTION_MOVE:
float x= event.getY()-y;//在此定义一个x,意思为滑动的每一刻,当前时刻的纵坐标减去最初刚按下手指的纵坐标
if(x>0||params.height<=250){//如果手指是向下滑(x=0)或者ListView的高度小于250,
params.height= (int) (params.height-x); //则执行降低或者升高ListView的操作
if(params.height>250){//这个步骤的意思为:假设用户很快速的往上滑,可能造成高度大于250
params.height=250;//如果过高,那么固定为250
}
}
if(params.height<0){//这个步骤的意思为:假设用户很快速的往下滑,可能造成高度小于0,造成ListView选取滑动之前的高度为当前高度
params.height=0;
}
listView.setLayoutParams(params);
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
});
如果帮到了观众们,点个赞吧~
[!--infotagslink--]

相关文章

  • 用js的document.write输出的广告无阻塞加载的方法

    一、广告代码分析很多第三方的广告系统都是使用document.write来加载广告,如下面的一个javascript的广告链接。复制代码 代码如下:<script type="text/javascript" src="http://gg.5173.com/adpolestar/5173/;ap=2EBE5...2014-06-07
  • jQuery页面加载初始化常用的三种方法

    当页面打开时我们需要执行一些操作,这个时候如果我们选择使用jquery的话,需要重写他的3中方法,自我感觉没什么区 别,看个人喜好了,第二种感觉比较简单明了: 第一种: 复制代码 代码如下: <script type="text/javas...2014-06-07
  • 解决IDEA插件市场Plugins无法加载的问题

    这篇文章主要介绍了解决IDEA插件市场Plugins无法加载的问题,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-21
  • Android WebView加载html5页面实例教程

    如果我们要在Android应用APP中加载html5页面,我们可以使用WebView,本文我们分享两个WebView加载html5页面实例应用。 实例一:WebView加载html5实现炫酷引导页面大多...2016-09-20
  • vue3如何按需加载第三方组件库详解

    距离 Vue 3.0 正式版发布已经有一段时间了,关于vue3组件库相关的问题还是挺多人感兴趣的,这篇文章主要给大家介绍了关于vue3如何按需加载第三方组件库的相关资料,需要的朋友可以参考下...2021-06-02
  • AngularJS 实现按需异步加载实例代码

    AngularJS 通过路由支持多视图应用, 可以根据路由动态加载所需的视图, 在 AngularJS 的文档中有详细的介绍, 网上也有不少教程, 就不用介绍了!随着视图的不断增加,js文件会越来越多,而 AngularJS 默认需要把全部的js都一次性...2015-10-21
  • 解决vue动态路由异步加载import组件,加载不到module的问题

    这篇文章主要介绍了解决vue动态路由异步加载import组件,加载不到module的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-07-27
  • Angular性能优化之第三方组件和懒加载技术

    这篇文章主要介绍了Angular性能优化之第三方组件和懒加载技术,对性能优化感兴趣的同学,可以参考下...2021-05-11
  • 几种延迟加载JS代码的方法加快网页的访问速度

    本文介绍了如何延迟javascript代码的加载,加快网页的访问速度。 当一个网站有很多js代码要加载,js代码放置的位置在一定程度上将会影像网页的加载速度,为了让我们的网页加载速度更快,本文总结了一下几个注意点...2013-10-13
  • ThinkPHP+jquery实现“加载更多”功能代码

    本篇文章主要介绍了ThinkPHP+jquery实现“加载更多”功能代码,以实例代码讲诉了加载更多的代码实现,非常具有实用价值,需要的朋友可以参考下 ...2017-03-13
  • C#实现带进度条的ListView

    这篇文章主要介绍了C#实现带进度条的ListView 的相关资料,需要的朋友可以参考下...2020-06-25
  • C#获取鼠标在listview右键点击单元格的内容方法

    下面小编就为大家带来一篇C#获取鼠标在listview右键点击单元格的内容方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • 用C++面向对象的方式动态加载so的方法

    下面小编就为大家带来一篇用C++面向对象的方式动态加载so的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-04-25
  • jQuery Easyui使用(二)之可折叠面板动态加载无效果的解决方法

    这篇文章主要介绍了jQuery Easyui使用之可折叠面板动态加载无效果的解决方案,非常不错,具有参考借鉴价值,感兴趣的朋友一起看下吧...2016-08-24
  • 基于Pycharm加载多个项目过程图解

    这篇文章主要介绍了基于Pycharm加载多个项目过程图解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-04-22
  • jQuery实现模仿微博下拉滚动条加载数据效果

    这篇文章主要介绍了jQuery实现模仿微博下拉滚动条加载数据效果,涉及jQuery响应下拉滚动事件动态操作页面元素的技巧,需要的朋友可以参考下...2015-12-27
  • C#中调用DLL时未能加载文件或程序集错误的处理方法(详解)

    下面小编就为大家带来一篇C#中调用DLL时未能加载文件或程序集错误的处理方法(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • JavaScript判断图片是否已经加载完毕的方法汇总

    在网上有很多关于判断图片是否已经加载完毕的文章,但是有的浏览器并不适合,下面小编给大家分享一些有关JavaScript判断图片是否已经加载完毕的方法汇总,需要的朋友参考下...2016-02-12
  • 解决vue-loader加载不上的问题

    这篇文章主要介绍了解决vue-loader加载不上的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-10-21
  • javascript自定义加载loading效果

    这篇文章主要为大家详细介绍了javascript自定义加载loading效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-09-15