首页 文章 精选 留言 我的

精选列表

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

CUDA学习(九十四)

数据迁移和一致性:统一内存通过将数据迁移到正在访问的设备(即将数据移动到主机内存(如果CPU正在访问它,并将数据移动到设备内存,如果GPU将访问它),来尝试优化内存性能)。 数据迁移是统一内存的基础,但对于程序而言是透明的。 系统会尝试将数据放置在最有效访问的位置,而不会违反一致性。数据的物理位置对于程序是不可见的,并且可以随时更改,但访问数据的虚拟地址将保持任何处理器的有效性和连贯性,而不管本地是什么。 请注意,保持一致性是主要要求,在性能之前; 在主机操作系统的限制下,系统被允许无法访问或移动数据,以保持处理器之间的全局一致性。计算能力低于6.x的GPU架构不支持托管数据向GPU按需细粒度移动。无论何时启动GPU内核,通常都必须将所有托管内存传输到GPU内存,以避免内存访问出现故障。通过计算能力6.x,引入了新的GPU页面错误机制,可提供更加无缝的统一内存功能。结合系统范围的虚拟地址空间,页面错误提供了几个好处。首先,页面错误意味着CUDA系统软件在每次内核启动之前不需要将所有托管的内存分配同步到GPU。如果在GPU上运行的内核访问不在其内存中的页面,则它会发生故障,从而允许页面按需自动迁移到GPU内存。或者,页面可能映射到GPU地址空间,以便通过PCIe或NVLink互连进行访问(访问映射有时可能比迁移快)。请注意,统一内存是系统范围内的:GPU(和CPU)可能会在CPU内存或系统中其他GPU的内存上发生故障并迁移内存页面。GPU内存Oversubscription:计算能力低于6.x的设备无法分配比GPU内存的物理大小更多的托管内存。计算能力6.x的设备扩展寻址模式以支持49位虚拟寻址。 这足以覆盖现代CPU的48位虚拟地址空间以及GPU自己的内存。 大型虚拟地址空间和页面错误功能使应用程序能够访问整个系统虚拟内存,而不受任何一个处理器的物理内存大小的限制。 这意味着应用程序可以超额订阅内存系统:换句话说,它们可以分配,访问和共享比系统总物理容量更大的阵列,从而可以对超大型数据集进行非核心处理。 只要有足够的系统内存可用于分配,cudaMallocManaged就不会耗尽内存多GPU支持:对于计算能力低于6.x的设备,托管内存分配的行为与使用cudaMalloc()分配的非托管内存的行为相同:当前活动设备是物理分配的归属,所有其他GPU都接收对等映射到内存。 这意味着系统中的其他GPU将通过PCIe总线以更低的带宽访问内存。 请注意,如果系统中的GPU之间不支持对等映射,则托管内存页将放置在CPU系统内存(“零拷贝”内存)中,并且所有GPU都会遇到PCIe带宽限制。 有关详细信息,请参阅6.x之前的架构下的带有多GPU程序的托管内存。具有计算能力6.x的设备的系统上的托管分配对所有GPU均可见,并可按需迁移到任何处理器。

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

CUDA学习(九十二)

统一的存储器编程:统一内存简介:Unified Memory是CUDA编程模型的一个组件,首次在CUDA 6.0中引入,该模型定义了一个托管内存空间,其中所有处理器都可以看到具有公共地址空间的单个一致内存映像。(处理器是指具有专用MMU的任何独立执行单元。 这包括任何类型和架构的CPU和GPU。)底层系统管理CUDA程序中的数据访问和位置,而不需要显式的内存拷贝调用。 这有利于两种主要方式的GPU编程: GPU编程通过统一系统中所有GPU和CPU的内存空间并通过为CUDA程序员提供更紧密和更直接的语言集成而得到简化。 通过将数据透明地迁移到使用它的处理器,可以最大限度地提高数据访问速度。 简而言之,统一内存不需要通过cudaMemcpy *()例程进行显式数据移动,而且不会因将所有数据放入零拷贝内存而导致性能损失。 数据移动当然仍然会发生,所以程序的运行时间通常不会减少; 统一内存改为可以编写更简单,更易维护的代码。Unified Memory提供了一个“单指针到数据”模型,它在概念上类似于CUDA的零拷贝内存。 两者之间的一个关键区别在于,使用零拷贝分配时,内存的物理位置被固定在CPU系统内存中,使得程序可能对其进行快速访问或缓慢访问,具体取决于访问的位置。 另一方面,统一内存将内存和执行空间分开,以便所有数据访问都很快。统一内存这个术语描述了一个系统,它提供内存管理服务给各种各样的程序,从定位运行时API到使用虚拟ISA(PTX)的程序。 该系统的一部分定义了选择统一内存服务的托管内存空间。托管内存可与设备特定的分配互操作并互换,例如使用cudaMalloc()例程创建的分配。 所有在设备内存上有效的CUDA操作在托管内存上也是有效的; 主要区别在于程序的主机部分也能够引用和访问内存。系统要求:统一内存有两个基本要求: SM体系结构3.0或更高版本的GPU(开普勒架构或更新) 一个64位主机应用程序和非嵌入式操作系统(Linux,Windows,MacOS) SM体系结构6.x或更高版本(Pascal或更新版本)的GPU可提供额外的统一内存功能,如本文档中概述的按需页面迁移和GPU内存超额认购。 请注意,目前这些功能仅在Linux操作系统上受支持。 运行在Windows上的应用程序(无论是TCC还是WDDM模式)还是macOS,都将使用基本统一内存模型,与6.x之前的体系结构一样,即使它们在计算能力为6.x或更高的硬件上运行。

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

深度学习必备包

安装 Tensorflow Keras Opencv # For a specific version: !pip install tensorflow-gpu==1.5.0rc0 # To determine which version you're using: !pip show tensorflow-gpu # For the current version: !pip install --upgrade tensorflow-gpu # For the latest nightly build: !pip install tf-nightly-gpu !pip install -U tensorflow-gpu !pip install -U keras !pip install opencv-contrib-python --upgrade Keras: The Python Deep Learning library OpenCV An open-source software library for Machine Intelligence Install 7zip reader libarchive !pip install -U libarchive Install GraphViz & PyDot !pip install -U pydot graphviz Install xgboost !pip install -U xgboost import tensorflow as tf tf.keras # Keras 为 TensorFlow 提供了 API 探寻有趣之事!

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

python的HTMLParser学习

先来大致看看HTMLParser的源代码吧: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 """A parser for HTML and XHTML.""" # This file is based on sgmllib.py, but the API is slightly different. # XXX There should be a way to distinguish between PCDATA (parsed # character data -- the normal case), RCDATA (replaceable character # data -- only char and entity references and end tags are special) # and CDATA (character data -- only end tags are special). import markupbase import re # Regular expressions used for parsing interesting_normal = re. compile ( '[&<]' ) interesting_cdata = re. compile (r '<(/|\Z)' ) incomplete = re. compile ( '&[a-zA-Z#]' ) entityref = re. compile ( '&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]' ) charref = re. compile ( '&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]' ) starttagopen = re. compile ( '<[a-zA-Z]' ) piclose = re. compile ( '>' ) commentclose = re. compile (r '--\s*>' ) tagfind = re. compile ( '[a-zA-Z][-.a-zA-Z0-9:_]*' ) attrfind = re. compile ( r '\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*' r '(\'[^\']*\'|"[^"]*"|[-a-zA-Z0-9./,:;+*%?!&$\(\)_#=~@]*))?' ) locatestarttagend = re. compile (r """ <[a-zA-Z][-.a-zA-Z0-9:_]* # tag name (?:\s+ # whitespace before attribute name (?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name (?:\s*=\s* # value indicator (?:'[^']*' # LITA-enclosed value |\"[^\"]*\" # LIT-enclosed value |[^'\">\s]+ # bare value ) )? ) )* \s* # trailing whitespace """ , re.VERBOSE) endendtag = re. compile ( '>' ) endtagfind = re. compile ( '</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>' ) class HTMLParseError(Exception): """Exception raised for all parse errors.""" def __init__( self , msg, position = ( None , None )): assert msg self .msg = msg self .lineno = position[ 0 ] self .offset = position[ 1 ] def __str__( self ): result = self .msg if self .lineno is not None : result = result + ", at line %d" % self .lineno if self .offset is not None : result = result + ", column %d" % ( self .offset + 1 ) return result class HTMLParser(markupbase.ParserBase): """Find tags and other markup and call handler functions. Usage: p = HTMLParser() p.feed(data) ... p.close() Start tags are handled by calling self.handle_starttag() or self.handle_startendtag(); end tags by self.handle_endtag(). The data between tags is passed from the parser to the derived class by calling self.handle_data() with the data as argument (the data may be split up in arbitrary chunks). Entity references are passed by calling self.handle_entityref() with the entity reference as the argument. Numeric character references are passed to self.handle_charref() with the string containing the reference as the argument. """ CDATA_CONTENT_ELEMENTS = ( "script" , "style" ) def __init__( self ): """Initialize and reset this instance.""" self .reset() def reset( self ): """Reset this instance. Loses all unprocessed data.""" self .rawdata = '' self .lasttag = '???' self .interesting = interesting_normal markupbase.ParserBase.reset( self ) def feed( self , data): """Feed data to the parser. Call this as often as you want, with as little or as much text as you want (may include '\n'). """ self .rawdata = self .rawdata + data self .goahead( 0 ) def close( self ): """Handle any buffered data.""" self .goahead( 1 ) def error( self , message): raise HTMLParseError(message, self .getpos()) __starttag_text = None def get_starttag_text( self ): """Return full source of start tag: '<...>'.""" return self .__starttag_text def set_cdata_mode( self ): self .interesting = interesting_cdata def clear_cdata_mode( self ): self .interesting = interesting_normal # Internal -- handle data as far as reasonable. May leave state # and data to be processed by a subsequent call. If 'end' is # true, force handling all data as if followed by EOF marker. def goahead( self , end): rawdata = self .rawdata i = 0 n = len (rawdata) while i < n: match = self .interesting.search(rawdata, i) # < or & if match: j = match.start() else : j = n if i < j: self .handle_data(rawdata[i:j]) i = self .updatepos(i, j) if i = = n: break startswith = rawdata.startswith if startswith( '<' , i): if starttagopen.match(rawdata, i): # < + letter k = self .parse_starttag(i) elif startswith( "</" , i): k = self .parse_endtag(i) elif startswith( "<!--" , i): k = self .parse_comment(i) elif startswith( "<?" , i): k = self .parse_pi(i) elif startswith( "<!" , i): k = self .parse_declaration(i) elif (i + 1 ) < n: self .handle_data( "<" ) k = i + 1 else : break if k < 0 : if end: self .error( "EOF in middle of construct" ) break i = self .updatepos(i, k) elif startswith( "&#" , i): match = charref.match(rawdata, i) if match: name = match.group()[ 2 : - 1 ] self .handle_charref(name) k = match.end() if not startswith( ';' , k - 1 ): k = k - 1 i = self .updatepos(i, k) continue else : if ";" in rawdata[i:]: #bail by consuming &# self .handle_data(rawdata[ 0 : 2 ]) i = self .updatepos(i, 2 ) break elif startswith( '&' , i): match = entityref.match(rawdata, i) if match: name = match.group( 1 ) self .handle_entityref(name) k = match.end() if not startswith( ';' , k - 1 ): k = k - 1 i = self .updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: # match.group() will contain at least 2 chars if end and match.group() = = rawdata[i:]: self .error( "EOF in middle of entity or char ref" ) # incomplete break elif (i + 1 ) < n: # not the end of the buffer, and can't be confused # with some other construct self .handle_data( "&" ) i = self .updatepos(i, i + 1 ) else : break else : assert 0 , "interesting.search() lied" # end while if end and i < n: self .handle_data(rawdata[i:n]) i = self .updatepos(i, n) self .rawdata = rawdata[i:] # Internal -- parse processing instr, return end or -1 if not terminated def parse_pi( self , i): rawdata = self .rawdata assert rawdata[i:i + 2 ] = = '<?' , 'unexpected call to parse_pi()' match = piclose.search(rawdata, i + 2 ) # > if not match: return - 1 j = match.start() self .handle_pi(rawdata[i + 2 : j]) j = match.end() return j # Internal -- handle starttag, return end or -1 if not terminated def parse_starttag( self , i): self .__starttag_text = None endpos = self .check_for_whole_start_tag(i) if endpos < 0 : return endpos rawdata = self .rawdata self .__starttag_text = rawdata[i:endpos] # Now parse the data between i+1 and j into a tag and attrs attrs = [] match = tagfind.match(rawdata, i + 1 ) assert match, 'unexpected call to parse_starttag()' k = match.end() self .lasttag = tag = rawdata[i + 1 :k].lower() while k < endpos: m = attrfind.match(rawdata, k) if not m: break attrname, rest, attrvalue = m.group( 1 , 2 , 3 ) if not rest: attrvalue = None elif attrvalue[: 1 ] = = '\'' = = attrvalue[ - 1 :] or \ attrvalue[: 1 ] = = '"' = = attrvalue[ - 1 :]: attrvalue = attrvalue[ 1 : - 1 ] attrvalue = self .unescape(attrvalue) attrs.append((attrname.lower(), attrvalue)) k = m.end() end = rawdata[k:endpos].strip() if end not in ( ">" , "/>" ): lineno, offset = self .getpos() if "\n" in self .__starttag_text: lineno = lineno + self .__starttag_text.count( "\n" ) offset = len ( self .__starttag_text) \ - self .__starttag_text.rfind( "\n" ) else : offset = offset + len ( self .__starttag_text) self .error( "junk characters in start tag: %r" % (rawdata[k:endpos][: 20 ],)) if end.endswith( '/>' ): # XHTML-style empty tag: <span attr="value" /> self .handle_startendtag(tag, attrs) else : self .handle_starttag(tag, attrs) if tag in self .CDATA_CONTENT_ELEMENTS: self .set_cdata_mode() return endpos # Internal -- check to see if we have a complete starttag; return end # or -1 if incomplete. def check_for_whole_start_tag( self , i): rawdata = self .rawdata m = locatestarttagend.match(rawdata, i) if m: j = m.end() next = rawdata[j:j + 1 ] if next = = ">" : return j + 1 if next = = "/" : if rawdata.startswith( "/>" , j): return j + 2 if rawdata.startswith( "/" , j): # buffer boundary return - 1 # else bogus input self .updatepos(i, j + 1 ) self .error( "malformed empty start tag" ) if next = = "": # end of input return - 1 if next in ( "abcdefghijklmnopqrstuvwxyz=/" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ): # end of input in or before attribute value, or we have the # '/' from a '/>' ending return - 1 self .updatepos(i, j) self .error( "malformed start tag" ) raise AssertionError( "we should not get here!" ) # Internal -- parse endtag, return end or -1 if incomplete def parse_endtag( self , i): rawdata = self .rawdata assert rawdata[i:i + 2 ] = = "</" , "unexpected call to parse_endtag" match = endendtag.search(rawdata, i + 1 ) # > if not match: return - 1 j = match.end() match = endtagfind.match(rawdata, i) # </ + tag + > if not match: self .error( "bad end tag: %r" % (rawdata[i:j],)) tag = match.group( 1 ) self .handle_endtag(tag.lower()) self .clear_cdata_mode() return j # Overridable -- finish processing of start+end tag: <tag.../> def handle_startendtag( self , tag, attrs): self .handle_starttag(tag, attrs) self .handle_endtag(tag) # Overridable -- handle start tag def handle_starttag( self , tag, attrs): pass # Overridable -- handle end tag def handle_endtag( self , tag): pass # Overridable -- handle character reference def handle_charref( self , name): pass # Overridable -- handle entity reference def handle_entityref( self , name): pass # Overridable -- handle data def handle_data( self , data): pass # Overridable -- handle comment def handle_comment( self , data): pass # Overridable -- handle declaration def handle_decl( self , decl): pass # Overridable -- handle processing instruction def handle_pi( self , data): pass def unknown_decl( self , data): self .error( "unknown declaration: %r" % (data,)) # Internal -- helper to remove special character quoting entitydefs = None def unescape( self , s): if '&' not in s: return s def replaceEntities(s): s = s.groups()[ 0 ] if s[ 0 ] = = "#" : s = s[ 1 :] if s[ 0 ] in [ 'x' , 'X' ]: c = int (s[ 1 :], 16 ) else : c = int (s) return unichr (c) else : # Cannot use name2codepoint directly, because HTMLParser supports apos, # which is not part of HTML 4 import htmlentitydefs if HTMLParser.entitydefs is None : entitydefs = HTMLParser.entitydefs = { 'apos' :u "'" } for k, v in htmlentitydefs.name2codepoint.iteritems(): entitydefs[k] = unichr (v) try : return self .entitydefs[s] except KeyError: return '&' + s + ';' return re.sub(r "&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));" , replaceEntities, s) 大家可以看到,其实内部的很多的方法都是没有实现的,所以需要我们继承这个类,自己去实现一些方法。关于HTMLParser的方法,大家可以参考官方文档: http://docs.python.org/library/htmlparser.html#HTMLParser.HTMLParser(英文,笔者没有多少时间去翻译这些) 另外,给一个例子大家对照着看看,我相信这么简单的例子,大家都能看懂的。 假设我们要处理的文件在d盘根目录下,名字为hello.html,文件的内容为: <! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> < html xmlns="http://www.w3.org/1999/xhtml"> < head > < meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> < title >Rollen Holt - cnblogs</ title > < meta name="keywords" content="Rollen Holt,rollenholt" /> < link type="text/css" rel="stylesheet" href="http://www.cnblogs.com/css/common.css"/> < link id="MainCss" type="text/css" rel="stylesheet" href="http://www.cnblogs.com/Skins/kubrick/style.css"/> < link type="text/css" rel="stylesheet" href="http://www.cnblogs.com/css/common2.css"/> < link type="text/css" rel="stylesheet" href="http://common.cnblogs.com/css/shCore.css"/> < link type="text/css" rel="stylesheet" href="http://common.cnblogs.com/css/shThemeDefault.css"/> < link title="RSS" type="application/rss+xml" rel="alternate" href="http://www.cnblogs.com/rollenholt/rss"/> < link title="RSD" type="application/rsd+xml" rel="EditURI" href="http://www.cnblogs.com/rollenholt/rsd.xml"/> < link type="application/wlwmanifest+xml" rel="wlwmanifest" href="http://www.cnblogs.com/rollenholt/wlwmanifest.xml"/> < script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></ script > < script src="/script/common.js" type="text/javascript"></ script > < script src="http://common.cnblogs.com/script/jquery.json-2.2.min.js" type="text/javascript"></ script > < script type="text/javascript" src="http://common.cnblogs.com/script/shCore.js"></ script > < script type="text/javascript" src="http://common.cnblogs.com/script/shLanguage.js"></ script > </ head > < body > < a name="top"></ a > < form method="post" action="" id="Form1"> < div class="aspNetHidden"> < input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="" /> </ div > </ form > </ body > </ html > 我们的python代码为: #coding=utf-8 from HTMLParser import HTMLParser class MyParser(HTMLParser): """一个简单的HTMLparser的例子""" def handle_decl( self , decl): """处理头文档""" HTMLParser.handle_decl( self , decl) print decl def handle_starttag( self , tag, attrs): """处理起始标签""" HTMLParser.handle_starttag( self , tag, attrs) if not HTMLParser.get_starttag_text( self ).endswith( "/>" ): print "<" ,tag, ">" def handle_data( self , data): """处理文本元素""" HTMLParser.handle_data( self , data) print data, def handle_endtag( self , tag): """处理结束标签""" HTMLParser.handle_endtag( self , tag) if not HTMLParser.get_starttag_text( self ).endswith( "/>" ): print "</" ,tag, ">" def handle_startendtag( self , tag, attrs): """处理自闭标签""" HTMLParser.handle_startendtag( self , tag, attrs) print HTMLParser.get_starttag_text( self ) def handle_comment( self , data): """处理注释""" HTMLParser.handle_comment( self , data) print data def close( self ): HTMLParser.close( self ) print "parser over" demo = MyParser() demo.feed( open ( "d:\\hello.html" ).read()) demo.close() 输出的结果为: DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" < html > < head > <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> < title > Rollen Holt - cnblogs </ title > <meta name="keywords" content="Rollen Holt,rollenholt" /> <link type="text/css" rel="stylesheet" href="http://www.cnblogs.com/css/common.css"/> <link id="MainCss" type="text/css" rel="stylesheet" href="http://www.cnblogs.com/Skins/kubrick/style.css"/> <link type="text/css" rel="stylesheet" href="http://www.cnblogs.com/css/common2.css"/> <link type="text/css" rel="stylesheet" href="http://common.cnblogs.com/css/shCore.css"/> <link type="text/css" rel="stylesheet" href="http://common.cnblogs.com/css/shThemeDefault.css"/> <link title="RSS" type="application/rss+xml" rel="alternate" href="http://www.cnblogs.com/rollenholt/rss"/> <link title="RSD" type="application/rsd+xml" rel="EditURI" href="http://www.cnblogs.com/rollenholt/rsd.xml"/> <link type="application/wlwmanifest+xml" rel="wlwmanifest" href="http://www.cnblogs.com/rollenholt/wlwmanifest.xml"/> < script > </ script > < script > </ script > < script > </ script > < script > </ script > < script > </ script > </ head > < body > < a > </ a > < form > < div > <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="" /> parser over ============================================================================== 本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2011/12/01/2271058.html,如需转载请自行联系原作者

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

算法学习--数组

一个数组存放了2n+1个整数,其中有n个数出现了2次,1个数出现了1次,找出出现1次的数是多少? //方法一:借助辅助数组(长度为n+1,元素为一结构体(包含数值和 //个数两个成员))进行计数,但是时间复杂度为O(n*n),空间复杂度为O(n+1) //本来是想把Val定义为结构体的,但由于结构体是值类型,不是引用类型, //添加到List结合中的元素的属性值不能被修改,把List中的一个元素赋给另一个Val,修改Val中的value和num, //List中对应的Val相关的属性值是不会改变的,因为他们是内存中的两个不同单元 //总之:谁叫我C学得不好,用的是C#呢,不然就用C实现了。 public class Val {public int value;//值 public int num;//出现的次数 }public int FindA(int[] A, int n) { List<Val> list = new List<Val>(); Val val ; int j=0;for (int i = 0; i < n ; i++) {while (j < n) {bool isExist = false;for(int k=0;k<list.Count;k++) { if (list[k].value == A[j]) { isExist = true; list[k].num = 2;break; } }if (!isExist) { val = new Val(); val.value = A[j]; val.num = 1; list.Add(val); } j++; } }int result = -1;foreach (Val v in list) {if (v.num == 1) { result = v.value;break; } }return result; }//方法二:借助一个长度为n/2+1的数组B,如果A中的元素不在B中,就存入B中,//如果在B中,存在的那个元素后面所有的元素向前移一个单位,相当于去掉这个在B中存在的元素,//这一进一出的,出现偶数次的都去掉了,只剩下出现奇数次的元素。 public int FindI(int[] A, int n) {int[] B = new int[n / 2 + 1];int k = 0;for (int i = 0; i < n; i++) {bool isExist = false;for (int j = 0; j <= k; j++) {if (A[i] == B[j]) { isExist = true;for (int f = j; f < k - 1; f++) { B[f] = B[f + 1]; } k--;break; } }if (!isExist) { B[k] = A[i]; k++; } }return B[0]; }//方法三:排序。相等的数当然就在一起,单独的那个数就是那个只出现一次的了,哈哈... public int FindS(int[] A, int n) {for (int i = 0; i < n - 1; i++) {for (int j = i + 1; j < n; j++) {if (A[i] > A[j]) {int temp = A[j]; A[j] = A[i]; A[i] = temp; } } }int result = -1;for (int i = 0; i < n; i = i + 2) {if (A[i] != A[i + 1]) { result = A[i];break; } }return result; }//方法四:异或运算(博客园这位帅哥牛) //异或运算 0与任何数异或等于任何数,相等的两个数异或等于0,//也就是两个数对应的二进制位进行异或运算;0^0=0 , 1^0=1 , 0^1=1 , 1^1=0//出现偶数次都完蛋了,就剩下出现奇数次的了 public int FindSpecial(int[] A, int n) {int res = 0;for (int i = 0; i < n; i++) { res = res ^ A[i]; }return res; } 本文转自啊汉博客园博客,原文链接:http://www.cnblogs.com/hlxs/archive/2010/11/16/2087989.html

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

Android开发学习清单

目录: 第1章 Android应用与开发环境 1.1 Android的发展和历史 1.1.1 Android的发展和简介 1.1.2 Android平台架构及特性 1.2 搭建Android开发环境 1.2.1下载和安装Android SDK 1.2.2 安装Eclipse和ADT插件 1.3 Android常用开发工具的用法 1.3.1创建、删除和浏览AVD 1.3.2 使用Android模拟器(Emulator) 1.3.3使用DDMS进行调试android调试输出 1.3.4 Android Debug Bridge(ADB)的用法 1.3.5 使用DX编译Android应用 1.3.6 使用Android Asset Packaging Tool(AAPT)打包资源 1.3.7 使用mksdcard管理虚拟SD卡 1.4 开始第一个Android应用 1.4.1 使用Eclipse开发第一个Android应用 1.4.2 通过ADT运行Android应用 1.5Android应用结构分析 1.5.1 创建一个Android应用 1.5.2 自动生成的R.java 1.5.3 res目录说明 1.5.4 Android应用的清单文件:AndroidManifest.xml 1.5.5应用程序权限说明 1.6 Android应用的基本组件介绍 1.6.1 Activity和View 1.6.2Android中Services简析 1.6.3 BroadcastReceiver 1.6.4 ContentProvider 1.6.5 Intent和IntentFilter 1.7 本章小结 第2章 Android应用的界面编程2.1 界面编程与视图(View)组件 2.1.1 视图组件与容器组件 2.1.2 使用XML布局文件控制UI界面 2.1.3 在代码中控制UI界面 2.1.4 使用XML布局文件和Java代码混合控制UI界面 2.1.5 开发自定义View 2.2 布局管理器 2.2.1线性布局 2.2.2表格布局 2.2.3 帧布局 2.2.4相对布局 2.2.5绝对布局 2.2.6 框架布局 2.2.7layout_weight详解 2.2.8Android中include标签的使用 2.2.9Android LayoutInflater详解2.3 基本界面组件 2.3.1文本框(TextView)与编辑框(EditText)的功能和用法 2.3.1.1TextView显示html文件中的图片 2.3.2按钮(Button)与图片按钮(ImageButton)组件的功能和用法 2.3.3 使用9Patch图片作为按钮背景 2.3.4单选按钮(RadioButton)和复选框(CheckBox)介绍与应用 2.3.5状态开关按钮ToggleButton的功能与用法 2.3.6 时钟(AnalogClock和DigitalClock)的功能与功法 2.3.7图像视图(ImageView)的功能和用法 2.4 高级界面组件 2.4.1自动完成文本框AutoCompleteTextView的功能和用法 2.4.2Spinner的功能和用法 2.4.3日期、时间选择DatePicker、TimePicker的功能和用法 2.4.4进度条ProgressBar的功能和用法 2.4.5拖动条SeekBar的功能和用法 2.4.6 星级评分条(RatingBar) 的功能和用法 2.4.7选项卡TabHost的功能和用法 2.4.8 滚动视图(ScrollView) 的功能和用法 2.4.9列表视图(ListView和ListActivity) 2.4.9.1Android中动态更新ListView(转) 2.4.10 可展开的列表组件(ExpandableListView) 2.4.11网格视图(GridView)和图像切换器(ImageSwitcher)功能和用法 2.4.12画廊视图Gallery的功能和用法 2.5 对话框 2.5.1 使用AlertDialog创建简单对话框 2.5.2 使用AlertDialog创建列表对话框 2.5.3 使用AlertDialog创建自定义对话框 2.5.4 使用PopupWindow 2.5.5 使用DatePickerDialog、TimePickerDialog 2.5.6 使用ProgressDialog创建进度对话框 2.6 消息提示 2.6.1 使用Toast显示提示信息框 2.6.2Notification的功能与用法 2.7 菜单 2.7.1 选项菜单和子菜单(SubMenu) 2.7.2 使用监听器来监听菜单事件 2.7.3 创建复选菜单项和单选菜单项 2.7.4 设置与菜单项关联的Activity 2.7.5 上下文菜单 2.8 本章小结 第3章 事件处理 3.1 Android的事件处理 3.2 基于监听的事件处理 3.2.1 事件监听的处理模型 3.2.2 事件和事件监听器 3.2.3 内部类作为事件监听器类 3.2.4 外部类作为事件监听器类 3.2.5 Activity本身作为事件监听器 3.2.6 匿名内部类作为事件监听器类 3.2.7 直接绑定到标签 3.3 基于回调的事件处理 3.3.1 回调机制与监听机制 3.3.2 基于回调的事件传播 3.3.3 重写onTouchEvent方法响应触摸屏事件 3.4 响应的系统设置的事件 3.4.1 Configuration类简介 3.4.2 重写onConfigurationChanged响应系统设置更改 3.5 Handler消息传递机制 3.5.1 Handler类简介 3.5.2Handler使用案例 3.6 本章小结 第4章 深入理解Activity4.1 建立、配置和使用Activity 4.1.1 建立Activity 4.1.2 配置Activity 4.1.3 启动、关闭Activity 4.1.4使用Bundle在Activity之间交换数据 4.1.5启动其他Activity并返回结果 activity结束之后刷新之前的activity的内容 4.2 Activity的回调机制 4.3 Activity的生命周期 4.3.1 Activity的生命周期演示 4.3.2 Activity与Servlet的相似性与区别 4.4 本章小结 第5章 使用Intent和IntentFilter进行通信5.1 Intent对象详解 5.1.1使用Intent启动系统组件5.2 Intent的属性及intent-filter配置 5.2.1 Component属性 5.2.2 Action、Category属性与intent-filter配置 5.2.3 指定Action、Category调用系统Activity 5.2.4 Data、Type属性与intent-filter配置 5.2.5 Extra属性5.3 使用Intent创建Tab页面 5.4 本章小结 第6章 Android应用的资源6.1 资源的类型及存储方式 6.1.1 资源的类型以及存储方式 6.1.2 使用资源6.2使用字符串、颜色、尺寸资源 6.2.1 颜色值的定义 6.2.2定义字符串、颜色、尺寸资源文件android 中resources管理 6.2.3Android中自定义属性(attrs.xml,TypedArray的使用) 6.2.4Android中关于dip和px以及转换的总结 6.3 数组(Array)资源6.4 使用(Drawable)资源 6.4.1 图片资源 6.4.2 StateListDrawable资源 6.4.3 LayerDrawable资源 6.4.4 ShapeDrawable资源 6.4.5 ClipDrawable资源 6.4.6 AnimationDrawable资源6.5 使用原始XML资源 6.5.1 定义原始XML资源 6.5.2 使用原始XML文件 6.6 使用布局(Layout)资源6.7 使用菜单(Menu)资源 6.7.1 定义菜单资源 6.7.2 使用菜单资源6.8 样式(Style)和主题(Theme)资源 6.8.1样式资源 6.8.2主题资源6.9 属性(Attribute)资源6.10 使用原始资源6.11 国际化和资源自适应 6.11.1 Java国际化的思路 6.11.2 Java支持的语言和国家 6.11.3 完成程序国际化 6.11.4 为Android应用提供国际化资源 6.11.5 国际化Android应用 6.12 本章小结 第7章 图形与图像处理7.1 使用简单图片 7.1.1 使用Drawable对象 7.1.2 Bitmap和BitmapFactory7.2 绘图 7.2.1 Android绘图基础:Canvas、Paint等 7.2.2 Path类 7.2.3 绘制游戏动画7.3 图形特效处理 7.3.1 使用Matrix控制变换 7.3.2 使用drawBitmapMesh扭曲图像 7.3.3 使用Shader填充图形7.4 逐帧(Frame)动画 7.4.1 AnimationDrawable与逐帧动画7.5 补间(Tween)动画 7.5.1 Tween动画与Interpolator 7.5.2 位置、大小、旋转度、透明度改变的补间动画 7.5.3 自定义补间动画7.6 使用SurfaceView实现动画 7.6.1 SurfaceView的绘图机制 7.7 本章小结 第8章 Android的数据存储和IO8.1 使用SharedPreferences 8.1.1 SharedPreferences与Editor简介 8.1.2 SharedPreferences的存储位置和格式 8.1.3 读、写其他应用Shared Preferences8.2 File存储 8.2.1 openFileOutput和open FileInput 8.2.2读写SD卡上的文件8.3SQLite数据库 8.3.1 简介SQLiteDatabase 8.3.2 创建数据库和表 8.3.3 使用SQL语句操作SQLite数据库 8.3.4 使用sqlite3工具 8.3.5 使用特定方法操作SQLite数据库 8.3.6 事务 8.3.7 SQLiteOpenHelper类8.4 手势(Gesture) 8.4.1 手势检测 8.4.2 增加手势 8.4.3 识别用户的手势8.5 自动朗读(TTS) 8.6 本章小结 第9章 使用ContentProvider实现数据共享 9.1 数据共享标准:ContentProvider简介 9.1.1 ContentProvider简介 9.1.2 Uri简介 9.1.3 使用ContentResolver操作数据 9.2 操作系统的ContentProvider 9.2.1 使用ContentProvider管理联系人 9.2.2 使用ContentProvider管理多媒体内容 9.3 实现ContentProvider 9.3.1 创建ContentProvider的步骤 9.4 监听ContentProvider的数据改变 9.4.1 ContentObserver简介 9.5 本章小结 第10章 Service与BroadcastReceiver10.1 Service简介 10.1.1 创建、配置Service 10.1.2 启动和停止Service 10.1.3绑定本地Service并与之通信 10.1.4 Service的生命周期10.2 跨进程调用Service(AIDL服务) 10.2.1 AIDL服务简介 10.2.2 创建AIDL文件 10.2.3 将接口暴露给客户端 10.2.4 客户端访问AIDLService 10.2.5Android中Services之异步IntentService 10.3 电话管理器(TelephonyManager)Android监听来电和去电 10.4 短信管理器(SmsManager) 10.5 音频管理器(AudioManager) 10.5.1 AudioManager简介10.6 振动器(Vibrator) 10.6.1 Vibrator简介 10.6.2 使用Vibrator控制手机振动10.7 手机闹钟服务(AlarmManager) 10.7.1 AlarmManager简介 10.7.2 设置闹钟10.8 接收广播消息 10.8.1BroadcastReceiver简介 10.8.2 发送广播 10.8.3 有序广播10.9 接收系统广播消息 10.10在Android中实现service动态更新UI界面 第11章 多媒体应用开发 11.1 音频和视频的播放 11.1.1 使用MediaPlayer播放音频 11.1.2 使用SoundPool播放音效 11.1.3 使用VideoView播放视频 11.1.4 使用MediaPlayer和SurfaceView播放视频 11.2 使用MediaRecorder录制音频 11.3 控制摄像头拍照 11.3.1 通过Camera进行拍照 11.3.2 录制视频短片 11.4 本章小结 第12章 OpenGL与3D应用开发 12.1 3D图像与3D开发的基本知识 12.2 OpenGL和OpenGL ES简介 12.3 绘制2D图形 12.3.1 在Android应用中使用OpenGL ES 12.3.2 绘制平面上的多边形 12.3.3 旋转 12.4 绘制3D图形 12.4.1 构建3D图形 12.4.2 应用纹理贴图 12.5 本章小结 第13章 Android的网络应用13.1 基于TCP协议的网络通信 13.1.1 TCP协议基础 13.1.2 使用ServerSocket创建TCP服务器端 13.1.3 使用Socket进行通信 13.1.4 加入多线程 13.1.5Android的UI设计与后台线程交互 13.1.6使用AsyncTask异步更新UI界面及原理分析 13.1.7实例演示Android异步加载图片 13.1.8AsyncTask和Handler对比(转) 13.2 使用URL访问网络资源 13.2.1 使用URL读取网络资源 13.2.2 使用URLConnection提交请求13.3 使用HTTP访问网络 13.3.1 使用HttpURLConnection 13.3.2 使用Apache HttpClient13.4 使用WebView视图显示网页 13.4.1 使用WebView浏览网页 13.4.2 使用WebView加载HTML代码 13.5 使用Web Service进行网络编程13.5.1 Web Service简介 13.5.2 Web Service平台概述 13.5.3使用Android应用调用Web Service 常见问题及解决方法: Eclipse JAVA文件注释乱码 Android SDK Manager无法更新的解决 android 项目中出现红色感叹号的解决方法 Eclipse快捷键大全(转载) 设置Android程序图标 eclipse中关联文件设置方法 Android在对Sdcard进行文件的读写操作的时候报错FileNotFoundException No resource identifier found for attribute 'showAsAction' in package 'android' Android SlidingMenu 仿网易新闻客户端布局 没有R.java问题找不到getActionBar()方法 Android 2.x中使用actionbar - Actionbarsherlock Android 2.x中使用actionbar - Actionbarsherlock (2) android布局文件中android:icon="?attr/menuIconCamera"找不到对应图标路径 Cannot override the final method from SherlockFragmentActivity 移植SlidingMenu Android library,和安装example出现的问题解决 android防止内存溢出浅析 Android系统目录介绍 ImageView的scaletype属性 Android中TextView setText int 报错 本文转自欢醉博客园博客,原文链接http://www.cnblogs.com/zhangs1986/p/3608882.html如需转载请自行联系原作者 欢醉

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

Android UI学习 - Menu

Android系统里面有3种类型的菜单:options menu,context menu,sub menu。 options menu 按Menu键就会显示,用于当前的Activity。 它包括两种菜单项: 因为options menu在屏幕底部最多只能显示6个菜单项,这些菜单项称为 icon menu,icon menu只支持文字(title) 以及icon,可以设置快捷键,不支持checkbox以及radio控件,所以不能设置checkable选项。 而多于6的菜单项会以“more” icon menu来调出,称为 expanded menu。它不支持icon,其他的特性都和icon menu一样! 在Activity里面,一般通过以下函数来使用options menu: Activity::onCreateOptionsMenu (Menu menu) 创建options menu,这个函数只会在menu第一次显示时调用。 Activity::onPrepareOptionsMenu (Menu menu)更新改变options menu的内容,这个函数会在menu每次显示时调用。 Activity::onOptionsItemSelected (MenuItem item)处理选中的菜单项。 context menu 要在相应的view上按几秒后才显示的,用于view,跟某个具体的view绑定在一起。 这类型的菜单不支持icon和快捷键! 在Activity里面,一般通过以下函数来使用context menu: Activity::registerForContextMenu(View view)为某个view注册context menu,一般在Activity::onCreate里面调用。 Activity::onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)创建context menu,和options menu不同,context meun每次显示时都会调用这个函数。 Activity::onContextItemSelected(MenuItem item)处理选中的菜单项。 sub menu 以上两种menu都可以加入子菜单,但子菜单不能嵌套子菜单,这意味着在Android系统,菜单只有两层,设计时需要注意的!同时子菜单不支持icon。 xml形式的menu定义及应用 上述的三种类型的menu都能够定义为xml资源,但需要手动地使用 MenuInflater来得到Menu对象的引用。 一个菜单,对应一个xml文件,因为要求只能有一个根节点<menu>。官方说<?xml>声明可以不写,但我觉得还是写上好些,很多时候那个<?xml>声明主要是为了声明编码格式utf-8之类的。xml文件保存为res/menu/some_file.xml。Java代码引用资源: R.menu.some_file 接下来介绍相关的节点和属性(所有的属性都定义为android空间内,例如android:icon="@drawable/icon"): <menu>根节点,没有属性。 <group>表示在它里面的<item>在同一group。相关属性包括: id:group id menuCategory:对应常量Menu CATEGORY_* — 定义了一组的优先权,有 效值:container,system,secondary,和alternative orderInCategory:定义这组菜单在菜单中的默认次序,int值 checkableBehavior:这组菜单项是否checkable。有效值:none,all(单选/单选按钮radio button),single(非单选/复选类型checkboxes) visible:这组菜单是否可见 true or false enabled:这组菜单是否可用,true or false <item> 菜单项,可以嵌入<menu>作为子菜单。相关属性包括: id: item id menuCategory: 用来定义menu类别 orderInCategory: 用来定义次序,与一个组在一起(Used to define the order of the item, within a group ) title: 标题 titleCondensed:标题摘要, 当原标题太长的时候,需要用简短的字符串来代替title icon: icon 图标 alphabeticShortcut: 字母快捷键 numericShortcut:数学快捷键 checkable:是否为checkbox, true or false checked:是否设置为checked状态,true or false visible: 是否可见, true or false enabled:是否可用,true or false xml示例: <?xmlversion="1.0"encoding="utf-8"?> <menuxmlns:android="http://schemas.android.com/apk/res/android"> <itemandroid:id="@+id/item1" android:title="Item1" android:icon="@drawable/icon" android:checkable="true" android:checked="false" /> <groupandroid:id="@+id/group_1" android:checkableBehavior="single"> <itemandroid:id="@+id/group_item1" android:title="Item1ingroup" /> <itemandroid:id="@+id/group_item2" android:title="Item2ingroup" android:checked="true" /> </group> <itemandroid:id="@+id/submenu" android:title="SubMenu"> <menu> <itemandroid:id="@+id/submenu_item" android:title="SubMenuItem" /> </menu> </item> <itemandroid:id="@+id/item3" android:title="item3" android:checkable="true" android:checked="true" /> </menu> Java代码 publicvoidonCreate(BundlesavedInstanceState){ ... registerForContextMenu(editText); } @Override publicvoidonCreateContextMenu(ContextMenumenu,Viewv, ContextMenuInfomenuInfo){ super.onCreateContextMenu(menu,v,menuInfo); getMenuInflater().inflate(R.menu.menu1,menu); } 效果图 由于这是contextMenu,所以可以看到即使xml定义里面的item1.seticon了,但还是没有显示出来的,即那语句是无效的! 另外,要明确的是,要显示radio,需要用group,而group里面的item设置了checked = true即选中。而checkable和checked的区别,一开始我是很困惑的,但写了代码并运行后,明白它们的区别了: checkable=true表示这个item是checkbox, checked则表示是否选中。所以对于checkbox item,最好先写 checkable="true",然后再写checked。 Java实现 用Java来实现以上的效果图,就比较麻烦些: privatestaticfinalintMENU_GROUPITEM1=Menu.FIRST+8; privatestaticfinalintMENU_GROUPITEM2=Menu.FIRST+9; privatestaticfinalintMENU_ITEM1=Menu.FIRST+10; publicvoidonCreate(BundlesavedInstanceState){ ... registerForContextMenu(findViewById(R.id.edittext)); } @Override publicvoidonCreateContextMenu(ContextMenumenu,Viewv, ContextMenuInfomenuInfo){ super.onCreateContextMenu(menu,v,menuInfo); menu.add(1,MENU_ITEM1,Menu.NONE,"Item1").setCheckable(true).setChecked(false); //GroupID intgroupId=0; //Theorderpositionoftheitem intmenuItemOrder=Menu.NONE; menu.add(groupId,MENU_GROUPITEM1,menuItemOrder,"Item1ingroup"); menu.add(groupId,MENU_GROUPITEM2,menuItemOrder,"Item2ingroup") .setChecked(true); menu.setGroupCheckable(groupId,true,true);//这句要写在groupitem的最后 SubMenusubMenu=menu.addSubMenu("SubMenu1"); subMenu.add("SubMenuItem") .setOnMenuItemClickListener(newMenuItem.OnMenuItemClickListener(){ @Override publicbooleanonMenuItemClick(MenuItemitem){ Toast.makeText(HelloDemo.this, "SubMenuItemselected", Toast.LENGTH_SHORT).show(); returntrue;//true表示完成当前item的click处理,不再传递到父类处理 } }); menu.add("Item3").setCheckable(true).setChecked(true); } 在编写过程中,发现groupId的影响很大,不推荐使用Menu.add(int titleRes)和add(CharSequence title)方法来添加MenuItem,因为没有指定groupID,默认为0,这样子和后面的menu group 一组了,导致执行完 menu.setGroupCheckable(groupId,true,true)后同一group的Item都变成radio。 OptionsMenu的Java实现 @Override publicbooleanonCreateOptionsMenu(Menumenu){ //GroupID intgroupId=0; //Theorderpositionoftheitem intmenuItemOrder=Menu.NONE; menu.add(groupId,MENU_COPY,menuItemOrder,"Copy") .setIcon(R.drawable.icon); menu.add(groupId,MENU_EDIT,menuItemOrder,"Edit"); menu.add(groupId,MENU_PASTE,menuItemOrder,"Paste"); menu.add(groupId,MENU_DELETE,menuItemOrder,"Delete"); menu.add(groupId,MENU_OK,menuItemOrder,"Ok"); menu.add(groupId,MENU_CANCEL,menuItemOrder,"Cancel"); menu.add(groupId,MENU_TEST,menuItemOrder,"Test"); menu.add(groupId,MENU_DEMO,menuItemOrder,"Demo"); //.setIcon(R.drawable.icon);moreexpandmenu不支持icon,setIcon不会报错,但运行时还是看不到icon的 //returnsuper.onCreateOptionsMenu(menu); returntrue;//true表示要显示menu;false表示不显示menu } 处理菜单点击事件 方法一: 利用菜单自带的监听器功能,直接监听,就象处理控件事件一样,像上面的ContextMenu的 subMenu.add("SubMenuItem")设置MenuItem.OnMenuItemClickListener。 方法二: 在Activity和View都直接提供了一个菜单点击统一处理函数, Activity::onOptionsItemSelected (MenuItem item); Activity::onContextItemSelected(MenuItem item) ; @Override publicbooleanonOptionsItemSelected(MenuItemitem){ switch(item.getItemId()){ caseMENU_COPY: Toast.makeText(this,"CopyItemselected",Toast.LENGTH_SHORT).show(); break; default:break; } returnfalse;//false表示继续传递到父类处理 } 效果图 动态菜单 对于OptionsMenu,一般可以使用onPrepareOptionsMenu来改变。 另外,使用函数 android.view.Menu.addIntentOptions(int groupId,int itemId,int order,ComponentName caller, Intent[] specifics, Intent intent,int flags,MenuItem[] outSpecificItems) Specifics 以action+uri的具体方式来增加激活相应activity的菜单项 Intent 以categroy+uri这种一般形式来增加激活相应activity的菜单项 参数Intent和Specifics的区别是,一个用categroy+uri来匹配activity,一个用action+uri来匹配activity。 //按Action查找 Intent[] specifics = new Intent[1]; specifics[0] = new Intent(Intent.ACTION_EDIT, uri); //按Category查找,Action设为null Intent intent = new Intent(null, uri); intent.addCategory(Intent.CATEGORY_ALTERNATIVE); MenuItem[] items = new MenuItem[1]; menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0, null, specifics, intent, 0, items); 有关Menu的创建可以参考官方的 http://androidappdocs.appspot.com/guide/topics/ui/menus.html。另外官方提供了Menu Design Guidelines http://androidappdocs.appspot.com/guide/practices/ui_guidelines/menu_design.html 本文转自 Icansoft 51CTO博客,原文链接:http://blog.51cto.com/android/306424

资源下载

更多资源
Mario

Mario

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

腾讯云软件源

腾讯云软件源

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

Nacos

Nacos

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

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册