安卓002入门

来源:互联网 发布:新闻的作用和意义知乎 编辑:程序博客网 时间:2024/06/01 21:08

2. Android 入门案例
案例-电话拨号
电话拨号案例,界面如下:
 搭建界面需要组件:TextView(请输入电话号码)、EditText(xxx号码
)、Button(呼叫此号码)
 当点击Button时获取EditText中文本
 使用Intent向系统内置的电话拨号器发送意图拨打电话
 注册拨打电话权限android.permission.CALL_PHONE
 layout布局代码
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"

        android:layout_height="wrap_content"
        android:layout_marginTop="27dp"
        android:text="请输入手机号码" />
    <EditText
        android:id="@+id/et_number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="21dp"
        android:ems="10" >
        <requestFocus />
    </EditText>
    <Button
        android:id="@+id/btn_call"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/et_number"
        android:layout_below="@+id/et_number"
        android:layout_marginTop="38dp"
        android:text="拨打此号码" />
</RelativeLayout>
 Activity代码
package com.itheima.phonedail;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
    
    /**
     * activitiy 第一次创建的时候调用
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 加载 activity 需要显示布局

        setContentView(R.layout.activity_main);
        // 1. 找到拨打电话号码按钮
        Button btn_call = (Button) findViewById(R.id.btn_call);
        // 2. 给按钮设置点击事件 因为这个参数 是以借口 所有我搞以实现类
        btn_call.setOnClickListener(new MyButtonListener());
    }
    
    /**
     * 定义一个内部类 目的实现 按钮监听
     * 
     * @author Administrator
     * 
     */
    private class MyButtonListener implements OnClickListener {
        
        // 当按钮被点击的时候调用
        @Override
        public void onClick(View v) {
            // 3. 获取到 我要拨打的号码 首先我要 找到 文本框
            EditText et_number = (EditText) 
findViewById(R.id.et_number);
            String number = 
et_number.getText().toString().trim(); // 获取文本框的内容
            // 判断number 如果号码为空 我弹出一个提示 土司 Toast
            if ("".equals(number)) {
                // context 上下文 duration 显示土司的时长
                Toast.makeText(MainActivity.this, "号码不能为空", 
Toast.LENGTH_LONG).show();
                return;
            }
            System.out.println("number--" + number);
            // 4 拨打此号码 意图 干 一件事的想法 打 狗 猫 打代码 打电话 
Intent
            Intent intent = new Intent();  // 创建意图对象
            // 设置要拨打的动作
            intent.setAction(Intent.ACTION_CALL);
            // 设置拨打电话号码的数据 uri统一资源标示符 范围要比 
url定义范围要广定义的语法规则 比较 url
            // http://www.baidu.com 统一资源定位符
            intent.setData(Uri.parse("tel:" + number));
            // 真正的拨打号码 开启意图对象
            startActivity(intent);
        }
        

    }
    
}
 清单文件AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest 
xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itheima.phonedail"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
<!-- 注意这里的打电话权限 -->
    <uses-permission android:name="android.permission.CALL_PHONE" 
/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itheima.phonedail.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" 
/>
                <category 
android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
查看程序错误信息
 Android程序中如果出错,错误不会显示在Console中,而是显示在LogCa
t界面下。可以从window – show view中打开
 日志信息分为5个级别:verbose > debug > info > warn > error 
高级的包含低级的

 可以创建过滤器对日志进行过滤显示,点击绿色加号,可以按照tag、pid
、level进行筛选
 LogCat不打印日志,如何激活:点击DDMS中的Device或重启adb,实
在不行就重启
,实
在不行就重启Eclipse
将程序安装到真实手机
 在电脑上安装手机驱动。有些手机自带驱动,有些没有,可以从官网下
载。
 在手机设置中打开USB调试,将手机用USB数据线连接到电脑
我的手机是:三星 i9100 。双核1228MHz、1GB RAM 、4GB 
ROM、480×800像素、Android 2.3、4.3英寸
 检查Eclipse的设备管理器中是否显示出新设备。如果未能显示出设备,
检查驱动安装是否正常,USB调试是否打开
 Eclipse安装程序。Eclipse上右键点击工程 – Run as – Android Application 
– 自动安装运行
 手动打包安装。右键点击工程 – Export – Export Android Application – 
选择或创建密钥对程序签名并打包生成apk文件。将apk文件放到手机的SD
卡中,通过手机文件浏览器执行安装。
案例-短信发送

 搭建界面需要组件:TextView、EditText、Button
 给Button添加监听器,当被点击的时候获取号码,获取内容
 使用SmsManager发送短信
 需要注册短信发送权限。android.permission.SEND_SMS
 主要代码
SmsManager smsManager=SmsManager.getDefault();
//一条短信可以发送70个中文汉字,140个英文字符,将短信内容分隔
ArrayList<String> sms= smsManager.divideMessage(s_content);
for(String mes:sms){
smsManager.sendTextMessage(s_num, null,mes,null,null);
}
四大布局
LinearLayout(线性布局)
线性布局:水平、垂直显示,如果有多个组件,超出屏幕大小,超出部分
就不显示,可以通过android:orientation来定义方向。
android:orientation=“horizontal”表示水平方向
android:orientation=“vertical”表示垂直方向
下面通过代码实现一个线性布局。
1. 新建工程,工程名字叫《线性布局》

然后一直执行Next直到Finish即可。项目的目录结构如下图:
2. 编写布局文件activity_main.xml
由于布局文件比较长,因此把该布局文件拆分成了三份。布局文件第一部
分:
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical"
     >
布局文件第二部分:
<LinearLayout 
    android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0sp"
android:layout_weight="4"
    >
    <TextView 
        android:layout_height="match_parent"
        android:layout_width="0sp"
        android:layout_weight="1"
        android:background="#ffffff"
        />
    <TextView 
       android:layout_height="match_parent"
       android:layout_weight="1"
       android:layout_width="0sp"
       android:background="#ffff00"
        />
    <TextView 

        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_width="0sp"
        android:background="#00ff00"
        />
    <TextView 
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_width="0sp"
        android:background="#0000ff"
        />
</LinearLayout>
布局文件第三部分:
<TextView
        android:layout_width="match_parent"
         android:layout_height="0sp"
        android:layout_weight="1"
        android:text="@string/hello_world" 
        android:background="#ff0000"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="0sp"
        android:layout_weight="1"
        android:text="@string/hello_world" 
        android:background="#0000ff"
        />
    <TextView
        android:layout_width="match_parent"
         android:layout_height="0sp"
        android:layout_weight="1"
        android:text="@string/hello_world" 
        android:background="#00ff00"
        />
</LinearLayout>
3. 编写java文件MainActivity.java
该java文件是ADT自动生成的。MainActivity.java
package com.itheima.linearLayout;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
4. 将该项目运行在模拟器上
TableLayout(表格布局)
1.
Tablelayout实现边框
默认的是没有边框的 实现边框 可以通过不同的背景颜色去实现
<?xml version="1.0" encoding="utf-8"?>
<TableLayout android:layout_width="wrap_content" 
xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_height="wrap_content"
     android:stretchColumns="*" android:background="#ff0000">
     <TableRow android:background="#00ff00" 
android:layout_margin="2dip">
      <Button android:id="@+id/button" android:text="+" 
android:background="#0000ff" android:layout_margin="2dip"/>
      <TextView android:text="wahah"  
android:background="#0000ff" android:layout_margin="2dip"/>
      <TextView android:id="@+id/amount"  
android:background="#0000ff" android:layout_margin="2dip"/>
 </TableRow>
 </TableLayout>

2.
Tablelayout常用属性

android:stretchColumns="1"是设置 TableLayout所有行的第二列为扩展列。
Id从0开始,1代表第二列。也就是说如果每行都有三列的话,剩余的空间
由第二列补齐   

collapseColumns – 设置隐藏那些列,列ID从0开始,多个列的话用”,”分隔。

stretchColumns – 
设置自动伸展那些列,列ID从0开始,多个列的话用”,”分隔。

shrinkColumns -
设置自动收缩那些列,列ID从0开始,多个列的话用”,”分隔。可以用”*”来
表示所有列,同一列可以同时设置为shrinkable和stretchable。
FrameLayout(帧布局)
框架布局是将控件组织在Android程序的用户界面中最简单的布局类型之一
。框架布局在xml文件中使用<FrameLayout>来定义。框架布局中的子视图总是
被绘制到相对于屏幕的左上角上,所有添加到这个布局中的视图都是以层叠的
方式显示,第一个添加到框架布局中的视图显示在最底层,最后一个被放在最
顶层,上一层的视图会覆盖下一层的视图,类似于html中的div。
帧布局的运行效果图:
帧布局的布局文件activity_main.xml
布局文件第一部分:
<FrameLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
布局文件第二部分:
<TextView
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:background="#ff0000"
        android:layout_gravity="center"
        />
    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="#00ff00"
        android:layout_gravity="center"
        />
    <TextView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:background="#0000ff"
        android:layout_gravity="center"
        />
    <TextView
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:background="#aabbcc"
        android:layout_gravity="center"
        />
    <TextView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:background="#ffff00"
        android:layout_gravity="center"
        />
    <TextView
        android:id="@+id/tv_6"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:background="#000000"
        android:layout_gravity="center"
        />
</FrameLayout>

RelativeLayout(相对布局)
相对布局是实际布局中最常用的布局方式之一。相对布局在xml文件中使用
<RelativeLayout>来定义。相对布局可以设置某一个视图相对于其他视图的位置
,这些位置可以包括上下左右等,因而相较于其他的布局方式而言具有很大的
灵活性。
下面通过代码实现一个相对布局。创建工程步骤跟线性布局一样,因此直
接给出布局文件盒运行效果。运行效果图如下所示:
相对布局布局文件activity_main.xml。布局文件第一部分:
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" 
    android:id="@+id/rl"
    >
    <Button 
        android:id="@+id/bt_center"
        android:layout_centerInParent="true"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:text="居中"
        />

    <Button 
        android:id="@+id/bt_zn"
        android:layout_below="@id/bt_center"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_centerHorizontal="true"
        android:text="正南"
        />
    <Button 
        android:id="@+id/bt_zb"
        android:layout_above="@id/bt_center"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_centerHorizontal="true"
        android:text="正北"
        />
布局文件第二部分:
<Button 
        android:id="@+id/bt_zx"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_toLeftOf="@id/bt_center"
        android:layout_centerVertical="true"
        android:text="正西"
        />
    <Button 
        android:id="@+id/bt_zd"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_toRightOf="@id/bt_center"
        android:layout_centerVertical="true"
        android:text="正东"
        />
    <Button 
        android:id="@+id/bt_db"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignRight="@id/bt_zd"
        android:layout_alignTop="@id/bt_zb"
        android:text="东北"
        />
    <Button 
        android:id="@+id/bt_dn"
        android:layout_width="60dp"

        android:layout_height="60dp"
        android:layout_alignRight="@id/bt_zd"
        android:layout_alignTop="@id/bt_zn"
        android:text="东南"
        />
布局文件第三部分:
<Button 
        android:id="@+id/bt_xn"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignRight="@id/bt_zx"
        android:layout_alignTop="@id/bt_zn"
        android:text="西南"
        />
    <Button 
        android:id="@+id/bt_xb"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignRight="@id/bt_zx"
        android:layout_alignTop="@id/bt_zb"
        android:text="西北"
        />
</RelativeLayout>

在相对布局内的组件可以使用以下属性:
ParentLeft:true;父窗体左边
ParentBottom:true;父窗体下边
android:layout_centerHorizontal="true" 使组件能够水平居中
android:layout_centerVertical="true"  使组件能够垂直居中
layout_below:指定某个组件,位于此组件的下方。
AbsoluteLayout绝对布局
绝对布局的每一个控件都会有坐标位置:
android:layout_x="97dp"
android:layout_y="92dp"
使用绝对布局的程序,需要对每种手机的分辨率做相应的调整。QQ游戏大
厅就是使用绝对布局,他就有各种分辨率的版本。
800*400 的apk  854*400 的apk

Android下的单位
dip
缩写:dp
一个基于density(密度)的抽象单位,这个和设备硬件有关,通常在开发中设
置一些view的宽高推荐用这个,一般情况下,在不同分辨率,都不会有缩放的
感觉。在运行时, 
Android根据使用中的屏幕的实际密度, 透明地处理任何所需dip单位的缩放。不
依赖设备像素,依据设备自动适应大小,推荐使用。
sp
同dip/dp相似,会根据用户的字体大小偏好来缩放,专门用于设置字体的大
小。
px
像素,是屏幕的物理像素点,与密度相关,密度大了,单位面积上的px会
比较多。在不同分辨率下会有不同的效果,通常不推荐使用这个
dp和px的区别
首先明确一点,HVGA屏density=160;QVGA屏density=120;WVGA屏den
sity=240;WQVGA屏density=120。
density值表示每英寸有多少个显示点,与分辨率是两个概念。dip到px的转
换公式: px = dip * (density / 160)。
Android官方定义dip等价于160dpi屏幕下的一个物理像素点, 
即1dip=1px。举例来说, 在 240 dpi 的屏幕上, 1dip 等于 1.5px。
不同density下屏幕分辨率信息,以480dip*800dip的 
WVGA(density=240)为例:

当density=120时屏幕实际分辨率为240px*400px 
(两个点对应一个分辨率)状态栏和标题栏高为19px或者25dip。
横屏时屏幕宽度为400px或者800dip,工作区域高度211px或者455dip;
竖屏时屏幕宽度为240px或者480dip,工作区域高度381px或者775dip。

当density=160时屏幕实际分辨率为320px*533px 
(3个点对应两个分辨率)状态栏和标题栏高为25px或者25dip。
横屏是屏幕宽度533px 或者800dip,工作区域高度295px或者455dip;
竖屏时屏幕宽度320px或者480dip,工作区域高度508px或者775dip。


当density=240时屏幕实际分辨率为480px*800px 
(一个点对于一个分辨率)状态栏和标题栏高为38px或者25dip。
横屏是屏幕宽度800px 或者800dip,工作区域高度442px或者455dip;
竖屏时屏幕宽度480px或者480dip,工作区域高度762px或者775dip。
 
在Android的应用包apk中,系统会根据各个设备的具体情况引用相应的资源文
件(注:不加任何标签的资源是各种分辨率情况下共用的):
当屏幕density=240时,使用hdpi标签的资源;
当屏幕density=160时,使用mdpi标签的资源;
当屏幕density=120时,使用ldpi标签的资源。
下面是在manifest中设置app在不同分辨率时,是否支持多密度的方法。
<?xml version="1.0" encoding="utf-8"?>
<manifest 
xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itheima.FrameLayout"
    android:versionCode="1"
android:versionName="1.0" >
--------
<supports-screens
     android:smallScreens="true"
     android:normalScreens="true"
     android:largeScreens="true"
     android:xlargeScreens="true"
     android:anyDensity="true" />
-------
</manifest>
下面是dp与px换算的工具类:
package com.itheima.screenDesity;
import android.content.Context;
public class DensityUtil {
public static int dip2px(Context context, float dipValue) {
final float scale = 
context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue) {
final float scale = 
context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}

}
RGB
颜色:window里是bgr、android里是rgb。有关RGB三色空间我想大家都很
熟悉,这里我想说的是在Windows下,RGB颜色阵列存储的格式其实BGR。所以
window里的颜色是FF0202,那么android里就是0202FF
Android点击事件的四种写法
Android中获取到按钮后,我们一般会为其添加点击事件,而android中的点
击事件共有四种。
通过匿名内部类来实现,代码由电话拨号器项目改编:
btn_call.setOnClickListener(new OnClickListener()
{
    
    @Override
    public void onClick(View v) {
        EditText et_number = (EditText) 
findViewById(R.id.et_number);
        String number = et_number.getText().toString().trim(); 
// 获取文本框的内容
        if ("".equals(number)) {
            // context 上下文 duration 显示土司的时长
            Toast.makeText(MainActivity.this, "号码不能为空", 
Toast.LENGTH_LONG).show();
            return;
        }
        Intent intent = new Intent();  // 创建意图对象
        intent.setAction(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + number));
        startActivity(intent);
    }
});
 二、通过内部类来实现
其实第二种方法跟第一种方法在本质上没有任何差别,虽然一个是匿名内
部类另外一个是内部类,但是这只是写法上的差别,两者都是通过Button对象
的setOnClickListener()方法来绑定实现的。
代码摘抄自电话拨号器项目:
    /**
     * 定义一个内部类 目的实现 按钮监听
     * 
     * @author Administrator
     * 

     */
    private class MyButtonListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            EditText et_number = (EditText) 
findViewById(R.id.et_number);
            String number = 
et_number.getText().toString().trim(); 
// 获取文本框的内容
            if ("".equals(number)) {
                Toast.makeText(MainActivity.this, "号码不能为空", 
Toast.LENGTH_LONG).show();
                return;
            }
            System.out.println("number--" + number);
            Intent intent = new Intent();  
// 创建意图对象
            intent.setAction(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + number));
            startActivity(intent);
        }
    }
三、由类文件去实现监听接口
代码如下:
//第一步:Activity实现OnClickListener接口
public class SecondActivity extends Activity implements 
OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
//第二步:得到button,并且设置点击监听为:this
        Button btnCall = (Button) findViewById(R.id.btn_call);
        btnCall.setOnClickListener(this);
}
//第三步:重写OnClickListener接口的onClick方法
    @Override
public void onClick(View v) {
//根据v的id来区分点击的是哪个按钮
        switch (v.getId()) {
            case R.id.btn_call:
                    //DoSomething
            break;
        }
黑马Android课程笔记       
就业服务部出品
    }
}
 四、在布局文件中注册事件
1.
在布局文件中添加android:onClick 属性
<Button 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="点击我"
    android:onClick="btnCall"/>
2.
在相应的java代码中定义call方法
该方法的形参必须为View对象,且只能有一个。修饰符必须是Public
    public void btnCall(View view) {
        Toast.makeText(getApplicationContext(), 
                "点击了我", Toast.LENGTH_SHORT).show();
    }
结合工作和面试

查看程序错误信息
这个比较重要,有些Android断点调试比较麻烦,需要依据错误信息来
定位错误。

将程序安装到真实手机
这个会把手机连上Eclipse,会发布应用到手机上即可。
会把电脑上的apk安装到手机里,可通过手机助手,也可以通过adb命令
安装。

四大布局
比较重要的是线形布局,和相对布局。帧布局也会用到,其他的不常用


Android下的单位
了解dp、sp是依据手机屏幕分辨率改变的,自动适应屏幕。px依赖像素
不会自动屏幕适配。

四种点击事件的写法
这个在工作中用的非常多,需要掌握。但是具体用哪一种,看公司编码
风格。

四大布局
在笔试中常考,面试问的不算多,比较基础。

屏幕适配  后期会具体讲解,到时候大家在自己总结
这个是面试常见问题:

在manifest里定义你的程序支持的屏幕类型
美工切多套图、定义多套layout、9path图片,代码中不要出现具体的像
素值

四种点击事件,笔试面试有可能问,但是不多,也比较基础




--------------------源自培训笔记--------------------

0 0
原创粉丝点击