首页 文章 精选 留言 我的

精选列表

搜索[联网搜索API],共10000篇文章
优秀的个人博客,低调大师

Android中文API (109) —— SimpleCursorTreeAdapter

正文 一、结构 public abstract classSimpleCusrorTreeAdapter extends ResourceCusorTreeAdpater java.lang.Object android.widget.BaseExpandableListAdapter android.widget.CursorTreeAdapter android.widget.ResourceCusorTreeAdapter android.widget.SimpleCursorTreeAdapter 二、概述 这是一个用起来很方便的适配器类,它主要将Cursor与在XML文件中定义的TextView或ImageView进行映射。比如,你想设定要展示三列,那么当做好绑定之后,视图就会展示你设定好的那些列;当然了,视图的外观是定义在XML文件里面的,你只需用这个类与视图做好绑定就可以了。(译者注:Android推荐我们尽可能的将组视图和子视图分离开,也就是说不要把整体定义在一个布局文件当中。)与视图绑定有两个阶段。第一阶段:如果使用SimpleCursorTreeAdapter.ViewBinder时,那么就会调用setViewValue(android.view.View, android.database.Cursor, int)方法。该方法返回true就说明绑定成功,否则返回false,这就到了第二阶段,SimpleCursorAdapter内部开始自行绑定,过程是这样的,若绑定到TextView上,调用setViewText(TextView, String);若绑定到ImageView上,调用setViewImage(ImageView, String),如果视图不是TextView或ImageView则抛出IllegalStateException异常。 三、内部类 public interfaceSimpleCursorTreeAdapter.ViewBinder 这个内部接口可以在外部通过SimpleCursorTreeAdapter.ViewBinder的方式进行Cursor与View的绑定。 四、构造函数 publicSimpleCursorTreeAdapter(Context context, Cursor cursor, int collapsedGroupLayout, int expandedGroupLayout, String[] groupFrom, int[] groupTo, int childLayout, int lastChildLayout, String[] childFrom, int[] childTo) 构造函数。 参数 context上下文,多指ExpandableListView的上下文 cursor数据库游标 collapsedGroupLayout布局资源文件标识ID,其定义的是收缩时的ExpandableListView布局样式,并且内部至少要包含参数“groupTo”中指定的视图ID。 expandedGroupLayout布局资源文件标识ID,其定义的是展开时的ExpandableListView布局样式,并且内部至少要包含参数“groupTo”中指定的视图ID。 groupFrom列名列表,显示ExpandableListView的组节点。 groupTo展示参数“groupFrom”中的列,也就是说ExpandableListView中的视图显示的是参数“groupFrom”的列值,它们应该都是TextView或是ImageView。 childLayout布局资源文件标识ID,其定义的是子视图的布局样式(不包括最后一个子视图),内部至少要包含参数“childTo”中指定的视图ID。lastChildLayout布局资源文件标识ID,其定义的是最后一个子视图的布局样式,内部至少要包含参数“childTo”中指定的视图ID。 lastChildLayout布局资源文件标识ID,其定义的是最后一个子视图的布局样式,内部至少要包含参数“childTo”中指定的视图ID。lastChildLayout布局资源文件标识ID,其定义的是最后一个子视图的布局样式,内部至少要包含参数“childTo”中指定的视图ID。 childFrom列名列表,显示ExpandableListView的子节点。 childTo展示参数“childFrom”中的列,也就是说ExpandableListView中的视图显示的是参数“childFrom”的列值,它们应该都是TextView或是ImageView。 publicSimpleCursorTreeAdapter(Context context, Cursor cursor, int collapsedGroupLayout, int expandedGroupLayout, String[] groupFrom, int[] groupTo, int childLayout, String[] childFrom, int[] childTo) 构造函数。(译者注:该构造函数只是少了一个参数lastChildLayout) 参数 context上下文,多指ExpandableListView的上下文 cursor数据库游标 collapsedGroupLayout布局资源文件标识ID,其定义的是收缩时的ExpandableListView布局样式,并且内部至少要包含参数“groupTo”中指定的视图ID。 expandedGroupLayout布局资源文件标识ID,其定义的是展开时的ExpandableListView布局样式,并且内部至少要包含参数“groupTo”中指定的视图ID。 groupFrom列名列表,显示ExpandableListView的组节点。 groupTo展示参数“groupFrom”中的列,也就是说ExpandableListView中的视图显示的是参数“groupFrom”的列值,它们应该都是TextView或是ImageView。 childLayout布局资源文件标识ID,其定义的是子视图的布局样式(不包括最后一个子视图),内部至少要包含参数“childTo”中指定的视图ID。lastChildLayout布局资源文件标识ID,其定义的是最后一个子视图的布局样式,内部至少要包含参数“childTo”中指定的视图ID。 childFrom列名列表,显示ExpandableListView的子节点。 childTo展示参数“childFrom”中的列,也就是说ExpandableListView中的视图显示的是参数“childFrom”的列值,它们应该都是TextView或是ImageView。 publicSimpleCursorTreeAdapter(Context context, Cursor cursor, int groupLayout, String[] groupFrom, int[] groupTo, int childLayout, String[] childFrom, int[] childTo) 构造函数。 参数 context上下文,多指ExpandableListView的上下文 cursor数据库游标 groupLayout 显示组元素的资源文件。该资源文件定义了如何显示组元素。该布局文件必须至少包括groupTo中所定义的View。(即groupTo中的View id数组必须都在该布局文件中找到) groupFrom列名列表,显示ExpandableListView的组节点。 groupTo展示参数“groupFrom”中的列,也就是说ExpandableListView中的视图显示的是参数“groupFrom”的列值,它们应该都是TextView或是ImageView。 childLayout布局资源文件标识ID,其定义的是子视图的布局样式(不包括最后一个子视图),内部至少要包含参数“childTo”中指定的视图ID。lastChildLayout布局资源文件标识ID,其定义的是最后一个子视图的布局样式,内部至少要包含参数“childTo”中指定的视图ID。 childFrom列名列表,显示ExpandableListView的子节点。 childTo 展示参数“ childFrom ”中的列,也就是说 ExpandableListView 中的视图显示的是参数 “ childFrom ”的列值, 它们应该都是 TextView 或是 ImageView 。 五、公共方法 public SimpleCursorAdapter.ViewBindergetViewBinder() 返回SimpleCursorTreeAdapter.ViewBinder引用,这个ViewBinder用来将数据绑定到视图上的。 返回值 如果ViewBinder不存在,则返回null。 参考 setViewBinder(android.widget.SimpleCursorTreeAdapter.ViewBinder) public voidsetViewBinder(SimpleCursorTreeAdapter.ViewBinder viewBinder) .设置视图绑定器。 参数 viewBinder视图绑定器。可以设置为null来删除已经存在的绑定器。 参考 getViewBinder() public voidsetViewText(TextView v, String text) 仅当ViewBinder不存在或是当ViewBinder不为TextView绑定时(也就是setViewValue()返回false),则这个方法会被bindView()调用,以便为TextView设置文本。可重写适配器从数据库中检索过滤字符串。 参数 v 文本控件引用 value为文本控件设置的文本信息(译者注:是从Cursor获取到的)。 六、受保护方法 protected voidbindChildView(View view, Context context, Cursor cursor, boolean isExpanded) 通过参数cursor将数据绑定到已有的子视图上。。 参数 view已有视图,返回之前调用newChildView创建的视图。 context应用程序上下文 cursor用于获取数据的Coursor。Coursor已经移到正确的位置。 isLastChild子元素是否处于组中的最后一个 protected voidbindGroupView(View view, Context context, Cursor cursor, boolean isExpanded) 通过参数cursor将数据绑定到已有组视图上。 参数 view已有组视图,返回之前调用newGroupView创建的视图。 context应用程序上下文 cursor用于获取数据的Coursor。Coursor已经移到正确的位置。 isExpanded组视图是否呈展开状态 protected voidsetViewImage(ImageView v, String value) 这个方法会被bindView()调用,以便为ImageView设置图片。默认情况下,参数value作为图片资源ID来看待,否则会视为图片的Uri。另外还可以通过过滤器来获得更灵活的设置。 参数 v 图片控件引用 value图片资源ID,是从Cursor获取到的。 七、补充 文章精选 android播放器(music player)源码分析2 示例代码 SimpleCursorTreeAdapter(深夜未眠).rar SimpleCursorTreeAdapter.ViewBinder 译者署名:深夜未眠 译者链接:http://chris1012f.javaeye.com/ 翻译时间:2011-3-3 版本:Android 3.0 r1 结构 继承关系 public static interfaceSimpleCusrorTreeAdapter.ViewBinder java.lang.Object android.widget.SimpleCursorTreeAdapter.ViewBinder 类概述 这个内部接口可以在外部通过SimpleCursorTreeAdapter.ViewBinder的方式进行Cursor与View的绑定。Android推荐我们采用这种方式进行绑定操作,而不是沿用SimpleCursorTreeAdapter内部的方式。 参见 setViewImage(ImageView, String) setViewText(TextView, String) 公共方法 public abstract booleansetViewValue(View view, Cursor cursor, int columnIndex) 将指定的列数据绑定到指定的视图上。当ViewBinder处理绑定时,这个方法必须返回true;否则SimpleAdapter将尝试通过其内部默认的方法绑定数据。 参数 view被绑定的视图。 cursor数据库游标,绑定数据从它这里获取 columnIndex列位置,能够在数据库游标中寻找到。 返回值 返回 true 意味着数据与视图已经绑定上,否则为未绑定上。 本文转自over140 51CTO博客,原文链接:http://blog.51cto.com/over140/582375,如需转载请自行联系原作者

优秀的个人博客,低调大师

Android中文API(115)——AudioFormat

正文 一、结构 public classAudioFormat extendsObject java.lang.Object android.media.AudioFormat 二、概述 AndioFormat 类用于访问一些音频格式和通道配置常量。这些常量应用在 AudioTrack 和 AudioRecord 类中。 三、常量 public static final intCHANNEL_CONFIGURATION_DEFAULT 已弃用。 用CHANNEL_OUT_DEFAULT or CHANNEL_IN_DEFAULT代替。 常量值:1 (0x00000001) public static final intCHANNEL_CONFIGURATION_INVALID 已弃用。 用CHANNEL_INVALID代替。 常量值:0 (0x00000000) public static final intCHANNEL_CONFIGURATION_MONO 已弃用。 用CHANNEL_OUT_MONO or CHANNEL_IN_MONO代替。 常量值:2 (0x00000002) public static final intCHANNEL_CONFIGURATION_STEREO 已弃用。 用CHANNEL_OUT_STEREO or CHANNEL_IN_STEREO代替。 常量值:3 (0x00000003) public static final intCHANNEL_INVALID 无效的音频通道掩码 常量值:0 (0x00000000) public static final intCHANNEL_IN_BACK 常量值:32 (0x00000020) public static final intCHANNEL_IN_BACK_PROCESSED 常量值:512 (0x00000200) public static final intCHANNEL_IN_DEFAULT 常量值:1 (0x00000001) public static final intCHANNEL_IN_FRONT 常量值:16 (0x00000010) public static final intCHANNEL_IN_FRONT_PROCESSED 常量值:256 (0x00000100) public static final intCHANNEL_IN_LEFT 常量值:4 (0x00000004) public static final intCHANNEL_IN_LEFT_PROCESSED 常量值:64 (0x00000040) public static final intCHANNEL_IN_MONO 常量值:16 (0x00000010) public static final intCHANNEL_IN_PRESSURE 常量值:1024 (0x00000400) public static final intCHANNEL_IN_RIGHT 常量值:8 (0x00000008) public static final intCHANNEL_IN_RIGHT_PROCESSED 常量值:128 (0x00000080) public static final intCHANNEL_IN_STEREO 常量值:12 (0x0000000c) public static final intCHANNEL_IN_VOICE_DNLINK 常量值:32768 (0x00008000) public static final intCHANNEL_IN_VOICE_UPLINK 常量值:16384 (0x00004000) public static final intCHANNEL_IN_X_AXIS 常量值:2048 (0x00000800) public static final intCHANNEL_IN_Y_AXIS 常量值:4096 (0x00001000) public static final intCHANNEL_IN_Z_AXIS 常量值:8192 (0x00002000) public static final intCHANNEL_OUT_5POINT1 常量值:252 (0x000000fc) public static final intCHANNEL_OUT_7POINT1 常量值:1020 (0x000003fc) public static final intCHANNEL_OUT_BACK_CENTER 常量值:1024 (0x00000400) public static final intCHANNEL_OUT_BACK_LEFT 常量值:64 (0x00000040) public static final intCHANNEL_OUT_BACK_RIGHT 常量值:128 (0x00000080) public static final intCHANNEL_OUT_DEFAULT 默认的音频通道掩码。 常量值:1 (0x00000001) public static final intCHANNEL_OUT_FRONT_CENTER 常量值:16 (0x00000010) public static final intCHANNEL_OUT_FRONT_LEFT 常量值:4 (0x00000004) public static final intCHANNEL_OUT_FRONT_LEFT_OF_CENTER 常量值:256 (0x00000100) public static final intCHANNEL_OUT_FRONT_RIGHT 常量值:8 (0x00000008) public static final intCHANNEL_OUT_FRONT_RIGHT_OF_CENTER 常量值:512 (0x00000200) public static final intCHANNEL_OUT_LOW_FREQUENCY 常量值:32 (0x00000020) public static final intCHANNEL_OUT_MONO 常量值:4 (0x00000004) public static final intCHANNEL_OUT_QUAD 常量值:204 (0x000000cc) public static final intCHANNEL_OUT_STEREO 常量值:12 (0x0000000c) public static final intCHANNEL_OUT_SURROUND 常量值:1052 (0x0000041c) public static final intENCODING_DEFAULT 默认的音频数据格式 常量值:1 (0x00000001) public static final intENCODING_INVALID 无效的音频数据格式 常量值:0 (0x00000000) public static final intENCODING_PCM_16BIT 音频数据格式:脉冲编码调制(PCM)每个样品16位。设备保证提供支持。(参见:这里) 常量值:2 (0x00000002) public static final intENCODING_PCM_8BIT 音频数据格式:脉冲编码调制(PCM)每个样品8位。设备不保证提供支持。 常量值:3 (0x00000003) 本文转自over140 51CTO博客,原文链接:http://blog.51cto.com/over140/582354,如需转载请自行联系原作者

优秀的个人博客,低调大师

android 中文 api (87) —— BaseInputConnection

正文 一、结构 public classBaseInputConnection extendsObjectimplementsInputConnection java.lang.Object android.view.inputmethod.BaseInputConnection 二、概述 InputConnection接口实现的基类,注意大多数行为提供的是Editable联接。本类的实现一定要实现getEditable()提供对它们自己的可编辑对象的访问。 三、公共方法 public booleanbeginBatchEdit() 缺省实现什么也不做。 public booleanclearMetaKeyStates(int states) 缺省实现用MetaKeyKeyListener.clearMetaKeyState(long, int)来清除状态。 参数 states要清除的状态,每个KeyEvent.getMetaState()中可能是1或个状态。 返回值 成功返回true,输入连接无效时返回false。 public booleancommitCompletion(CompletionInfo text) 缺省实现什么也不做。 参数 text提交的完成。 返回值 成功返回true,输入连接无效时返回false。 public booleancommitText(CharSequence text, int newCursorPosition) 缺省实现将用给出的文本替代正在构建的文本。另外在虚拟状态时,将发送包含新文本的按键事件并清空可编辑控件的缓存。 参数 text提交的文本。 newCursorPosition文本范围内新光标位置。如> 0,从文本未尾-1起计算;如<= 0,从文本起始处计算。所以是1时总是在刚插入文本之后。注意这意味着你不能将位置定义在文本中,因为编辑器可以修改你提交的文本,所以无必要将光标定位在文本中。 返回值 成功返回true,输入连接无效时返回false。 public booleandeleteSurroundingText(int leftLength, int rightLength) 缺省实现将删除当前光标位置附近的可编辑文本。 参数 leftLength删除文本在当前光标位置前的字符数 rightLength删除文本在当前光标位置后的字符数。 返回值 成功返回true,输入连接无效时返回false。。 public booleanendBatchEdit() 缺省实现什么也不做。 public booleanfinishComposingText() 缺省实现将用给定的文本替代正在构建的文本。另外在虚拟状态时,将发送包含新文本的按键事件并清空可编辑控件的缓存。 public static int getComposingSpanEnd (Spannable text) public static int getComposingSpanStart (Spannable text) public intgetCursorCapsMode(int reqModes) 缺省实现时,由TextUtils.getCapsMode返回当前可编辑文本的选定文本的光标大小写状态,虚拟状态时总是返回0。 参数 reqModes依据TextUtils.getCapsMode的定义取得期望的状态。通过已定义的常数,你可以轻易地传递TextBoxAttribute.contentType到当前。 返回值 返回当前有效的大小写状态。 public EditablegetEditable() 返回编辑操作的目标。缺省的实现是返回自己的虚拟可编辑控件,子类须重载一个可编辑控件并提供给它自己。 public ExtractedTextgetExtractedText(ExtractedTextRequest request, int flags) 缺省实现总是返回空。 参数 request 描述如何返回文本。 flags额外的客户端控制选项,0或GET_EXTRACTED_TEXT_MONITOR。 返回值 返回ExtractedText对象描述文本视窗的状态并包含提取文本的本身。 public CharSequencegetSelectedText(int flags) 缺省实现是返回当前选择文本,没有选取则为空。 参数 flags额外选项控制文本如何返回,可能为0或GET_TEXT_WITH_STYLES。 返回值 返回当前选择文本,没有选取则为空。 public CharSequencegetTextAfterCursor(int length, int flags) 缺省的实现是返回缓存中当前光标位置后给定数量的文本。 参数 length期望的文本长度。 flags如何返回文本的额外控制。可能为0或GET_TEXT_WITH_STYLES。 返回值 返回光标位置后的文本,返回文本的长度可能小于n。 public CharSequencegetTextBeforeCursor(int length, int flags) 缺省的实现是返回缓存中当前光标位置前给定数量的文本。 参数 length期望的文本长度。 flags如何返回文本的额外控制。可能为0或GET_TEXT_WITH_STYLES。 返回值 返回光标位置前的文本,返回文本的长度可能小于n。 public booleanperformContextMenuAction(int id) 缺省实现是什么也不做。 public booleanperformEditorAction(int actionCode) 缺省实现将其发送至返回键(enter key)。 参数 actionCode必须是EditorInfo.editorType中一常量之一,如EditorInfo.EDITOR_ACTION_GO。 返回值 成功返回true,输入连接无效时返回false。 public booleanperformPrivateCommand(String action, Bundle data) 缺省实现是什么也不做。 参数 action执行的命令名称。必须是作用域的名称(译者注:带包名,如”com.test.Command”),如以你自己的包名称前缀,这样不同的开发者就不会创建产生冲突的命令。 data命令中的数据。 返回值 命令发送返回true(无论相关的编辑器是否理解它),如输入连接无效返回false。 public static final void removeComposingSpans (Spannable text) public booleanreportFullscreenMode(boolean enabled) 以当前的全屏模式更新InputMethodManager。 public booleansendKeyEvent(KeyEvent event) 提供窗口附属输入连接视窗的发送按键事件的标准实现。 参数 event按键事件。 返回值 成功返回true,输入连接无效时返回false。 public booleansetComposingRegion(int start, int end) 将特定区域标记为正在构建文本。任何以前设置的正在构建文本自动清除。正在构建文本应用缺省样式。 参数 start文本中正在构建区域开始位置。 end文本中正在构建区域结束位置。 返回值 成功返回true,输入连接无效时返回false。 public static void setComposingSpans (Spannable text) public booleansetComposingText(CharSequence text, int newCursorPosition). 缺省实现是将给定文本置入可编辑文本,替代任何正在构建文本。新文本标记为正在构建文本并应用构建样式。 参数 text正在构建文本,如必要应用样式。如文本无附属样式,将正在构建文本应用缺省样式。参见how to attach style object to the text。{#link android.text.SpannableString}和{#link android.text.SpannableStringBuilder}是实现的接口。 newCursorPosition文本范围内新光标位置。如> 0,从文本未尾-1起计算;如<= 0,从文本起始处计算。所以是1时总是在刚插入文本之后。注意这意味着你不能将位置定义在文本中,因为编辑器可以修改你提交的文本,所以无必要将光标定位在文本中。 返回值 成功返回true,输入连接无效时返回false。 public booleansetSelection(int start, int end) 缺省实现是在当前可编辑文本中改变选取的位置。 返回值 成功返回true,输入连接无效时返回false。 本文转自over140 51CTO博客,原文链接:http://blog.51cto.com/over140/582421,如需转载请自行联系原作者

优秀的个人博客,低调大师

android中文api(79)——Gallery

正文 一、结构 public classGalleryextendsAbsSpinner implementsGestureDetector.OnGestureListener java.lang.Object android.view.View android.view.ViewGroup android.widget.AdapterView<T extends android.widget.Adapter> android.widget.AbsSpinner android.widget.Gallery 二、概述 一个锁定中心条目并且拥有水平滚动列表的视图。 Gallery(画廊)使用Theme_galleryItemBackground作为Gallery(画廊)适配器中的各视图的默认参数。如果你没有设置,你就需要调整一些Gallery(画廊)的属性,比如间距。 Gallery(画廊)中的视图应该使用Gallery.LayoutParams作为它们的布局参数类型。 参见 Gallery tutorial 。 三、内部类 class Gallery.LayoutParams Gallery(画廊)扩展了LayoutParams,以此提供可以容纳当前的转换信息和先前的位置转换信息的场所。 四、XML属性 属性名称 描述 android:animationDuration 设置布局变化时动画的转换所需的时间(毫秒级)。仅在动画开始时计时。该值必须是整数,比如:100。 android:gravity 指定在对象的X和Y轴上如何放置内容。指定一下常量中的一个或多个(使用 “|”分割) Constant Value Description top 0x30 紧靠容器顶端,不改变其大小 bottom 0x50 紧靠容器底部,不改变其大小 left 0x03 紧靠容器左侧,不改变其大小 right 0x05 紧靠容器右侧,不改变其大小 center_vertical 0x10 垂直居中,不改变其大小 fill_vertical 0x70 垂直方向上拉伸至充满容器 center_horizontal 0x01 水平居中,不改变其大小 Fill_horizontal 0x07 水平方向上拉伸使其充满容器 center 0x11 居中对齐,不改变其大小 fill 0x77 在水平和垂直方向上拉伸,使其充满容器 clip_vertical 0x80 垂直剪切(当对象边缘超出容器的时候,将上下边缘超出的部分剪切掉) clip_horizontal 0x08 水平剪切(当对象边缘超出容器的时候,将左右边缘超出的部分剪切掉) android:spacing (译者注:设置图片之间的间距) android:unselectedAlpha 设置未选中的条目的透明度(Alpha)。该值必须是float类型,比如:“1.2”。 五、公共方法 public booleandispatchKeyEvent(KeyEvent event) 在焦点路径上分发按钮事件到下一个视图。该路径从视图树的顶端遍历到当前获得焦点的视图。如果当前视图已获得焦点,就分发给自身。否则,就分发到下一个节点的焦点路径上。该方法监听任何按钮事件。 参数 event被分发的按钮事件 返回值 时间被处理返回true,否则false public voiddispatchSetSelected(boolean selected) 分发setSelected给视图的子类。 参数 selected新选中的状态 public ViewGroup.LayoutParamsgenerateLayoutParams(AttributeSet attrs) 返回一个新的已设置属性集合的布局参数。 参数 attrs用于生成布局参数的属性集合 返回值 一个ViewGroup.LayoutParams实例或者它的子类 public booleanonDown(MotionEvent e) 当轻击和按下手势事件发生时通知该方法。任何按下事件都会直接触发该方法。所有其他的事件都要先于该方法。 参数 e按下动作事件 public booleanonFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) 当初始化的按下动作事件和松开动作事件匹配时通知fling(译者注:快滑,用户按下触摸屏、快速移动后松开)事件。该动作的速度通过计算X和Y轴上每秒移动多少像素得来。 参数 e1导致开始fling的按下动作事件。 e2触发当前onFling方法的移动动作事件 velocityX测量fling沿X轴上的速度,像素/每秒 velocityY测量fling沿Y轴上的速度,像素/每秒 返回值 如果该事件被消耗返回true,否则false。 public booleanonKeyDown(int keyCode, KeyEvent event) 处理左,右和点击事件 参数 keyCode代表按下按钮的按键码,来自KeyEvent。 event定义按钮动作的KeyEvent对象。 返回值 如果已经处理了按钮事件,则返回true。如果你想让下一个事件接收者处理,就返回false 参见 onKeyDown(int, KeyEvent) public booleanonKeyUp(int keyCode, KeyEvent event) KeyEvent.Callback.onKeyMultiple()方法的默认实现:当KEYCODE_DPAD_CENTER或者KEYCODE_ENTER被释放时,执行点击视图操作。 参数 keyCode代表按下按钮的按键码,来自KeyEvent。 event定义按钮动作的KeyEvent对象。 返回值 如果已经处理了按钮事件,则返回true。如果你想让下一个事件接收者处理,就返回false public voidonLongPress(MotionEvent e) MotionEvent初始化并按下触发长按并通知本方法。 参数 e导致开始长按的初始按下动作事件。 public booleanonScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) 当初始按下动作事件和当前移动动作事件导致滚动时通知本方法。为了方便提供了X和Y轴上的距离。 监听屏幕滚动事件。为了方便提供了X和Y轴上的距离。 参数 e1 导致滚动开始按下的动作事件。 e2 触发当前onScroll方法的移动动作事件。 distanceX距离是自上一次调用onScroll方法在X轴上的距离。不是e1和e2之间的距离。 distanceY距离是自上一次调用onScroll方法在Y轴上的距离。不是e1和e2之间的距离。 返回值 如果该事件被消耗返回true否则false public voidonShowPress(MotionEvent e) 用户已经执行按下动作还没有执行移动或者弹起动作。该事件常通过高亮一个元素来向用户提供一个视觉反馈即用户的操作已经被辨识了。 参数 e按下动作事件 public booleanonSingleTapUp(MotionEvent e) 在轻击动作和up动作事件触发时通知本方法。(译者注:点击屏幕上的某项的执行流程有两种情况,一种是时间很短,一种时间稍长:时间很短:onDown--->onSingleTapUp--->onSingleTapConfirmed,见这里1,这里2。) 参数 e完成开始轻击的up动作事件 返回值 如果该事件被消耗返回true否则false public booleanonTouchEvent(MotionEvent event) 实现该方法来处理触摸屏动作事件 参数 event动作事件 返回值 如果该事件被消耗返回true否则false public voidsetAnimationDuration(int animationDurationMillis) 设置当子视图改变位置时动画转换时间。仅限于动画开始时生效。 参数 animationDurationMillis动画转换时间(毫秒级) public voidsetCallbackDuringFling(boolean shouldCallback) 当flinged时是否回调每一个getOnItemSelectedListener()。如果设为false,只回调最终选中的项。如果为true,则所有的项都会回调。 参数 shouldCallback设置抛滑的过程中是否回调 public voidsetGravity(int gravity) 描述子视图的对齐方式。 public voidsetSpacing(int spacing) 设置Gallery中项的间距 参数 spacing Gallery中项的间距,以像素为单位 public voidsetUnselectedAlpha(float unselectedAlpha) 设置Gallery中未选中项的透明度(alpha)值。 参数 unselectedAlpha未选中项的透明度(alpha)值 public booleanshowContextMenu() 显示该视图上下文菜单。 返回值 上下文菜单是否显示。 public booleanshowContextMenuForChild(View originalView) 为指定的视图或者其父类显示上下文菜单。 大部分情况下,子类不需要重写该方法。但是,如果子类被直接添加到窗口管理器(例如:addView(View.android.view.ViewGroup.LayoutParams)),此时就需要重写来显示上下文菜单 参数 originalView上下文菜单初次调用的源视图 返回值 如果上下文菜单被显示了则返回true。 六、受保护方法 protected intcomputeHorizontalScrollExtent() 在水平范围内计算滚动条滑块的滚动范围。该值用来计算滚动条滑块的长度。 该范围可以使用任意的单位但是必须跟computeHorizontalScrollRange()和computeHorizontalScrollOffset()的单位保持一致。 默认范围是视图的宽度。 返回值 滚动条滑块的水平滚动范围 protected intcomputeHorizontalScrollOffset() 在水平范围内计算滚动条滑块的偏移量。该值用来计算水平滑块的位置。 该范围可以使用任意的单位但是必须跟computeHorizontalScrollRange()和computeHorizontalScrollExtent()的单位保持一致。 默认偏移量是视图的偏移量。 返回值 滚动条滑块的水平偏移量。 protected intcomputeHorizontalScrollRange() 计算滚动条水平方向上的滚动范围。 该范围可以使用任意的单位但是必须跟computeHorizontalScrollExtent()和computeHorizontalScrollOffset()的单位保持一致。 返回值 水平滚动条代表的滑动总范围。 protected voiddispatchSetPressed(boolean pressed) 分发setPressed到View的子类。 参数 pressed新按下的状态 protected ViewGroup.LayoutParamsgenerateDefaultLayoutParams() 返回默认的布局参数。当View作为参数传递给addView(View)而没有布局参数时就会请求这些参数。如果返回null,则addView会抛出异常。 返回值 默认的布局参数或null protected ViewGroup.LayoutParamsgenerateLayoutParams(ViewGroup.LayoutParams p) 返回一组合法的受支持的布局参数。当把ViewGroup传递给View而该View的布局参数并没有通过checkLayoutParams(android.view.ViewGroup.LayoutParams)的测试时,就会调用该方法。该方法应该返回一组适合该ViewGroup的新的布局参数,该过程可能需要从指定的一组布局参数中复制相关的属性。 参数 p被转换成适合该ViewGroup的一组参数。 返回值 返回一个ViewGroup.LayoutParams的实例或者一个它的子类。 protected intgetChildDrawingOrder(int childCount, int i) 返回迭代的绘制子类索引。如果你想改变子类的绘制顺序就要重写该方法。默认返回i值。 提示:为了能够调用该方法,你必须首先调用setChildrenDrawingOrderEnabled(boolean)来允许子类排序。 参数 childCount子类个数 i当前迭代顺序 返回值 绘制该迭代子类的索引 protected booleangetChildStaticTransformation(View child, Transformation t) (译者注:setStaticTransformationsEnabled这个属性设成true的时候每次viewGroup(看Gallery的源码就可以看到它是从ViewGroup间接继承过来的)在重新画它的child的时候都会促发getChildStaticTransformation这个函数。这里1、这里2) protected ContextMenu.ContextMenuInfogetContextMenuInfo() Views如果有额外的信息跟上下文菜单有联系的话就需要实现该方法。返回的结果被用作回调方法onCreateContextMenu(ContextMenu, View, ContextMenuInfo)的参数。 返回值 显示上下文菜单的条目的额外信息。这些信息将会改变View不同的子类 protected voidonFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) 当该视图的焦点状态发生改变时将会调用视图系统。当导向的方向触发焦点事件时,方向和先前获得焦点的矩形提供焦点事件的来源。当用户重写该方法,必须调用父类方法来触发标准的焦点处理事件。 参数 gainFocus如果View获得焦点为true,否则false direction 当调用requestFocus()方法来给该视图焦点时焦点的移动方向。该值:FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT或FOCUS_RIGHT。该参数不常用,通常使用它的默认值。 previouslyFocusedRect该视图坐标系统中先前获得焦点的视图的矩形。如果适用,这将获得焦点事件来源的更细致的信息(除了方向以外)。否则为null。 protected voidonLayout(boolean changed, int l, int t, int r, int b) 当视图为每一个子类分配大小和位置时从布局中调用该方法。有子类的派生类应该重写该方法在子类中调用布局。 参数 changed该视图新的大小和位置。 l相对父容器的左侧位置 t相对父容器的顶部位置 r相对父容器的右侧位置 b相对父容器的底部位置 七、补充 文章精选 Android开发——使用Gallery实现“多级联动” android图片拖动效果(Gallery) 示例代码 Java文件 public class MyGallery extends Activity{ /** Calledwhentheactivityisfirstcreated. */ private Gallerygallery; @Override public void onCreate(BundlesavedInstanceState){ super .onCreate(savedInstanceState); setContentView(R.layout.main); gallery = (Gallery)findViewById(R.id.gallery); gallery.setAdapter( new ImageAdapter( this )); // 设置图片适配器 // 设置监听器 gallery.setOnItemClickListener( new OnItemClickListener(){ @Override public void onItemClick(AdapterView <?> arg0,Viewarg1, int arg2, long arg3){ Toast.makeText(MyGallery. this , " 点击了第 " + arg2 + " 张图片 " ,Toast.LENGTH_LONG).show(); } }); } } class ImageAdapter extends BaseAdapter{ private Contextcontext; // 图片源数组 private Integer[]imageInteger = { R.drawable.gallery_photo_1, R.drawable.gallery_photo_2, R.drawable.gallery_photo_3, R.drawable.gallery_photo_4, R.drawable.gallery_photo_5, R.drawable.gallery_photo_6, R.drawable.gallery_photo_7, R.drawable.gallery_photo_8 }; public ImageAdapter(Contextc){ context = c; } @Override public int getCount(){ return imageInteger.length; } @Override public ObjectgetItem( int position){ // TODOAuto-generatedmethodstub return position; } @Override public long getItemId( int position){ // TODOAuto-generatedmethodstub return position; } @Override public ViewgetView( int position,ViewconvertView,ViewGroupparent){ ImageViewimageView = new ImageView(context); imageView.setImageResource(imageInteger[position]); imageView.setScaleType(ImageView.ScaleType.FIT_XY); imageView.setLayoutParams( new Gallery.LayoutParams( 136 , 88 )); return imageView; } } XML文件 <? xmlversion="1.0"encoding="utf-8" ?> < Gallery xmlns:android ="http://schemas.android.com/apk/res/android" android:id ="@+id/gallery" android:layout_width ="fill_parent" android:layout_height ="wrap_content" android:gravity ="center_vertical" android:background ="?android:galleryItemBackground" /> 本文转自over140 51CTO博客,原文链接:http://blog.51cto.com/over140/582442,如需转载请自行联系原作者

优秀的个人博客,低调大师

Android API 中文 (15) —— GridView

正文 一、结构 public final classGridViewextendsAbsListView java.lang.Object android.view.View android.view.ViewGroup android.widget.AdapterView<T extends android.widget.Adapter> android.widget.AbsListView android.widget.GridView 二、类概述 一个在平面上可显示多个条目的可滚动的视图组件,该组件中的条目通过一个ListAdapter和该组件进行关联。比如android手机中显示的应用: 比如实现九宫格图,用GridView是首选,也是最简单的。 三、构造函数 public GridView (Context context) 创建一个默认属性的GridView实例 public GridView (Context context, AttributeSet attrs) 创建一个带有attrs属性的GridView实例 public GridView (Context context, AttributeSet attrs, int defStyle) 创建一个带有attrs属性,并且指定其默认样式的GridView实例 四、XML属性 属性名称 描述 android:columnWidth 设置列的宽度。关联的方法为:setColumnWidth(int) android:gravity 设置此组件中的内容在组件中的位置。可选的值有:top、bottom、left、right、center_vertical、fill_vertical、center_horizontal、fill_horizontal、center、fill、clip_vertical可以多选,用“|”分开。关联方法:setGravity (int gravity) android:horizontalSpacing 两列之间的间距。关联方法:setHorizontalSpacing(int) android:numColumns 列数。关联方法:setNumColumns(int) android:stretchMode 缩放模式。关联方法:setStretchMode(int) android:verticalSpacing 两行之间的间距。关联方法:setVerticalSpacing(int) 五、公共方法 public ListAdapter getAdapter () 获得与此组件相关的适配器.. 返回值 ListAdapter适配器实例 public int getStretchMode () 获得GridView的缩放模式.. public boolean onKeyDown (int keyCode, KeyEvent event) 默认由KeyEvent.Callback.onKeyMultiple()实现,如果视图是可用的并且是可点击的,那么传入KEYCODE_DPAD_CENTER或KEYCODE_ENTER值是执行的是按下视图操作。 参数 keyCode一个表示按下操作的键值. event表示按钮事件的对象. 返回值 如果你认为已经完成事件处理,不想让让下一个处理器来处理此事件,则返回true,否则返回false。 public boolean onKeyMultiple (int keyCode, int repeatCount, KeyEvent event) 默认由KeyEvent.Callback.onKeyMultiple()实现,总是返回false(不处理此事件)。 参数 keyCode键值. repeatCount该动作发生的次数. event事件对象. 返回值 如果你认为已经完成事件处理,不想让让下一个处理器来处理此事件,则返回true,否则返回false。 public boolean onKeyUp (int keyCode, KeyEvent event) 默认由KeyEvent.Callback.onKeyMultiple()实现,如果视图是可用的并且是可点击的,那么传入KEYCODE_DPAD_CENTER或KEYCODE_ENTER值是执行的是点击视图操作。 参数 keyCode键值. event事件对象. 返回值 如果你认为已经完成事件处理,不想让让下一个处理器来处理此事件,则返回true,否则返回false。 public void setAdapter (ListAdapter adapter) 设置GridView的数据。 参数 adapter为grid提供数据的适配器 public void setColumnWidth (int columnWidth) 设置GridView的列宽. 参数 columnWidth列的宽度,以像素为单位 public void setGravity (int gravity) 设置控件内容的位置,默认值为:Gravity.LEFT. 参数 gravity位置值 public void setHorizontalSpacing (int horizontalSpacing) 设置列间距. 参数 horizontalSpacing列间距值 public void setNumColumns (int numColumns) 设置grid的列数 参数 numColumns列数值. public void setSelection (int position) 设置选中的条目. 参数 position.数据条目在列表中的索引值(从0开始),如果在可触摸的模式下,在该索引值下的条目将不会被选中,但是该索引值仍然指向该条目。 public void setStretchMode (int stretchMode) 设置grid中的条目以什么缩放模式去填充空间。. 参数 stretchMode可选值:NO_STRETCH,STRETCH_SPACING,STRETCH_SPACING_UNIFORM,或STRETCH_COLUMN_WIDTH public void setVerticalSpacing (int verticalSpacing) 设置行间距. 参数 verticalSpacing间距值,以像素为单位 六、代码示例 下面给出一个小例子,先看效果: a). GridView01.java public class GridView01 extends Activity{ private GridViewgridview; @Override protected void onCreate(BundlesavedInstanceState){ // TODOAuto-generatedmethodstub super .onCreate(savedInstanceState); setContentView(R.layout.gridview); // 准备要添加的数据条目 List < Map < String,Object >> items = new ArrayList < Map < String,Object >> (); for ( int i = 0 ;i < 10 ;i ++ ){ Map < String,Object > item = new HashMap < String,Object > (); item.put( " imageItem " ,R.drawable.icon); item.put( " textItem " , " text " + i); items.add(item); } // 实例化一个适配器 SimpleAdapteradapter = new SimpleAdapter( this ,items,R.layout.grid_item, new String[]{ " imageItem " , " textItem " }, new int []{R.id.image_item,R.id.text_item}); // 获得GridView实例 gridview = (GridView)findViewById(R.id.mygridview); // gridview.setNumColumns(3); // 可以在xml中设置 // gridview.setGravity(Gravity.CENTER); // 同上 // 将GridView和数据适配器关联 gridview.setAdapter(adapter); } } b). gridview.xml <? xmlversion="1.0"encoding="utf-8" ?> < LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android" android:layout_width ="wrap_content" android:layout_height ="wrap_content" > < GridView android:id ="@+id/mygridview" android:numColumns ="3" android:gravity ="center_horizontal" android:layout_width ="wrap_content" android:layout_height ="wrap_content" > </ GridView > </ LinearLayout > c). grid_item.xml <? xmlversion="1.0"encoding="utf-8" ?> < RelativeLayout android:id ="@+id/RelativeLayout01" android:layout_width ="fill_parent" android:layout_height ="fill_parent" xmlns:android ="http://schemas.android.com/apk/res/android" > < ImageView android:id ="@+id/image_item" android:layout_width ="wrap_content" android:layout_height ="wrap_content" > </ ImageView > < TextView android:id ="@+id/text_item" android:layout_below ="@+id/image_item" android:layout_height ="wrap_content" android:layout_width ="wrap_content" > </ TextView > </ RelativeLayout > 本文转自over140 51CTO博客,原文链接:http://blog.51cto.com/over140/582689,如需转载请自行联系原作者

优秀的个人博客,低调大师

Android API 中文 (55) —— ListAdapter

正文 一、结构 public interfaceListAdapterextendsAdapter android.widget.ListAdapter 直接子类 ArrayAdapter<T>, BaseAdapter, CursorAdapter, HeaderViewListAdapter, ResourceCursorAdapter, SimpleAdapter, SimpleCursorAdapter, WrapperListAdapter 二、概述 扩展Adapter是在ListView与数据之间的一座桥梁。通常数据来自于游标,但不是必须的。ListView可以显示包含在ListAdapter里的所有数据。 三、公共方法 public abstract booleanareAllItemsEnabled() 在ListAdapter中所有的项目都是可用的?如果是,则代表所有的项目都是可选择,可用鼠标点击的。 返回值 如果所有项目是可用的返回真 public abstract booleanisEnabled(int position) 如果指定的位置不是一个隔离(separator)项目(隔离项目是一个不可选择,不可用鼠标点击的项目)则返回真。如果位置是无效的,其结果将是不确定的。在这种情况下一个ArrayIndexOutOfBoundsException(越界)异常将抛出。 参数 position项目的索引 返回值 如果这个项目不是一个隔离(separator)项目则返回真。 本文转自over140 51CTO博客,原文链接:http://blog.51cto.com/over140/582570,如需转载请自行联系原作者

优秀的个人博客,低调大师

Flink DataSet API Programming Guide

Example Program 编程的风格和spark很类似, ExecutionEnvironment -- SparkContext DataSet – RDD Transformations 这里用Java的接口,所以传入function需要用FlatMapFunction类对象 public class WordCountExample { public static void main(String[] args) throws Exception { final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DataSet<String> text = env.fromElements( "Who's there?", "I think I hear them. Stand, ho! Who's there?"); DataSet<Tuple2<String, Integer>> wordCounts = text .flatMap(new LineSplitter()) .groupBy(0) .sum(1); wordCounts.print(); } public static class LineSplitter implements FlatMapFunction<String, Tuple2<String, Integer>> { @Override public void flatMap(String line, Collector<Tuple2<String, Integer>> out) { for (String word : line.split(" ")) { out.collect(new Tuple2<String, Integer>(word, 1)); } } } } Specifying Keys 如何定义key, 1. 用tuple的index,如下用tuple的第一个和第二个做联合key DataSet<Tuple3<Integer,String,Long>> input = // [...] DataSet<Tuple3<Integer,String,Long> grouped = input .groupBy(0,1) .reduce(/*do something*/); 2. 对于POJO对象,使用Field Expressions // some ordinary POJO (Plain old Java Object) public class WC { public String word; public int count; } DataSet<WC> words = // [...] DataSet<WC> wordCounts = words.groupBy("word").reduce(/*do something*/); 3. 使用Key Selector Functions // some ordinary POJO public class WC {public String word; public int count;} DataSet<WC> words = // [...] DataSet<WC> wordCounts = words .groupBy( new KeySelector<WC, String>() { public String getKey(WC wc) { return wc.word; } }) .reduce(/*do something*/); Passing Functions to Flink 1. 实现function interface class MyMapFunction implements MapFunction<String, Integer> { public Integer map(String value) { return Integer.parseInt(value); } }); data.map (new MyMapFunction()); 或使用匿名类, data.map(new MapFunction<String, Integer> () { public Integer map(String value) { return Integer.parseInt(value); } }); 2. 使用Rich functions Rich functions provide, in addition to the user-defined function (map, reduce, etc), four methods:open,close,getRuntimeContext,andsetRuntimeContext. These are useful for parameterizing the function (seePassing Parameters to Functions), creating and finalizing local state, accessing broadcast variables (seeBroadcast Variables, and for accessing runtime information such as accumulators and counters (seeAccumulators and Counters, and information on iterations (seeIterations). Rich functions的使用和普通的function是一样的,不同的就是,多4个接口函数,可以用于一些特殊的场景,比如给function传参,或访问broadcast变量,accumulators和counter,因为这些场景你需要先getRuntimeContext class MyMapFunction extends RichMapFunction<String, Integer> { public Integer map(String value) { return Integer.parseInt(value); } }); Execution Configuration ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); ExecutionConfig executionConfig = env.getConfig(); enableClosureCleaner()/disableClosureCleaner(). The closure cleaner is enabled by default. The closure cleaner removes unneeded references to the surrounding class of anonymous functions inside Flink programs. With the closure cleaner disabled, it might happen that an anonymous user function is referencing the surrounding class, which is usually not Serializable. This will lead to exceptions by the serializer. 对于Java,比如传入function也要生成function对象,这样里面的function是会reference这个对象的,其实这种情况,你需要的只是function逻辑,所以closureCleaner会去掉这个reference 这样的好处是,传输类对象时候,是要求对象可序列化的,如果每个去实现序列号接口很麻烦,不实现又会报错,所以这里干脆clean掉这个reference getParallelism()/setParallelism(int parallelism)Set the default parallelism for the job. 设置Job的全局的parallelism getExecutionRetryDelay()/setExecutionRetryDelay(long executionRetryDelay)Sets the delay in milliseconds that the system waits after a job has failed, before re-executing it. The delay starts after all tasks have been successfully been stopped on the TaskManagers, and once the delay is past, the tasks are re-started. This parameter is useful to delay re-execution in order to let certain time-out related failures surface fully (like broken connections that have not fully timed out), before attempting a re-execution and immediately failing again due to the same problem. This parameter only has an effect if the number of execution re-tries is one or more.getExecutionMode()/setExecutionMode(). The default execution mode is PIPELINED. Sets the execution mode to execute the program. The execution mode defines whether data exchanges are performed in a batch or on a pipelined manner. 和失败重试相关的配置 enableObjectReuse()/disableObjectReuse()By default, objects are not reused in Flink. Enabling theobject reuse modewill instruct the runtime to reuse user objects for better performance. Keep in mind that this can lead to bugs when the user-code function of an operation is not aware of this behavior. 这个由于Java什么都要生成对象,比如function,所以会生成大量重复对象,这个可以打开object重用,提高性能 enableSysoutLogging()/disableSysoutLogging()JobManager status updates are printed toSystem.outby default. This setting allows to disable this behavior. 打开和关闭系统日志 getGlobalJobParameters()/setGlobalJobParameters()This method allows users to set custom objects as a global configuration for the job. Since theExecutionConfigis accessible in all user defined functions, this is an easy method for making configuration globally available in a job. 可以设置Job全局参数 其他的参数都是序列化相关的,不列了 Data Sinks Data sinks consume DataSets and are used to store or return them. Data sink operations are described using anOutputFormat. 可以custom output format: 比如写数据库, DataSet<Tuple3<String, Integer, Double>> myResult = [...] // write Tuple DataSet to a relational database myResult.output( // build and configure OutputFormat JDBCOutputFormat.buildJDBCOutputFormat() .setDrivername("org.apache.derby.jdbc.EmbeddedDriver") .setDBUrl("jdbc:derby:memory:persons") .setQuery("insert into persons (name, age, height) values (?,?,?)") .finish() ); 还有个功能,可以做locally的排序, DataSet<Tuple3<Integer, String, Double>> tData = // [...] DataSet<Tuple2<BookPojo, Double>> pData = // [...] DataSet<String> sData = // [...] // sort output on String field in ascending order tData.print().sortLocalOutput(1, Order.ASCENDING); // sort output on Double field in descending and Integer field in ascending order tData.print().sortLocalOutput(2, Order.DESCENDING).sortLocalOutput(0, Order.ASCENDING); Debugging 本地执行,LocalEnvironement final ExecutionEnvironment env = ExecutionEnvironment.createLocalEnvironment(); DataSet<String> lines = env.readTextFile(pathToTextFile); // build your program env.execute(); 便于调式的datasouce, final ExecutionEnvironment env = ExecutionEnvironment.createLocalEnvironment(); // Create a DataSet from a list of elements DataSet<Integer> myInts = env.fromElements(1, 2, 3, 4, 5); // Create a DataSet from any Java collection List<Tuple2<String, Integer>> data = ... DataSet<Tuple2<String, Integer>> myTuples = env.fromCollection(data); // Create a DataSet from an Iterator Iterator<Long> longIt = ... DataSet<Long> myLongs = env.fromCollection(longIt, Long.class); 便于输出的datasink, DataSet<Tuple2<String, Integer>> myResult = ... List<Tuple2<String, Integer>> outData = new ArrayList<Tuple2<String, Integer>>(); myResult.output(new LocalCollectionOutputFormat(outData)); Iteration Operators Iterations implement loops in Flink programs. The iteration operators encapsulate a part of the program and execute it repeatedly, feeding back the result of one iteration (the partial solution) into the next iteration. There are two types of iterations in Flink:BulkIterationandDeltaIteration. 参考,https://ci.apache.org/projects/flink/flink-docs-release-0.10/apis/iterations.html BulkIteration就是正常的Iteration,每次都处理全量数据 DeltaIteration,就是每次都只处理部分数据并delta更新,效率更高 Semantic Annotations Semantic annotations can be used to give Flink hints about the behavior of a function. 目的是做性能优化,优化器在明确知道function读参数的使用情况,比如如果知道某些field只是做forward,就可以保留它的sorting or partitioning信息 有3种语义annotation, Forwarded Fields Annotation 表示,输入的某个field会原封不动的copy到输出的某个field 下面的例子,表示输入的第一个field会copy到输出的第3个field 可以看到,输出tuple的第三个field是val.f0 @ForwardedFields("f0->f2") public class MyMap implements MapFunction<Tuple2<Integer, Integer>, Tuple3<String, Integer, Integer>> { @Override public Tuple3<String, Integer, Integer> map(Tuple2<Integer, Integer> val) { return new Tuple3<String, Integer, Integer>("foo", val.f1 / 2, val.f0); } } Non-Forwarded Fields 和上面相反,除指定的fields,其他fields都是原位置copy 例子,除输入的第二个field,其他都是原位置copy @NonForwardedFields("f1") // second field is not forwarded public class MyMap implements MapFunction<Tuple2<Integer, Integer>, Tuple2<Integer, Integer>> { @Override public Tuple2<Integer, Integer> map(Tuple2<Integer, Integer> val) { return new Tuple2<Integer, Integer>(val.f0, val.f1 / 2); } } Read Fields 表明这个fields会在function被读到或用到, 表明,输入的第一个field和第4个field会被读到或用到 @ReadFields("f0; f3") // f0 and f3 are read and evaluated by the function. public class MyMap implements MapFunction<Tuple4<Integer, Integer, Integer, Integer>, Tuple2<Integer, Integer>> { @Override public Tuple2<Integer, Integer> map(Tuple4<Integer, Integer, Integer, Integer> val) { if(val.f0 == 42) { return new Tuple2<Integer, Integer>(val.f0, val.f1); } else { return new Tuple2<Integer, Integer>(val.f3+10, val.f1); } } } Broadcast Variables Broadcast variables allow you to make a data set available to all parallel instances of an operation, in addition to the regular input of the operation. This is useful for auxiliary data sets, or data-dependent parameterization. The data set will then be accessible at the operator as a Collection. Broadcast: broadcast sets are registered by name viawithBroadcastSet(DataSet, String), and Access: accessible viagetRuntimeContext().getBroadcastVariable(String)at the target operator. // 1. The DataSet to be broadcasted DataSet<Integer> toBroadcast = env.fromElements(1, 2, 3); DataSet<String> data = env.fromElements("a", "b"); data.map(new RichMapFunction<String, String>() { @Override public void open(Configuration parameters) throws Exception { // 3. Access the broadcasted DataSet as a Collection Collection<Integer> broadcastSet = getRuntimeContext().getBroadcastVariable("broadcastSetName"); } @Override public String map(String value) throws Exception { ... } }).withBroadcastSet(toBroadcast, "broadcastSetName"); // 2. Broadcast the DataSet 这个场景,就是有些不大的公共数据,是要被所有的实例访问到的,比如一些查询表 上面的例子,会将toBroadcast设置为广播变量broadcastSetName,这样在运行时,可以用getRuntimeContext().getBroadcastVariable获取该变量使用 Passing Parameters to Functions 应该是如果将参数传递给function类,这个完全由java冗余导致的 首先,当然可以用类构造函数来传参数, ataSet<Integer> toFilter = env.fromElements(1, 2, 3); toFilter.filter(new MyFilter(2)); private static class MyFilter implements FilterFunction<Integer> { private final int limit; public MyFilter(int limit) { this.limit = limit; } @Override public boolean filter(Integer value) throws Exception { return value > limit; } } 自定义MyFilter,构造函数可以传入limit 也可以使用withParameters(Configuration) DataSet<Integer> toFilter = env.fromElements(1, 2, 3); Configuration config = new Configuration(); config.setInteger("limit", 2); toFilter.filter(new RichFilterFunction<Integer>() { private int limit; @Override public void open(Configuration parameters) throws Exception { limit = parameters.getInteger("limit", 0); } @Override public boolean filter(Integer value) throws Exception { return value > limit; } }).withParameters(config); 可以用withParameters将定义好的config传入function 然后用RichFunction的Open接口,将参数解析出来使用 这样和上面的比有啥好处,我怎么觉得上面那个看着更方便些?可以用匿名类? 当然你也可以用全局参数,这个和广播变量有什么区别?相同点就是都是全局可见,全局参数只能用于参数形式,广播变量可以是任意dataset Setting a custom global configuration Configuration conf = new Configuration(); conf.setString("mykey","myvalue"); final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); env.getConfig().setGlobalJobParameters(conf); Accessing values from the global configuration public static final class Tokenizer extends RichFlatMapFunction<String, Tuple2<String, Integer>> { private String mykey; @Override public void open(Configuration parameters) throws Exception { super.open(parameters); ExecutionConfig.GlobalJobParameters globalParams = getRuntimeContext().getExecutionConfig().getGlobalJobParameters(); Configuration globConf = (Configuration) globalParams; mykey = globConf.getString("mykey", null); } // ... more here ... Accumulators & Counters 用于分布式计数,job结束的时候,会全部汇总 Flink currently has the followingbuilt-in accumulators. Each of them implements theAccumulatorinterface. IntCounter,LongCounterandDoubleCounter: See below for an example using a counter. Histogram: A histogram implementation for a discrete number of bins. Internally it is just a map from Integer to Integer. You can use this to compute distributions of values, e.g. the distribution of words-per-line for a word count program. //定义和注册counter private IntCounter numLines = new IntCounter(); getRuntimeContext().addAccumulator("num-lines", this.numLines); //在任意地方进行计数 this.numLines.add(1); //最终取得结果 myJobExecutionResult.getAccumulatorResult("num-lines") Execution Plans 首先可以打印出执行plan,json格式, final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); ... System.out.println(env.getExecutionPlan()); 打开这个网页, The HTML document containing the visualizer is located undertools/planVisualizer.html. 将Json贴入,就可以看到执行计划, Web Interface Flink offers a web interface for submitting and executing jobs. If you choose to use this interface to submit your packaged program, you have the option to also see the plan visualization. The script to start the webinterface is located underbin/start-webclient.sh. After starting the webclient (per default onport 8080), your program can be uploaded and will be added to the list of available programs on the left side of the interface. 也可以通过web interface来提交job和查看执行计划

优秀的个人博客,低调大师

MapReduce、Hbase接口API实践

读取hdfs中文件并做处理,取出卡号,通过卡号连接hbase查询出对应客户号,写入redis,因为不用输出,所以不调用context.write方法,整个操作在一个map中便可完成 protected HTable connect //setup方法被MapReduce框架仅且执行一次,在执行Map任务前,进行相关变量或者资源的集中初始化工作。若是将资源初始化工作放在方法map()中,导致Mapper任务在解析每一行输入时都会进行资源初始化工作,导致重复,程序运行效率不高! protected void setup(Context context) throws IOExcption,InterruptedException{ super.setup(context) String jobName = context.getJobName(); //文件索引值 cartNoIndex = conf.get(jobName + "source.key","7"); //创建hbase连接,hbase-site.xml配置文件需要在jar包中 Configuration config = HBaseConfiguration.create(); connect = new HTable(config,"tableName") } protected void map(writable key,Text value,Context context){ if(value == null || value.toString().trim().isEmpty()){ //计数器,记录处理的条数 context.getCounter(....).increment(1); }else{ String[] values = Utils.split(value,separator,true); //业务逻辑处理 int i = Integer.parseInt(cartNoIndex); if(i<values.length){ cardNo = values[i]; }else{ logger.error("cardNo cannot find"); } //从hbase中查询出对应客户号 String rowkey = HTableManager.generatRowkey(cardNo); Get getResult = new Get(rowkey.getBytes()); Result rs = connect.get(getResult); String curNo = Bytes.toString(rs.getValue("f1".getBytes(),"column_name".getBtes());RedisClient.getRedisClient().zincrbyset("spending:rank",countNum,custNo);protected void cleanup(context context)throws IOException,InterruptedException{ super.cleanup(context); connect.close();} public static String[] split(String value,String separator,boolean trimSpace){ String[] rtn = split(value.separator); if(trimSpace && rtn != null){ for(int i=0;i<rtn.length;i++){ rtn[i] = rtn[i].trim(); } } return rtn; } public static String[] split(String value,String separator){ String[] rtn = null; if(value != null){ boolean endBlank = false; if(value.endsWith(separator)){ value +=" "; endBlank = true; } separator = escapeExprSpecialWord(deparator); if(endBlank){ rtn(rtn.length-1) = ""; } } return rtn; } public static String escapeExprSpecialWord(String keyWord){ if(keyword != null && !keyword.isEmpty()){ String[] fbsArr = {"\\","|","(",")"}; for(String key : fbsArr){ if(keyword.contains(key){ keyword = keyword.replace(key,"\\"+key); } } } return keyword; }

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册