Android 学习(一)

来源:互联网 发布:淘宝购物车html模板 编辑:程序博客网 时间:2024/06/08 10:05

一、Android系统框架介绍

Ø在res资源文件夹下包含有以下的文件:
Ødrawable 存放工程图片的信息,默认png格式的图片
Ølayout 存放工程的布局文件以 . xml结束
Øvalues 文件夹下面存放一个很重要的string.xml 此文件夹存放的是自定义的字符串和数值。
Ø除了这个文件之外,还可以定义arrays.xml(用来定义数组)、
Øcolor.xml(用来定义颜色和颜色字符串数值)
Ødimens.xml(用来定义尺寸数值)
Østyles.xml(用来定义样式)
Ø既然是存储值,那么在android工程中如何取值呢?

二、意图

·传递意图
1
2
3
4
5
6
7
8
Intent intent = new Intent();
// 在意图中传递数据
intent.putExtra("name""张三");
intent.putExtra("age"23);
intent.putExtra("address""北京");
intent.setClass(Main.this, OtherActivity.class);
// 启动意图
startActivity(intent);

·使用意图:

1
2
3
4
Intent intent = getIntent();
int age = intent.getIntExtra("age"0);
String name = intent.getStringExtra("name");
String address = intent.getStringExtra("address");

·具有返回结果的意图
1
2
3
4
5
Intent intent = new Intent();
int three = Integer.parseInt(editText.getText().toString());
intent.putExtra("three", three);
//通过Intent对象返回结果,setResult方法,
setResult(2, intent);

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
    button.setOnClickListener(new View.OnClickListener() {
     
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int a = Integer.parseInt(one.getText().toString());
            int b = Integer.parseInt(two.getText().toString());
            Intent intent = new Intent(Main.this, OtherActivity.class);
            intent.putExtra("a", a);
            intent.putExtra("b", b);
            //启动Intent
            startActivityForResult(intent, REQUESTCODE);// 表示可以返回结果
        }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode==2){
        if(requestCode==REQUESTCODE){
            int three = data.getIntExtra("three"0);
            result.setText(String.valueOf(three));
        }
    }
}

三、布局
oncreate方法中使用setContentView来加载指定的xml布局文件
1
setContentView(R.layout.main);
表示单位长度的方式:
Øpx:表示屏幕实际的象素。例如,320*480的屏幕在横向有320个象素,在纵向有480个象素。
Ødp(dip): 是屏幕的物理尺寸。大小为1英寸的1/72
Øsp(与刻度无关的像素):与dp类似,但是可以根据用户的字体大小首选项进行缩放。
设计技巧:
Ø如果设置表示长度、高度等属性时可以使用dp sp。但如果设置字体,需要使用sp
Ø
Ødp是与密度无关,sp除了与密度无关外,还与scale无关
Ø
Ø如果使用dpsp,系统会根据屏幕密度的变化自动进行转换。
·
·android:gravity用于设置View组件的对齐方式,而android:layout_gravity用于设置Container组件的对齐方式

·线性布局LinearLayout :

·线性布局当中:gravity用于控制布局中视图的位置,多个值用 | 分割
layout_weight 用于给一个线性布局中的诸多视图的重要度赋值。
·所有的视图都有一个layout_weight值,默认为零,意思是需要显示多大的视图就占据多大的屏幕空 间。
若赋一个高于零的值,则将父视图中的可用空间分割,分割大小具体取决于每一个视图的layout_weight值以及该值在当前屏幕布局的整体 layout_weight值和在其它视图屏幕布局的layout_weight值中所占的比率而定。
·框架布局FrameLayOut
框架布局是最简单的布局方式、所有添加到这个布局中的视图都是以层叠的方式显示。
第一个添加到框架布局中的视图显示在最底层,最后一个被放在最顶层,上一层的视图会覆盖下一层的视图,因此框架布局类似堆栈布局。
·RelativeLayout相对布局
·RelativeLayout可以设置某一个视图相对于其他视图的位置,这些位置可以包括上下左右等

属性

说明

android:layout_below

在某元素的下方

android:layout_above

在某元素的的上方

android:layout_toLeftOf

在某元素的左边

android:layout_toRightOf

在某元素的右边

·绝对布局AbsoluteLayout
·可以通过android:layout_xandroid:layout_y属性可以设置视图的横坐标和纵坐标的位置。
·TableLayout布局
·一个列的宽度由该列中最宽的那个单元格指定,而表格的宽度是由父容器指定的。
·Shrinkable,则该列的宽度可以进行收缩,以使表格能够适应其父容器的大小。
·Stretchable,则该列的宽度可以进行拉伸,以使填满表格中的空闲空间。
·Collapsed,则该列会被隐藏
·同时具有Shrinkable属性和Stretchable属性,在这种情况下,该列的宽度将任意拉伸或收缩以适应父容器

四、HTTP介绍相关
·http协议GET方式获取图片:
·
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
package com.http.get;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
 
import org.apache.http.message.BasicNameValuePair;
 
public class HttpUtils {
 
    private static String URL_PATH = "http://192.168.0.102:8080/myhttp/pro1.png";
 
    public HttpUtils() {
        // TODO Auto-generated constructor stub
    }
 
    public static void saveImageToDisk() {
        InputStream inputStream = getInputStream();
        byte[] data = new byte[1024];
        int len = 0;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("C:\\test.png");
            while ((len = inputStream.read(data)) != -1) {
                fileOutputStream.write(data, 0, len);
            }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
 
    /**
     * 获得服务器端的数据,以InputStream形式返回
     * @return
     */
    public static InputStream getInputStream() {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(URL_PATH);
            if (url != null) {
                httpURLConnection = (HttpURLConnection) url.openConnection();
                // 设置连接网络的超时时间
                httpURLConnection.setConnectTimeout(3000);
                httpURLConnection.setDoInput(true);
                // 表示设置本次http请求使用GET方式请求
                httpURLConnection.setRequestMethod("GET");
                int responseCode = httpURLConnection.getResponseCode();
                if (responseCode == 200) {
                    // 从服务器获得一个输入流
                    inputStream = httpURLConnection.getInputStream();
                }
            }
        catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return inputStream;
    }
 
    public static void main(String[] args) {
        // 从服务器获得图片保存到本地
        saveImageToDisk();
    }
}
·
·使用POST方式进行提交数据
·
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
package com.http.post;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
 
public class HttpUtils {
 
    // 请求服务器端的url
    private static String PATH = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";
    private static URL url;
 
    public HttpUtils() {
        // TODO Auto-generated constructor stub
    }
 
    static {
        try {
            url = new URL(PATH);
        catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
    /**
     * @param params
     *            填写的url的参数
     * @param encode
     *            字节编码
     * @return
     */
    public static String sendPostMessage(Map<String, String> params,
            String encode) {
        // 作为StringBuffer初始化的字符串
        StringBuffer buffer = new StringBuffer();
        try {
            if (params != null && !params.isEmpty()) {
                  for (Map.Entry<String, String> entry : params.entrySet()) {
                        // 完成转码操作
                        buffer.append(entry.getKey()).append("=").append(
                                URLEncoder.encode(entry.getValue(), encode))
                                .append("&");
                    }
                buffer.deleteCharAt(buffer.length() - 1);
            }
            // System.out.println(buffer.toString());
            // 删除掉最有一个&
             
            System.out.println("-->>"+buffer.toString());
            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();
            urlConnection.setConnectTimeout(3000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);// 表示从服务器获取数据
            urlConnection.setDoOutput(true);// 表示向服务器写数据
            // 获得上传信息的字节大小以及长度
            byte[] mydata = buffer.toString().getBytes();
            // 表示设置请求体的类型是文本类型
            urlConnection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            urlConnection.setRequestProperty("Content-Length",
                    String.valueOf(mydata.length));
            // 获得输出流,向服务器输出数据
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(mydata,0,mydata.length);
            outputStream.close();
            // 获得服务器响应的结果和状态码
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 200) {
                return changeInputStream(urlConnection.getInputStream(), encode);
            }
        catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }
 
    /**
     * 将一个输入流转换成指定编码的字符串
     
     * @param inputStream
     * @param encode
     * @return
     */
    private static String changeInputStream(InputStream inputStream,
            String encode) {
        // TODO Auto-generated method stub
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        String result = "";
        if (inputStream != null) {
            try {
                while ((len = inputStream.read(data)) != -1) {
                    outputStream.write(data, 0, len);
                }
                result = new String(outputStream.toByteArray(), encode);
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return result;
    }
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Map<String, String> params = new HashMap<String, String>();
        params.put("username""admin");
        params.put("password""1234");
        String result = HttpUtils.sendPostMessage(params, "utf-8");
        System.out.println("--result->>" + result);
    }
 
}
·
·使用apache工具类提交数据
·
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
package com.http.post;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
 
public class HttpUtils {
 
    public HttpUtils() {
        // TODO Auto-generated constructor stub
    }
 
    public static String sendHttpClientPost(String path,
            Map<String, String> map, String encode) {
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        if (map != null && !map.isEmpty()) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry
                        .getValue()));
            }
        }
        try {
            // 实现将请求的参数封装到表单中,请求体中
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
            // 使用Post方式提交数据
            HttpPost httpPost = new HttpPost(path);
            httpPost.setEntity(entity);
            // 指定post请求
            DefaultHttpClient client = new DefaultHttpClient();
            HttpResponse httpResponse = client.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                return changeInputStream(httpResponse.getEntity().getContent(),
                        encode);
            }
        catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }
 
    /**
     * 将一个输入流转换成指定编码的字符串
     
     * @param inputStream
     * @param encode
     * @return
     */
    public static String changeInputStream(InputStream inputStream,
            String encode) {
        // TODO Auto-generated method stub
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        String result = "";
        if (inputStream != null) {
            try {
                while ((len = inputStream.read(data)) != -1) {
                    outputStream.write(data, 0, len);
                }
                result = new String(outputStream.toByteArray(), encode);
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return result;
    }
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String path = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";
        Map<String, String> params = new HashMap<String, String>();
        params.put("username""admin");
        params.put("password""123");
        String result = HttpUtils.sendHttpClientPost(path, params, "utf-8");
        System.out.println("-->>"+result);
    }
 
}
·
五、Android解析XML
·android使用sax解析xml
·在Test.java中加入mian
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String path = "http://192.168.0.102:8080/myhttp/person.xml";
    InputStream inputStream = HttpUtils.getXML(path);
    try {
        List<HashMap<String, String>> list = SaxService.readXML(
                inputStream, "person");
        for (HashMap<String, String> map : list) {
            System.out.println(map.toString());
        }
    catch (Exception e) {
        // TODO: handle exception
    }
}
·在HttpUtils.java中编写如下方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static InputStream getXML(String path) {
    InputStream inputStream = null;
    try {
        URL url = new URL(path);
        if (url != null) {
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setConnectTimeout(3000);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            int code = connection.getResponseCode();
            if (code == 200) {
                inputStream = connection.getInputStream();
            }
        }
    catch (Exception e) {
        // TODO: handle exception
    }
    return inputStream;
}
·在SaxService.java中编写如下方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static List<HashMap<String, String>> readXML(
        InputStream inputStream, String nodeName) {
    try {
        // 创建一个解析xml的工厂对象
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser parser = spf.newSAXParser();// 解析xml
        MyHandler handler = new MyHandler(nodeName);
        parser.parse(inputStream, handler);
        inputStream.close();
        return handler.getList();
    catch (Exception e) {
        // TODO: handle exception
    }
    return null;
}
·MyHandler.java写法
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
package com.sax.handler;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.jar.Attributes.Name;
 
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
public class MyHandler extends DefaultHandler {
 
    private HashMap<String, String> map = null;// 存储单个解析的完整对象
    private List<HashMap<String, String>> list = null;// 存储所有的解析对象
    private String currentTag = null;// 正在解析的元素的标签
    private String currentValue = null;// 解析当前元素的值
    private String nodeName = null;// 解析当前的节点名称
 
    public MyHandler(String nodeName) {
        // TODO Auto-generated constructor stub
        this.nodeName = nodeName;
    }
 
    public List<HashMap<String, String>> getList() {
        return list;
    }
 
    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        // 当读到第一个开始标签的时候,会触发这个方法
        list = new ArrayList<HashMap<String, String>>();
    }
 
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // 当遇到文档的开头的时候,调用这个方法
        if (qName.equals(nodeName)) {
            map = new HashMap<String, String>();
        }
        if (attributes != null && map != null) {
            for (int i = 0; i < attributes.getLength(); i++) {
                map.put(attributes.getQName(i), attributes.getValue(i));
            }
        }
        currentTag = qName;
    }
 
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        // TODO Auto-generated method stub
        // 这个方法是用来处理xml文件所读取到的内容
        if (currentTag != null && map != null) {
            currentValue = new String(ch, start, length);
            if (currentValue != null && !currentValue.trim().equals("")
                    && !currentValue.trim().equals("\n")) {
                map.put(currentTag, currentValue);
            }
        }
        currentTag = null;// 把当前的节点的对应的值和标签设置为空
        currentValue = null;
 
    }
 
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        // TODO Auto-generated method stub
        // 遇到结束标记的时候,会调用这个方法
        if (qName.equals(nodeName)) {
            list.add(map);
            map = null;
        }
        super.endElement(uri, localName, qName);
    }
}
·
·android使用pull解析xml
·在Test.java中加入mian
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String path = "http://192.168.0.102:8080/myhttp/person.xml";
    InputStream inputStream = HttpUtils.getXML(path);
    List<Person> list = null;
    try {
        list = PullXMLTools.parseXML(inputStream, "utf-8");
        for (Person person : list) {
            System.out.println(person.toString());
        }
    catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 
}
·HttpUtils.java的编写同sax相同

·Person.java编写如下
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
package com.pull.domain;
public class Person {
    private int id;
    private String name;
    private int age;
    public int getId() {
        return id;
    }
    public Person(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    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;
    }
    public Person() {
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}
·PullXMLTools.java的编写如下:
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
package com.pull.parser;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import com.pull.domain.Person;
/**
 * 主要是使用PULL解析xml
 
 * @author jack
 
 */
public class PullXMLTools {
    public PullXMLTools() {
        // TODO Auto-generated constructor stub
    }
    /**
     * @param inputStream
     *            从服务器获取xml文件,以流的形式返回
     * @param encode
     *            编码格式
     * @return
     * @throws Exception
     */
    public static List<Person> parseXML(InputStream inputStream, String encode)
            throws Exception {
        List<Person> list = null;
        Person person = null;// 装载解析每一个person节点的内容
        // 创建一个xml解析的工厂
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        // 获得xml解析类的引用
        XmlPullParser parser = factory.newPullParser();
        parser.setInput(inputStream, encode);
        // 获得事件的类型
        int eventType = parser.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
            case XmlPullParser.START_DOCUMENT:
                list = new ArrayList<Person>();
                break;
            case XmlPullParser.START_TAG:
                if ("person".equals(parser.getName())) {
                    person = new Person();
                    // 取出属性值
                    int id = Integer.parseInt(parser.getAttributeValue(0));
                    person.setId(id);
                else if ("name".equals(parser.getName())) {
                    String name = parser.nextText();// 获取该节点的内容
                    person.setName(name);
                else if ("age".equals(parser.getName())) {
                    int age = Integer.parseInt(parser.nextText());
                    person.setAge(age);
                }
                break;
            case XmlPullParser.END_TAG:
                if ("person".equals(parser.getName())) {
                    list.add(person);
                    person = null;
                }
                break;
            }
            eventType = parser.next();
        }
        return list;
    }
}



自用,没看懂的实在抱歉。














































2 0
原创粉丝点击