android开发知识小汇2

来源:互联网 发布:hadoop是java写的吗 编辑:程序博客网 时间:2024/05/17 00:05
Android开发之ListView 适配器(Adapter)优化
readme外部引用原始文档
12345678
Adapter的作用就是ListView界面与数据之间的桥梁,当列表里的每一项显示到页面时,都会调用Adapter的getView方法返回一个View。想过没有? 在我们的列表有1000000项时会是什么样的?是不是会占用极大的系统资源?下面是三种优化级别level1是最基础的使用level2是稍微优化level3是优化过后的代码原文地址:http://blog.csdn.net/zuolongsnail/article/details/7197979
未命名.jpg外部引用原始文档
level1.java外部引用原始文档
1234567
public View getView(int position, View convertView, ViewGroup parent) {View item = mInflater.inflate(R.layout.list_item_icon_text, null);((TextView) item.findViewById(R.id.text)).setText(DATA[position]);((ImageView) item.findViewById(R.id.icon)).setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);return item;}
level2.java外部引用原始文档
 1 2 3 4 5 6 7 8 910
public View getView(int position, View convertView, ViewGroup parent) {if (convertView == null) {convertView = mInflater.inflate(R.layout.item, null);}((TextView) convertView.findViewById(R.id.text)).setText(DATA[position]);((ImageView) convertView.findViewById(R.id.icon)).setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);return convertView;}
level3.java外部引用原始文档
 1 2 3 4 5 6 7 8 91011121314151617181920
public View getView(int position, View convertView, ViewGroup parent) {ViewHolder holder;if (convertView == null) {convertView = mInflater.inflate(R.layout.list_item_icon_text, null);holder = new ViewHolder();holder.text = (TextView) convertView.findViewById(R.id.text);holder.icon = (ImageView) convertView.findViewById(R.id.icon);convertView.setTag(holder);} else {holder = (ViewHolder) convertView.getTag();}holder.text.setText(DATA[position]);holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);return convertView;}static class ViewHolder {TextView text;ImageView icon;}




Android HttpClient上传文件(亲测,成功)
README.md外部引用原始文档
1
 Android HttpClient上传文件  的一个封装方法。里面有一小段代码是处理获取JSON格式数据 

System.out.println("executing request " + httppost.getRequestLine()); 返回协议和返回码 
正确的话是 http 1.1 200 
System.out.println(EntityUtils.toString(resEntity,"utf-8")); 
获取处理后的页面内容

android并不自带MultipartEntity吧? 
对的。把httpmime-4.1.1.jar 这个放进lib中就可以使用 MultipartEntity了 
下载地址:http://pan.baidu.com/share/link?shareid=90009&uk=4012369003

demo.java外部引用原始文档
 1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233343536373839404142434445
public String post(String pathToOurFile,String urlServer) throws ClientProtocolException, IOException, JSONException {   HttpClient httpclient = new DefaultHttpClient();   //设置通信协议版本   httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);      //File path= Environment.getExternalStorageDirectory(); //取得SD卡的路径//String pathToOurFile = path.getPath()+File.separator+"ak.txt"; //uploadfile//String urlServer = "http://192.168.1.88/test/upload.php";    HttpPost httppost = new HttpPost(urlServer);   File file = new File(pathToOurFile);   MultipartEntity mpEntity = new MultipartEntity(); //文件传输   ContentBody cbFile = new FileBody(file);   mpEntity.addPart("userfile", cbFile); // <input type="file" name="userfile" />  对应的   httppost.setEntity(mpEntity);   System.out.println("executing request " + httppost.getRequestLine());      HttpResponse response = httpclient.execute(httppost);   HttpEntity resEntity = response.getEntity();   System.out.println(response.getStatusLine());//通信Ok   String json="";   String path="";   if (resEntity != null) {     //System.out.println(EntityUtils.toString(resEntity,"utf-8"));     json=EntityUtils.toString(resEntity,"utf-8");     JSONObject p=null;     try{     p=new JSONObject(json);     path=(String) p.get("path");     }catch(Exception e){     e.printStackTrace();     }   }   if (resEntity != null) {     resEntity.consumeContent();   }   httpclient.getConnectionManager().shutdown();   return path; }
android自定义弹出层
DialogShow.java外部引用原始文档
 1 2 3 4 5 6 7 8 91011121314151617181920212223242526
package com.asfman;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.Button;public class DialogShow extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        Button btn = (Button) findViewById(R.id.button1);        btn.setOnClickListener(new Button.OnClickListener() {            @Override            public void onClick(View v) {                // TODO Auto-generated method stub                new Tip(DialogShow.this).show();            }        });    }}
Tip.java外部引用原始文档
 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435363738394041424344
package com.asfman;import android.app.Dialog;import android.content.Context;import android.view.Gravity;import android.view.View;import android.view.ViewGroup;import android.view.Window;import android.view.WindowManager;import android.widget.ImageView;public class Tip {    private ImageView image;    private Dialog mDialog;    public Tip(Context context) {        mDialog = new Dialog(context, R.style.dialog);        Window window = mDialog.getWindow();        WindowManager.LayoutParams wl = window.getAttributes();        wl.x = -30;        wl.y = 20;        window.setAttributes(wl);        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,                WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);        //window.setGravity(Gravity.CENTER);        window.setLayout(ViewGroup.LayoutParams.FILL_PARENT,                ViewGroup.LayoutParams.WRAP_CONTENT);        mDialog.setContentView(R.layout.tip);        mDialog.setFeatureDrawableAlpha(Window.FEATURE_OPTIONS_PANEL, 0);        image = (ImageView) mDialog.findViewById(R.id.image);        image.setOnClickListener(new ImageView.OnClickListener() {            @Override            public void onClick(View arg0) {                mDialog.dismiss();            }        });    }    public void show() {        mDialog.show();    }}
dialog.xml外部引用原始文档
 1 2 3 4 5 6 7 8 91011
<?xml version="1.0" encoding="utf-8"?><resources>    <style name="dialog" parent="@android:style/Theme.Dialog"><!--         <item name="android:windowFrame">@null</item> --><!--         <item name="android:windowIsFloating">true</item> --><!--         <item name="android:windowIsTranslucent">false</item> -->        <item name="android:windowNoTitle">true</item>        <item name="android:windowBackground">@null</item><!--         <item name="android:backgroundDimEnabled">false</item> -->    </style></resources>
tip.xml外部引用原始文档
 1 2 3 4 5 6 7 8 9101112131415
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="300dp" android:layout_height="190dp"    android:orientation="vertical" android:background="@drawable/blueinfowindow">    <LinearLayout android:layout_width="fill_parent"        android:layout_height="wrap_content" android:orientation="horizontal"        android:id="@+id/upContent" android:layout_marginTop="30dp"        android:layout_marginLeft="30dp">        <TextView android:id="@+id/description" android:layout_width="220dp"            android:layout_height="wrap_content"            android:text="1.this is the test text!\n            1.this is the test text!\n1.this is the test text!\n1.this is the test text!\n" android:textColor="#000000" />        <ImageView android:id="@+id/image" android:background="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content"/>        </LinearLayout></LinearLayout>

获得手机浏览器的历史记录
history.java外部引用原始文档
 1 2 3 4 5 6 7 8 91011121314
private String history() {    String string = null;    ContentResolver contentResolver = getContentResolver();     Cursor cursor = contentResolver.query(            Uri.parse("content://browser/bookmarks"),            new String[] { "url" }, null, null, null);     while (cursor != null && cursor.moveToNext()) {        string = cursor.getString(cursor.getColumnIndex("url"));        Log.d("debug", string == null ? "null" : string);    }    return string;}



Android 打开网页搜索关键词
SearchManager.java外部引用原始文档
 1 2 3 4 5 6 7 8 9101112
String searchStr = "eoe";/* 取得网页搜寻的intent */Intent search = new Intent(Intent.ACTION_WEB_SEARCH);search.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);search.putExtra(SearchManager.QUERY, searchStr); final Bundle appData = getIntent().getBundleExtra(        SearchManager.APP_DATA);if (appData != null) {    search.putExtra(SearchManager.APP_DATA, appData);}startActivity(search);


使用SAX解析XML文件
readme外部引用原始文档
 1 2 3 4 5 6 7 8 9101112131415
SAX(Simple API for XML),是指一种接口,或者一个软件包。DOM:文档驱动。DOM在解析文件之前把整个文档装入内存,处理大型文件时其性能很差,是由于DOM的树结构所造成的,此结构占用的内存较多。SAX:事件驱动型的XML解析方式。顺序读取XML文件,不需要一次全部装载整个文件。当遇到像文件开头,文档结束,或者标签开头与标签结束时,会触发一个事件,用户通过在其回调事件中写入处理代码来处理XML文件,适合对XML的顺序访问,且是只读的。由于移动设备的内存资源有限,SAX的顺序读取方式更适合移动开发。SAX解析XML步骤①创建XML解析处理器。②创建SAX解析器。③将XML解析处理器分配给解析器。④对文档进行解析,将每个事件发送给处理器。原文地址:http://blog.csdn.net/zuolongsnail/article/details/6453468
MainActivity.java外部引用原始文档
 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435363738394041424344454647484950
/** * MainActivity *  * @author zuolongsnail *  */public class MainActivity extends Activity {private Button parseBtn;private ListView listView;private ArrayAdapter<Person> adapter;private ArrayList<Person> persons;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);parseBtn = (Button) findViewById(R.id.parse);listView = (ListView) findViewById(R.id.list);parseBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {persons = MainActivity.this.readXml();adapter = new ArrayAdapter<Person>(MainActivity.this,android.R.layout.simple_expandable_list_item_1, persons);listView.setAdapter(adapter);}});}private ArrayList<Person> readXml() {InputStream file = this.getClass().getClassLoader().getResourceAsStream("persons.xml");// ①创建XML解析处理器SAXXmlContentHandler contentHandler = new SAXXmlContentHandler();try {// 创建一个SAXParserFactorySAXParserFactory factory = SAXParserFactory.newInstance();// ②创建SAX解析器SAXParser parser = factory.newSAXParser();// ③将XML解析处理器分配给解析器// ④对文档进行解析,将每个事件发送给处理器。parser.parse(file, contentHandler);file.close();} catch (Exception e) {e.printStackTrace();}return contentHandler.getBooks();}}
SAXXmlContentHandler.java外部引用原始文档
 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
/** * 解析XML处理器 * @author zuolongsnail * */public class SAXXmlContentHandler extends DefaultHandler {private ArrayList<Person> persons;private Person person;private String tagName;public ArrayList<Person> getBooks() {return persons;}@Overridepublic void startDocument() throws SAXException {this.persons = new ArrayList<Person>();Log.e("SAXXmlContentHandler", "开始解析XML文件");}@Overridepublic void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {Log.e("SAXXmlContentHandler", "读取标签");this.tagName = localName;if(this.tagName.equals("person")){person = new Person();person.setId(Integer.parseInt(attributes.getValue(0)));}}@Overridepublic void characters(char[] ch, int start, int length)throws SAXException {Log.e("SAXXmlContentHandler", "根据tagName获取标签的内容");if (this.tagName != null) {String data = new String(ch, start, length);if (this.tagName.equals("name")) {this.person.setName(data);} else if (this.tagName.equals("age")) {this.person.setAge(Integer.parseInt(data));}}}@Overridepublic void endElement(String uri, String localName, String qName)throws SAXException {if(localName.equals("person")){this.persons.add(person);}this.tagName = null;}}
xml外部引用原始文档
 1 2 3 4 5 6 7 8 9101112131415
<?xml version="1.0" encoding="UTF-8"?><persons><person id="1"><name>张三</name><age>24</age></person><person id="2"><name>李四</name><age>25</age></person><person id="3"><name>王五</name><age>26</age></person></persons>
person.java外部引用原始文档
 1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435363738394041
/** * Person实体类 * @author zuolongsnail * */public class Person {private int id;private String name;private int age;public Person() {}public Person(int id, String name, int age) {this.id = id;this.name = name;this.age = age;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "姓名:" + this.name + ",年龄:" + this.age;}}
main.xml外部引用原始文档
 1 2 3 4 5 6 7 8 9101112
<?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="@string/hello" /><Button android:id="@+id/parse" android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="SAX解析XML" /><ListView android:id="@+id/list" android:layout_width="fill_parent"android:layout_height="fill_parent"></ListView></LinearLayout>


原创粉丝点击