ViewStub HorizontalScrollView

ViewStub组件和<include>标签的作用类似,主要是为了提高布局的重用性,及布局的模块化。它们之间最大的差别是,

  • ViewStub中的布局不会随着它所在布局的渲染而渲染,ViewStub中的布局只有在需要的时候才会渲染到主界面中
  • 而<include>标签中的布局会随着它所在布局的渲染而渲染

include、merge、viewstub的作用

滑屏分页,在iphone中由UIScrollView实现,而android的滑动屏幕由HorizontalScrollView和ScrollView实现,HorizontalScrollView支持横向滑屏,ScrollView支持竖向滑屏,将两者嵌套使用就可以达到iphone的UIScrollView效果:

<ScrollView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:layout_alignParentBottom=”true”
android:layout_alignParentTop=”true”
android:layout_marginBottom=”50dp”
android:scrollbars=”vertical”
>

<HorizontalScrollView
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”horizontal”
android:layout_gravity=”center_horizontal” >

<LinearLayout
android:id=”@+id/allnum”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:gravity=”center”
android:layout_gravity=”center”
android:orientation=”vertical” >
</LinearLayout>
</HorizontalScrollView>
</ScrollView>

HorizontalScrollView是一种FrameLayout(框架布局),其子项被滚动查看时是整体移动的,并且子项本身可以是一个有复杂层次结构的布局管理器。一个常见的应用是子项在水平方向中,用户可以滚动显示顶层水平排列的子项(items)。

HorizontalScrollView不可以和ListView同时用,因为ListView有自己的滚动条设置。最重要的是,如果在需要显示很大的list的情况下,两者同时用则会使ListView在一些重要的优化上失效。出现这种失效的原因在于,HorizontalScrollView会*ListView用HorizontalScrollView本身提供的空间容器(infinite container)来显示完整的列表。
类似的情况,TextView也有自己的滚动条,所以不需要ScrollView。但这两者是可以同时使用的,使用的结果会是在一个更大的容器里显示文本视图。
用HorizontalScrollView包装TableLayout,这样,当内容很长时,就会出现横向滚动条

<HorizontalScrollView
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<TableLayout
android:id=”@+id/tl_forcast_result”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:padding=”10dp”>
</TableLayout>
</HorizontalScrollView>

但此时又出现了另一个问题,加上HorizontalScrollView后,虽然我已经设了TableLayout的宽度是fill_parent。但当内容较少时,TableLayout还是根据内容自适应宽度,不能满屏。 此时,需要设置一个属性就能解决问题了。设置HorizontalScrollView的android:fillViewport=”true”。也就是设置是否将HorizontalScrollView的内容宽度拉伸以适应视口(viewport)

关于分割线: 
我们可以通过在两个TableRow之间添加一个<View>,并设置它的layout_height=”1dip”和background来解决。但这样就多产生了一个View,有点浪费
其实还可以设置TableRow的bottomMargin=1来产生一条分割线。

Gallery widget (adapter-based) is not the best starting point for implementing something like this:

  • It supports padding around each gallery item. Gallery items don’t generally take up all the horizontal space, several can be visible at the same time, next to each other.
  • When user swipes, Gallery flings, potentially over several child elements. Preventing that requires some hacky code.
  • It is adapter-based. Cannot define all the views in singe XML layout, need to create/inflate them in adapter.

The most prominent feature that Gallery has andHorizontalScrollView lacks, is that gallery always tries to center on one of its elements. HorizontalScrollView can be scrolled freely, and will happily stay at any horizontal scroll offset. But this is not hard to fix. By listening in on touch events and detecting flings, I can make it smooth-scroll to the nearest screen-ful in fling’s direction. I’m saying “screen-ful” not “element” because HorizontalScrollView is a subclass of FrameLayout and can only have a single child view. So I’m putting a horizontal LinearLayout in there, and the child views go in that layout. The LinearLayout is slightly hacked too to set appropriate widths for its child views.

Dynamically add to horizontalscrollview

  • the problem is, it creates main horizontalScrollView first, so it goes onMeasure method and calculates mMaxTabWidth. Then it starts to add these customTabView items as much as my tab count. And then it kicks onMeasure of horizontalScrollView again… Here it crashes!
  • HorizontalScrollView scroll = new HorizontalScrollView(this);
    scroll.setFillViewport(true); // if we set it to false, then HorizontalScrollView height measures correctly
  • 设置HorizontalScrollView的android:fillViewport=”true”。也就是设置是否将HorizontalScrollView的内容宽度拉伸以适应视口(viewport)

Your HorizontalScrollView must contain a container like a LinearLayout or a RelativeLayout, grab an instance to that Layout in your activity, and add the views as required…

LinearLayout yourLayout = (LinearLayout)findViewById(R.id.someID);

and then iterate through the number of items in your database and keep adding the views to your Layout until end like this…

for (int i = 0; i < yourData.size(); i++) {             
  TextView tv = new TextView(getApplicationContext());
  tv.setText(yourData.get(i));
  yourLayout.addView(tv);
}

[error] Android ime actionGo doesn’t work

  • android:clipchildren Defines whether a child is limited to draw inside of its bounds or not.
  • android:clipToPadding Defines whether the ViewGroup will clip its drawing surface so as to exclude the padding area.
  • android:weightsum Defines the maximum weight sum.

EditText element needs to be configured as a single-line input. Otherwise, the ‘Enter’ key event will behave as a new-line. This is configured in the xml above with the android:singleLine=”true” attribute.

Different manufacturers make a customized keyboard for their phone which may not completely behave as the android standard keyboard. This issue has been raised before. Most people overcome this issue by either overiding the onKey event or using a TextWatcher class.

android:capitalize is deprecated: Use inputType instead

Be careful if you add both android:capitalize="sentences" and android:inputType=text, as the latter seems to have priority over the first and the input won’t be capitalized.

There’s an specific inputType for automatically capitalizing the first letter

android:autoText=textCapSentences

 

textUri(URI格式) VS text

  • none、
  • text、
  • textCapCharacters字母大小、
  • textCapWords单词首字母大小、
  • textCapSentences仅第一个字母大小
  • textAutoCorrect、textAutoComplete自动完成、
  • textMultiLine多行输入、
  • textImeMultiLine输入法多行(如果支持)、
  • textNoSuggestions不提示、
  • textEmailAddress电子邮件地址、
  • textEmailSubject邮件主题、
  • textShortMessage短信息(会多一个表情按钮出来)
  • textLongMessage长讯息
  • textPersonName人名
  • textPostalAddress地址
  • textPassword密码
  • textVisiblePassword可见密码
  • textWebEditText作为网页表单的文本
  • textFilte文本筛选过滤
  • textPhonetic拼音输入
  • numberSigned有符号数字格式
  • numberDecimal可带小数点的浮点格式
  • phone电话号码
  • datetime时间日期
  • date日期
  • time时间。

android 只能输入数字和字母并且弹出数字键盘

android:digits=”0123456789xyzXYZ”
android:inputType=”number”

EditText中同时加这两条

自定义EditText 外观

自定义信笺纸样式的EditText

14.jpg

默认提示文字:

1.png

2.png

在用户没有输入的时候,我们默认在编辑框中显示“请输入数字”的提示,要实现这一功能很简单,“EditText.setHint(“请输入”)”或者在XML布局文件上写上“android:hint=”请输入””即可
android:layout_gravity=”center_vertical”//设置控件显示的位置:默认 top,这里居中显示,还有bottom

android:hint=”请输入数字!”//设置显示在空间上的提示信息

android:numeric=”integer”//设置只能输入整数,如果是小数则是:decimal

android:singleLine=”true”//设置单行输入,一旦设置为true,则文字不会自动换行。

android:password=”true”//设置只能输入密码

android:textColor = “#ff8c00″//字体颜色

android:textStyle=”bold”//字体,bold, italic, bolditalic

android:textSize=”20dip”//大小

android:capitalize = “characters”//以大写字母写

android:textAlign=”center”//EditText没有这个属性,但TextView有,居中

android:textColorHighlight=”#cccccc”//被选中文字的底色,默认为蓝色

android:textColorHint=”#ffff00″//设置提示信息文字的颜色,默认为灰色

android:textScaleX=”1.5″//控制字与字之间的间距

android:typeface=”monospace”//字型,normal, sans, serif, monospace

android:background=”@null”//空间背景,这里没有,指透明

android:layout_weight=”1″//权重,控制控件之间的地位,在控制控件显示的大小时蛮有用的。

android:textAppearance=”@android:attr/textAppearanceLargeInverse”//EditText始终不弹出软件键盘

EditText默认不弹出软件键盘
方法一:
在 AndroidMainfest.xml中选择哪个activity,设置windowSoftInputMode属性为 adjustUnspecified|stateHidden

android:windowSoftInputMode属性使用

方法二:
让 EditText失去焦点,使用EditText的clearFocus方法
例如:EditText edit=(EditText)findViewById(R.id.edit);
edit.clearFocus();

方法三:
强制隐藏Android输入法窗口

EditText edit=(EditText)findViewById(R.id.edit);

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(edit.getWindowToken(),0);

软件盘

关于Android软键盘弹出,会把原来的界面挤上去的问题~~

在androidMainfest.xml文件中在此Activity中写入  android:windowSoftInputMode=”adjustPan”//

  • “adjustPan” 当前窗口的内容将自动移动以便当前焦点从不被键盘覆盖和用户能总是看到输入内容的部分。这个通常是不期望比调整大小,因为用户可能关闭软键盘以便获得与被覆盖内容的交互操作。

android:windowSoftInputMode 决定活动的主窗口如何与包含屏幕上的软键盘窗口交互:

  • 活动(Activity)成为用户关注的焦点软件盘隐藏或显示
  • 活动的主窗口调整——是否减少活动主窗口大小以便腾出空间放软键盘或是否当活动窗口部分被软键盘覆盖时它的内容的当前焦点是可见的

屏幕整体上移: android:windowSoftInputMode=”adjustUnspecified|stateHidden

  • “stateHidden” 当用户选择该Activity时,软键盘被隐藏——也就是,当用户确定导航到该Activity时,而不是返回到它由于离开另一个Activity。
  • “adjustUnspecified” 它不被指定是否该Activity主窗口调整大小以便留出软键盘的空间,或是否窗口上的内容得到屏幕上当前的焦点是可见的。系统将自动选择这些模式中一种主要依赖于是否窗口的内容有任何布局视图能够滚动他们的内容。如果有这样的一个视图,这个窗口将调整大小,这样的假设可以使滚动窗口的内容在一个较小的区域中可见的。这个是主窗口默认的行为设置。

android:windowSoftInputMode=”adjustResize|stateVisible”

  • “stateVisible” 软键盘是可见的,当那个是正常合适的时(当用户导航到Activity主窗口时)。
  • adjustResize” 该Activity主窗口总是被调整屏幕的大小以便留出软键盘的空间

“stateUnspecified” 软键盘的状态(是否它是隐藏或可见)没有被指定。系统将选择一个合适的状态或依赖于主题的设置。这个是为了软件盘行为默认的设置。

界面加载完成自动弹出软键盘

就是设置一个定时器,让其在页面加载成功后,过一会再运行软键盘弹出事件。界面绘制需要一些时间,如果把弹出软键盘的代码用线程单独跑,会不会就会成功呢?

Timer timer = new Timer();
timer.schedule(new TimerTask(){@Override

public void run() {
InputMethodManager m = (InputMethodManager)
edit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
Toast.makeText(Key.this, “show”, Toast.LENGTH_SHORT).show();
}
}, 1000);

调用数字键盘并设置输入类型和键盘为英文

etNumber.setInputType(InputType.TYPE_CLASS_NUMBER); //调用数字键盘

rlEditText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);//设置输入类型和键盘为英文
或者:android:inputType=”textUri|textMultiLine”

android:capitalize = “characters”//以大写字母写

设置英文字母大写类型。设置如下值:

  • sentences仅第一个字母大写;
  • words每一个单词首字母大小,用空格区分单词;
  • characters每一个英文字母都大写。

不自动弹出键盘

<activity android:name=”.AddLinkman” android:windowSoftInputMode=”adjustUnspecified|stateHidden”/>//不自动弹出键盘

输入结束后关闭键盘

InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(etEditText.getWindowToken(), 0);

Enter键设置

软键盘的Enter键默认显示的是“完成”文本,我们知道按Enter键表示前置工作已经准备完毕了。比如见到的网页中输入url的go按钮,比如搜索的时候search图标。如果能显示“搜索”两个字或者显示一个表示搜索的图标多好。Android提供通过设置android:imeOptions改变默认的“完成”文本。这里举几个常用的常量值:

android:imeOptions=”flagNoExtractUi” //使软键盘不全屏显示,只占用一部分屏幕
同时,这个属性还能控件软键盘右下角按键的显示内容,默认情况下为回车键
android:imeOptions=”actionNone” //输入框右侧不带任何提示
android:imeOptions=”actionGo”   //右下角按键内容为’开始’
android:imeOptions=”actionSearch” //右下角按键为放大镜图片,搜索
android:imeOptions=”actionSend”   //右下角按键内容为’发送’
android:imeOptions=”actionNext”  //右下角按键内容为’下一步’
android:imeOptions=”actionDone” //右下角按键内容为’完成’

(1)actionUnspecified未指定,对应常量EditorInfo.IME_ACTION_UNSPECIFIED效果:

(2)actionNone 没有动作,对应常量EditorInfo.IME_ACTION_NONE效果:

(3)actionGo去往,对应常量EditorInfo.IME_ACTION_GO 效果:

(4)actionSearch 搜索,对应常量EditorInfo.IME_ACTION_SEARCH效果:  android:imeOptions=”actionSearch

(5)actionSend 发送,对应常量EditorInfo.IME_ACTION_SEND效果:

(6)actionNext 下一个,对应常量EditorInfo.IME_ACTION_NEXT效果:

(7)actionDone 完成,对应常量EditorInfo.IME_ACTION_DONE效果:

edittext光标

edittext.requestFocusFromTouch();//让光标放入到点击位置。
edittext.requestFocus();//默认方式获得焦点

EditText editor = (EditText)getCurrentView();//光标处插入
int cursor = editor.getSelectionStart();
editor.getText().insert(cursor,delta);

点击其他位置,edittext隐藏 ,软键盘隐藏

点击其他位置隐藏:

rl_main:整个布局,activity的根布局。

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {  //这个方法不要用错啊。
rl_main.requestFocus();
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
 im.hideSoftInputFromWindow(rl_main.getWindowToken(), 0);
return super.dispatchTouchEvent(ev);
}

Adapter的适用范围

将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。  — 《设计模式》GOF
Adapter模式的宗旨就是,基于现有类所提供的服务,向客户端提供接口,以满足客户的期望。—《java设计模式 》

适配器是AdapterView视图与数据之间的桥梁,用来处理数据并将数据绑定到AdapterView上。AdapterView对象有两个主要任务
1. 在布局中显示数据
2. 处理用户的选择

android提供多种适配器,开发时可以针对数据源的不同采用最方便的适配器,也可以自定义适配器完成复杂功能。

  • BaseAdapter一般的适配器基类可用于将数据绑定到listview、Gallery、GridView 、spinner、AutoCompleteTextView上,当然也可以绑定到ExpandableListView
  • BaseExpandableListAdapter可扩展的适配器基类,可用于将数据绑定到支持展开/收缩功能的列表控件ExpandableListView上,ExpandableListView继承自ListView
  • 当数量较多,比如超过100条或频繁动态增减时使用arrayadapter可以方便控制ui如果仅仅为了显示则使用baseadapter更节省资源

  • ListView控件是竖向滑动的,复用convertView,我们可以加载成千上万的数据; 我们想横向滑动的相册,并且数据有好多,这时候ViewPager控件。
  • ViewPager和ViewFlipper用法类似,但是更好用,左右滑动效果好,而且有类似于ListView的Adapter—PagerAdapter基类,提供回收内存,复用
    • void destroyItem(View container, int position, Object object)//左右滑动的时候,回收较早前的itemView.
    • int getCount()  //ViewPager里显示内容的条数.
    • Object instantiateItem(View container, int position) //初始化ItemView.
  • 设置ViewHolder 为static,也就是静态的,静态类只会在第一次加载时 会耗费比较长时间,但是后面就可以很好帮助加载,同时保证了内存中只有一个ViewHolder,节省了内存的开销。

使用国际化接口 字符数组来 给ArrayAdapter 赋值

<string-array name=”letter”>
<item>A</item>
<item>B</item>
<item>C</item>
<item>D</item>
</string-array>

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.letter,android.R.layout.my_list_item)//只需要显示

ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this,android.R.layout.my_list_item,Arrays.asList(getResources().getTextArray(R.array.letter)))//允许动态增删

在自定义ListView的样式时,需要重写数据接口的ListAdapter类中的getView函数,以此来定制ListView中每个item的样式。当列表里的每一项显示到页面时,都会调用Adapter的getView方法返回一个View。在ListView滑动的过程中,每次getView被执行都会new出一个View对象,长此以往会产生很大的消耗,特别当item中还有Bitmap等 甚至会造成OOM的错误导致程序崩溃

在这里Android系统为了效率的原因引进了ConvertView这一个变量。

  • ConvertView是个view 的缓存,优化:如果存在就不需要重新创建了,没有的话需要通过inflate方法获取。 这样就避免了反复创建大量view的问题。当ListView滑动的过程中,会有item被滑出屏幕而不再被使用,这时候Android会回收这个条目的view 这个view也就是这里的convertView

根据getView调用时间顺序,依次保存convertView。当下一次ListView重写UI,按先进后出的顺序传递给getView函数。

  • Viewholder是个自定义静态类,通过gettag()/settag()convertview关联起来,作用是减少findViewById的次数。因为findViewById会消耗大量时间。
  • View中的setTag(Onbect)表示给View添加一个格外的数据,以后可以用getTag()将这个数据取出来。可以用在多个Button添加一个监听器,每个Button都设置不同的setTag。这个监听器就通过getTag来分辨是哪个Button 被按下。

layout_gravity 和 gravity 的区别

android:gravity是对元素本身说的,元素本身的文本显示在什么地方靠这个属性设置,不设置默认是在左侧的。

android:layout_gravity是相对与它的父元素说的,说明元素显示在父元素的什么位置。比如说button:

  • android:gravity表示button上的字在button上的位置;
  • android:layout_gravity 表示按钮在界面上的位置。

可选值

top、bottom、left、right、center_vertical、fill_vertical、center_horizontal、fill_horizontal、center、fill、clip_vertical,这些属性是可以多选的,用“|”分开。默认这个的值是:Gravity.LEFT

image

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical” 
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
>
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”gravity水平居中”
android:textSize=”20dip”
android:gravity=”center_horizontal” 
    android:background=”#666″ />
<ImageButton
  android:layout_marginTop=”10dip” 
android:layout_marginBottom=”10dip” 
android:id=”@+id/ImageButton01″
android:src=”@drawable/android”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
 android:layout_gravity=”center_horizontal”>
</ImageButton>

<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_gravity=”right”
    android:text=”layout_gravity局右”
android:textSize=”20dip”
android:background=”#666″ />
</LinearLayout>

 

对于LinearLayout何时生效

  • 当 android:orientation=”vertical”  时, 只有水平方向的设置才起作用,垂直方向的设置不起作用。即:left,right,center_horizontal 是生效的
  • 当 android:orientation=”horizontal” 时, 只有垂直方向的设置才起作用,水平方向的设置不起作用。即:top,bottom,center_vertical 是生效的。

在EditText中文字居中显示,而EditText组件自己右对齐到了LinearLayout

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>
<EditText
android:layout_width=”wrap_content”
android:gravity=”center”
android:layout_height=”wrap_content”
android:text=”one”
android:layout_gravity=”right”/>
</LinearLayout>

通过Java代码来设置组件的位置

Button button = new Button(this);
button.setText(“One”);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
//此处相当于布局文件中的Android:layout_gravity属性
lp.gravity = Gravity.RIGHT;
button.setLayoutParams(lp);
//此处相当于布局文件中的Android:gravity属性
button.setGravity(Gravity.CENTER);
LinearLayout linear = new LinearLayout(this);
//注意,对于LinearLayout布局来说,设置横向还是纵向是必须的!否则就看不到效果了。
linear.setOrientation(LinearLayout.VERTICAL);
linear.addView(button);
setContentView(linear);

设置在RelativeLayout中的位置addRule

params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
mContainer.addView(progress,params);

via http://www.cnblogs.com/ghj1976/archive/2011/04/26/2029535.html

 

android 平滑切换屏幕Gallery、HorizontalScrollView、ViewFilpper、ViewFlow、ViewPager

1. ViewFlipper + GestureDetector = 用ViewSwitcher+ 动画效果

android手势识别ViewFlipper触摸动画

ViewFlipper主要用来实现View的自动切换。该类提供了如下几个主要的方法:

  • setFilpInterval:设置View切换的时间间隔。参数为毫秒。
  • startFlipping:开始进行View的切换,时间间隔是上述方法设置的间隔数。切换会循环进行。
  • stopFlipping:停止View切换。
  • setAutoStart:设置是否自动开始。如果设置为“true”,当ViewFlipper显示的时候View的切换会自动开始。

一般情况下,我们都会使用ViewFilpper类实现View的切换,而不使用它的父类ViewAnimator类。

1.1 实现滑动—GestureDetector介绍

如果想要实现滑动翻页的效果,就要了解另外一个类:android.view.GestureDetector类。GestureDetector类中可以用来检测各种手势事件。该类有两个回调接口,分别用来通知具体的事件:

  • GestureDetector.OnDoubleTapListener:用来通知DoubleTap事件,类似于PC上面的鼠标的双击事件。
  • GestureDetector.OnGestureListener:用来通知普通的手势事件,该接口有六个回调方法,具体的可以查看API。这里想要实现滑动的判断,就需要用到其中的onFling()方法

2.Viewflow

viewflow 是 Android 平台上一个视图切换的效果库, 相当于 Android UI 部件提供水平滚动的 ViewGroup使用 Adapter 进行条目绑定。文档上说,当你需要在一系列不确定数目的view中滑动时,可以考虑使用ViewFlow。如果你的view数目确定,你应该使用Fragments 或兼容库里的ViewPager 

3. 自己重写ViewGroup来管理view

创新源于模仿之三:实现左右两个屏幕的切换

4. 对Gallery循环滑动,其实就是对继承自BaseAdapter的类进行操作.

Gallery循环滑动原理

5. HorizontalScrollView

Gallery每次切换图片时都要新建视图,造成太多的资源浪费,当新建项目的API最低为8,其实Gallery这个类已经过期。

The type Gallery is deprecated.This widget is no longer supported. 
ther horizontally scrolling widgets include HorizontalScrollView and ViewPager from the support library.

hsv.jpgHSVDemo.rar

图片中使用了两个HorizontalScrollView,排成上下两行,每行均类似于之前gallery的效果。数据源一行在App的drawable包中,一行在sdcard中,sdk中的图片要自己找了拷进去

5.利用系统自带的ViewPager

ViewPager来源于google 的补充组件android-support-v4.jar, ViewPager类提供了多界面切换的新效果。新效果有如下特征:

  • 当前显示一组界面中的其中一个界面。
  • 用户通过左右滑动界面时,当前的屏幕显示当前界面和下一个界面的一部分
  • 滑动结束后,界面自动跳转到当前选择的界面中

ViewPager提供了一个适配器,方便我们对各个View进行控制,而Workspace需要我们手动去添加,它相当于是一个”静态切换”。使用步骤:

  • 写一个ViewPager的专用Adapter,要继承PagerAdapter, 实现如下方法:

 private class AwesomePagerAdapter extends PagerAdapter{  getCount(), instantiateItem(), destroyItem(), isViewFromObject() }

  • 其后,把你需要展示出来的每一个页面也就是每一个View放到一个ArrayList里面保存起来。传过去给Adapter;
  • 最后把ViewPager实例化,也就是findViewById()。接着就调用ViewPager的setAdapter就OK了

awesomeAdapter = new AwesomePagerAdapter();
awesomePager = (ViewPager) findViewById(R.id.awesomepager);
awesomePager.setAdapter(awesomeAdapter);
mListViews = new ArrayList<View>();
mInflater = getLayoutInflater();//LayoutInflater作用是将layout的xml布局文件实例化为View类对象
mListViews.add(mInflater.inflate(R.layout.layout1, null));
mListViews.add(mInflater.inflate(R.layout.layout2, null));
mListViews.add(mInflater.inflate(R.layout.layout3, null));

6.双向滚动ScrollView

结论

ViewFlipper + Webview——WebView本身的onTouchEvent和ViewFlipper有冲突;

ViewPager + TabhostViewPager多页面滑动切换以及动画效果

ViewPager + ListView

ViewPager+GridView实现GridView左右滑动翻页,实时动态读取数据

ViewFilpper使用时主要是在有限的少数页面切换中比较合适,并且能够自定义每一个切换动画,用于一个应用间的画面切换比较合适,类似于ActivityGroup;

ViewPager与ViewFlow都能够使用适配器进行大量数据的适配。ViewFlow 适用于不确定数目的view中滑动;

ViewFlow由于提供源码,所以在扩展性上更强,可根据需要自行定制,比如加入循环播放等。

Android – PHP – MySQL Scheme

Android Mysql PHP connect

  • connect android device to PHP Script
  • PHP Script will fetch data from the database. It will encode it into json format and send it to the device.
  • Android App will get these encoded data, then parse the data and display it on android device.

The PHP code will be very simple:
– Connect to the database
Run an SQL query, with a WHERE block depending on data from POST/GET values
– Output it in JSON format, the square bracket [ represents starting of an JSONArray node whereas curly bracket { represents JSONObject node.

food.php:

<?php
mysql_connect("127.0.0.1","root","12345");
mysql_select_db("FOOD");
$sql=mysql_query("select * from FOOD where FOOD_NAME like 'A%'");
while($row=mysql_fetch_assoc($sql)) $output[]=$row;
print(json_encode($output));
mysql_close();
?>

Android application:
– Use a HttpPost to get the data,
– Convert response to string
– Parse JSON data, and use it as you want

user unique id – I am generating unique user id in php using uniqid(”, true) function. Sample user id will be like 4f074eca601fb8.88015924

Encrypted Password – This password is stored using base64_encode method. Each password will need two columns to store in database. One is to store encrypted passwordand second column is to store salt used to encrypt the password.

Retrieve Data From a MySQL Database

mysql_fetch_array()which fetch a result row as an associative array, a numeric array, or both.

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) 

via 

read/send data from MySQL via PHP webservice

What is JSON

  • JSON stands for JavaScript Object Notation
  • JSON is lightweight text-data interchange format
  • JSON is language independent
  • JSON is “self-describing” and easy to understand
    (from w3schools)

1. a PHP web service which encodes a string array in to JSON format:  access that web service using Android http client and then it decodes json data

<?php

$data = array('name' => 'Froyo', 'version' => 'Android 2.2');
print (json_encode($data));
?>
Android activity:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://codeincloud.tk/json_android_example.php");
TextView textView = (TextView)findViewById(R.id.textView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
String name = object.getString("name");
String verion = object.getString("version");
textView.setText(name + " - " + verion);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}

2. A Web service to read data from the MySQL database

Java web service deployed on Tomcat server has a method which can run a quarry on database to retrieve data & this method returns results as a string output. To connect web service & database JDBC bridge will be used. The Android application calls that web service method remotely using ksoap library. Then web service runs a query on database table to retrieve data & returns data as a string to Android app. Android app display this data.

import ksoap2 library into project!!

Insert data to a database.

private final String NAMESPACE = "http://ws.login.com";

    private final String SOAP_ACTION = "http://ws.login.com/insertData";
    private final String METHOD_NAME = "insertData";

php用 $_Post[‘key’]可以拿到post数据

How to create a basic web service that provides an XML or JSON response using some PHP and MySQL?

How to connect an Android application to a mysql database via PHP web service?

To make this concrete, the goal is a webservice that accepts data in JSON format via a POST request. The data is simply an array of single-digit integers, e.g., [3, 2, 1].

On the server are images named 0.png, 1.png, 2.png, etc. The webservice takes the images corresponding to those specified in the JSON array and composes them into a montage, using the standard ImageMagick command line tool. For example:

montage 3.png 2.png 1.png 321.png

creates a new single image, 321.png, composed of 3.png, 2.png, and 1.png, all in a row.

E.g.

a simple employee system where the Manager logs in and see all the details of employees who are managed by him:

--Create the database
CREATE DATABASE EmployeeDB;

--Select the database
USE EmployeeDB;

--Create the table
CREATE Table Employees
(
	ID int PRIMARY KEY AUTO_INCREMENT,
	Username varchar(20) UNIQUE,
	Password varchar(8),
	Name varchar(40),
	Address varchar(50),
	Manager int references Employees(ID)
);

Now we’ll insert some values:

Insert into Employees(username,password,name,address)
	values ('guru','123','Guruparan','Colombo');
Insert into Employees (username,password,name,address,manager)
	values ('saman','123','saman','colombo',1);
Insert into Employees (username,password,name,address,manager)
	values ('john','123','john','New York',1);
Insert into Employees(username,password,name,address,manager)
	values ('sean','123','sean','Washington',1);

Now we’ll make the PHP web service which generates the JSON response:

<?php
 //Get the name of the Method
 //The method name has to be passed as Method via post
 $Request_Method=$_REQUEST['method'] or die('Method name not found');

 //Connect to the database
 $Connection = mysql_connect("localhost","root","") or die('Cannot connect to Database');

 //Select the database
 mysql_select_db("EmployeeDB") or die('Cannot select Database');

 //Method to verify the users login
 if($Request_Method=="verifyLogin")
 {
 	//username and password are password are passed via querystrings
 	$username=$_REQUEST['username'];
	$password=$_REQUEST['password'];

	//Generate the sql query based on username and password
	$query="select id from Employees where username='$username' and password='$password'";

	//Execute the query
	$result = mysql_query($query);

	//Get the rowcount
	$rowcount= mysql_num_rows($result);

	//if the count is 0 then no matching rows are found
	if($rowcount==0)
	{
		echo json_encode(array('result'=>0));
	}
	//Else there is an employee with the given credentials
	else {
		$row = mysql_fetch_assoc($result);
		//Get and return his employee id
		echo json_encode(array('result'=>$row['id']));
	}
 }

 //Get all th employees that are managed the by the given emplyee
 if($Request_Method=="getEmployees")
 {
 	$id=$_REQUEST['id'];
	$query="select name,address from Employees where manager=$id";
	$result = mysql_query($query);

	while($row = mysql_fetch_assoc($result))
	{
		$resultArray[] = $row;
	}

	echo json_encode($resultArray);
 }
 //Close Connection
 mysql_close($Connection);
?>

Class Employee and the Loginresult: are to be used by JSON to generate the objects
The Constants class: contains the constants such as the URL of the Web service and the user id of the currently logged in user.
server access class: handles the interaction between the server and the Application

imagesURLArray 中存储url,如果你的url是有规律的,都不需要存储,根据规则生成每一个地址然后传参就好了:

set_time_limit(0);
$imagesURLArray = array_unique($imagesURLArray );

foreach($imagesURLArray as $imagesURL) {
echo $imagesURL;
echo “<br/>”;
file_put_contents(basename($imagesURL), file_get_contents($imagesURL));
}

Connect Android and mysql via php webservices

http://yootles.com/nmontage/go.php?nums=[2,4,6]
<?php
$nums = json_decode($_REQUEST['nums']);//json_decode.
# Lambda functions are a little less ridiculous in php 5.3 but this is the best
# way I know how to do this in php 5.2:
function f($x) { return "$x.png"; }
$cmd = "montage " . implode(" ", array_map("f", $nums)) . " tmp.png";

/*$cmd = "montage";
foreach($images as $image){
  $cmd .= " ".$image.".png";
}
$cmd .= " temp.png";*/
exec($cmd); //set a png-header and use readfile or something similar to get you "tmp.png" header('Content-type: image/png'); readfile('tmp.png'); ?>

How can i record the Android device screen?

There is a long discussion of this on android-developers, but the short answer is: You can’t programatically take a screenshot of an android device’s screen at the moment, unless

  1. You have root access on that phone, or
  2. Your application is a system application

The Android Manifest permission READ_FRAME_BUFFER exists (see the api docs here), but can presently only be used by system applications.

There are various reasons for this, one being that it is a security risk. If an background can take a screenshot of the phone’s screen at any time, then people could use OCR techniques to sniff user’s passwords as they were typed in, among other private information. So no, a VNC application is not possible at the moment without root. To take a screenshot from your computer (while the phone is plugged in via usb) you can use DDMS.

You can try the following library: http://code.google.com/p/android-screenshot-library/ Android Screenshot Library (ASL) enables to programmatically capture screenshots from Android devices without requirement of having root access privileges. Instead, ASL utilizes a native service running in the background, started via the Android Debug Bridge (ADB) once per device boot.

ASL utilizes background native service which performs screen capturing on demand from an application that uses the library. This service has to be started using Android Debug Bridge (ADB), which is an utility program bundled with Android SDK. The service provides screenshot-taking functionality for any application that uses ASL for as long as the phone isn’t rebooted, regardless of whether or not it is connected to the PC.

How to capture video of the screen on Android

Not an app, but if you have a USB cable, you can install the Android SDK on a PC and take screenshots from the PC with androidscreencast, without having to root your phone.

 

BlueAsteroid

Just another WordPress.com site

Jing's Blog

Just another WordPress.com site

Start from here......

我的心情魔方

天才遠私廚

希望能做一個分享各種資訊的好地方

语义噪声

西瓜大丸子汤的博客

笑对人生,傲立寰宇

Just another WordPress.com site

Where On Earth Is Waldo?

A Project By Melanie Coles

the Serious Computer Vision Blog

A blog about computer vision and serious stuff

Cauthy's Blog

paper review...

Cornell Computer Vision Seminar Blog

Blog for CS 7670 - Special Topics in Computer Vision

datarazzi

Life through nerd-colored glasses

Luciana Haill

Brainwaves Augmenting Consciousness

槑烎

1,2,∞

Dr Paul Tennent

and the university of nottingham

turn off the lights, please

A bunch of random, thinned and stateless thoughts around the Web

John's Weblog

Just another WordPress.com weblog

I Am That I Am

Chasing tomorrow's sunrise.