Android

2017-12-12  本文已影响0人  映雪复习手册

PS:这里的东西肯定会有些遗漏,不知道你掌握程度怎么样,有些我认为你理所应当懂的就一笔带过了,所以如果你发现了,及时告诉我哈。

1、Bitmap分类(要打印)

1.1 BPM

优点:simple and direct operation,原图,原始数据,最真实的图片
缺点:memory consumption
适用场景:photo,单反(For professional digital photographers,preserve an image’s fidelity.Preferred to a digital negative by many photographers, who feel it preserves the subtle color and details possible.Can adjust brightness,contrast,sharpen, white balance and can apply noise reduction, sensor dust removal

1.2 S-RAW and M-RAW

试用场景:wedding photographers、sports/action photographers(suitable for wedding photographers who don’t need full resolution for wedding candidates, but who do want the post- production control that RAW offers. Could also be used by sports/action photographers who will get an increase in the number of frames when shooting in bursts due to using a smaller file size)

1.3 GIF

适用场景:graphics such as cartoon, line art,
不适用于:Not good for photos(Max 256 color i.e. 8 bits per pixel, need color table ,some colors may be missing for photos)

1.4 PNG

不支持动画

1.5 JPEG

适用场景:(natural image and photo)Good for natural image and photo ,lots of color levels and removing some of them cannot be easily noticed.For 640x480 24-bit image, need 900 kB,JPEG may become 30 kB
不适用:art line
优点:Smaller file sizes (more images can be stored)、Images are easy to view, mail and print than RAW files
缺点:Reduced post-processing flexibility、Reduced color depth and resolution、Need to get everything correct in-camera (only limited computer processing is possible)


2、Java基础(理解即可,不需要背)

2.1 main 方法

Java程序的入口,每个Java程序有且仅有一个main函数,程序运行时,系统会执行main函数,入口函数!

public class Sample1 {
  public static void main(String[] args) {
      System.out.println("Welcome to COMP7506!");
  }
}

2.2 变量(variable)声明

int a = 1; 
// Primitive 类型:int、float、double、boolean、char
People hyx = new People("Huang YingXue", 21);
// Reference 类型:所有的类,包括String、Button、ImageView都是Reference类型

2.4 类(Class)和对象(Objec/Instance)(要打印)

public class People {
    // 属性
    String name;
    int age;

    // 构造方法
    public People(String name, int age) {
      this.name = name;
      this.age = age;
    }

    public void setName(String name) {
      this.name = name;
    }

    public int getAge() {
      return this.age;
    }
    
    public void eat() {
      // People eat  
    }
}
// People 是类,hyx 是People类的一个对象,通过new创建了这个对象
People hyx = new People("Huang YingXue", 22); 

// 下面可以通过对象调用方法
hyx.setName("HYX");
int age = hyx.getAge();
hyx.eat();

2.5 static 变量

public class Friend {
  String name;
  static int count;
  
  public void addFriend() {
    count++;
  }
}
// 上面Friend类里,name是普通属性,count是成员属性
Friend.count = 0; // static 属性可以直接通过 Friend类名访问

// 而普通属性必须通过对象名访问
Friend mxm = new Friend();
mxm.name;

// static 属性是独立于对象的,所以我就算通过不同的对象调用addFriend(),都会导致count增加,看下面
Friend mxm = new Friend();
Friend hyx = new Friend();
mxm.addFriend();
hyx.addFriend();
// 完了之后,count变成了2

2.6 面向对象编程(OOP)的优点

(1)Simplicity(2)Modularity(3)Modifiability(4)Extensibility(5)Maintainability(6)Re-usability

2.7 for 和 while 循环

    for (int i = 0; i < 100; i++) {
      // Do something
    }

    // 先判断条件是否满足,再执行 // Do something处的代码
    int count = 0;
    while (count < 100) {
      // Do something
      count++;
    }

    // 先执行do中的代码,再判断条件是否满足
    int num = 0;
    do {
      // Do something
      num++;
    } while (num < 100);

    // 选择器,一定要写break,不然如果进了case 0,没有break,会接着执行到case 1
    int type = 1;
    switch (type) {
      case 0:
        // Do something
        break;
      case 1:
        // Do something
        break;
      case 2:
        // Do something
        break;
      default:
        // Do something
        break;
    }

2.9 数组和ArrayList(代码要打印)

2.12 其它

(1)Integer.parseInt("1");

String num = "11";
int a = Integer.parseInt(num); // 把字符串“11”转换成整数11
String num = "6.666";
double a = Double.parseDouble(num);

(2)toString() (getText().toString()

TextView tv = findViewById(R.id.tv);
String str = tv.getText().toString();

(3)String.valueOf(int) / String.valueOf(float)

int r = 0;
TextView tv; 
tv.setText(String.valueOf(r));

(4)字符串拼接

// sample 1
String str1 = "Huang";
String str2 = " YingXue";
String name = str1 + str2; // Huang YingXue
//也可以这样写,一样的结果
String name = "Huang" + " YingXue";

// sample 2(结合String.valueOf使用)
int r1 = 1;
int r2 = 2;
TextView tv;
tv.setText(String.valueOf(r1) + “ “ + String.valueOf(r2)); // 得到结果"12"

(5)Random 随机数

Random myRandom = new Random();
myRandom.nextDouble(); // 生成[0.0, 1.0)的随机double数
myRandom.nextFloat(); // 生成[0.0, 1.0)的随机float数
myRandom.nextInt(); //随机生成一个整数
myRandom.nextInt(int n); //生成[0, n)的随机整数

3、Android 基础

3.1 概念

(1)OHA:A business alliance consisting of 47 companies to develop open standards for mobile devices
(2)Android 2017 Q1 市场占有率:85%,iOS 2017 Q1 市场占有率:14.7%
(3)2017 Q1 智能手机市场占有率:三星23.3%、Apple14.7%、华为10%、OPPO7.5%、vivo5.5%
(4)Android分层结构(要打印)

3.2 AndroidManifest.xml 配置文件

AndroidManifest.xml

AndroidManifest.xml的重要属性:(要打印)
(1)user-permission:表示APP需要的权限,如INTERNET(网络访问权限)
(2)package:表示APP 的 package name
(3)icon:设置 APP 的图标
(4)activity:配置该 APP 需要展示的所有 activity

3.3 资源文件(res文件夹下)

3.4 如何新建 Android Studio project

3.5 Activity 和 Layout file

(1)设置 Activity 要显示的 Layout file

setContentView(R.layout.activity_main);

(2)xml 中 的 include 属性:记住我卷子上给你讲过的例子,include等于把被include的文件里的代码插入到这个地方

(3)也可以直接把某个 View 直接 设置给 Activity 显示,如下:

LinearLayout layout = new LinearLayout(this);
setContentView(layout);

(4)在 Activity 中获得 Layout file 中某个控件的对象引用

Button btn1 = (Button)findViewById(R.id.btn1);

(5)设置Click Listener,两种方法:

Button btn = findViewById(R.id.btnStart);
    btn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        // Do Something
      }
    });
// 先在布局文件中 activity_main.xml 这么写
<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="OpenWindow"
        android:text="Start"/>

// 然后在对应的Activity里写上OpenWindow这个方法,如下:
public void OpenWindow(View v) {
    // Do something
}

3.6 Activity 生命周期(要打印)

Activity 生命周期

3.7 Activity 之间的跳转

ActivityA.java

Button btn = findViewById(R.id.btnStart);
    btn.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        // 在这里跳转到 ActivityB

        Intent intent = new Intent(ActivityA.this,ActicityB.class);
        // 把99传递给 ActivityB,key是“X”,在 ActivityB 中可以通过 “X”取到这个值
        intent.putExtra("X",99);
        startActivity(intent);
      }
 });

ActivityB

// 接受 ActivityA 传递过来的数据
Intent intent = getIntent();
int num = intent.getIntExtra("X",0); // 取到99,然后赋值给num,0是说如果没取到任何值,就把0赋给num,默认值。

4、布局系统

4.1 容器(Container/ViewGroup)

4.1.1 LinearLayout

(1)orientation:houriziontal、vertical

4.1.2 RelativeLayout

(1)第一类:描述该控件相对父容器的四个边缘的位置(属性值为true或false)
android:layout_alignParentBottom 贴紧父元素的下边缘
android:layout_alignParentLeft 贴紧父元素的左边缘
android:layout_alignParentRight 贴紧父元素的右边缘
android:layout_alignParentTop 贴紧父元素的上边缘

(2)第二类:描述该控件相对父容器居中的方向(属性值为true或false)
android:layout_centerHrizontal 水平居中
android:layout_centerVertical 垂直居中
android:layout_centerInparent 相对于父元素完全居中
(3)第三类:描述该控件相对同级元素的外切位置(属性值必须为id的引用名“@id/id-name”)
android:layout_below 在某元素的下方
android:layout_above 在某元素的的上方
android:layout_toLeftOf 在某元素的左边
android:layout_toRightOf 在某元素的右边

(4)第四类:描述该控件相对同级元素的内切位置(属性值必须为id的引用名“@id/id-name”)
android:layout_alignTop 本元素的上边缘和某元素的的上边缘对齐
android:layout_alignLeft 本元素的左边缘和某元素的的左边缘对齐
android:layout_alignBottom 本元素的下边缘和某元素的的下边缘对齐
android:layout_alignRight 本元素的右边缘和某元素的的右边缘对齐

4.1.3 FrameLayout

上次给你讲了的,按顺序往FrameLayout中绘制元素,写在后面的元素,覆盖在最上面,默认对齐左上角。
记不得可以问我。

4.1.4 TableLayout

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/re s/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_height="match_parent"
             android:layout_width="match_parent">

    <TableRow>
        <Button
            android:id="@+id/backbutton"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Back"/>
    </TableRow>

    <TableRow>
        <TextView
            android:layout_column="1"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="First Name"/>

        <EditText
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:width="500px"/>
    </TableRow>

    <TableRow>
        <TextView
            android:layout_column="1"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="Last Name"/>

        <EditText
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:width="500px"/>
    </TableRow>
</TableLayout>

4.1.5 ScrollView

当内容太长了放不下可滚动查看ScrollView里的内容

4.1.6 ConstraintLayout

类似 RelativeLayout:
(1)第一类属性: layout_constraintLeft_toRightOf

<Button 
    android:id="@+id/buttonA" ... />
<Button 
    android:id="@+id/buttonB" ...
    app:layout_constraintLeft_toRightOf="@+id/buttonA" />

表示B的左边缘贴着A的右边缘:


image.png

(在水平布局中,Start就是Left,End就是Right)
– layout_constraintLeft_toLeftOf
– layout_constraintLeft_toRightOf
– layout_constraintRight_toLeftOf
– layout_constraintRight_toRightOf
– layout_constraintTop_toTopOf
– layout_constraintTop_toBottomOf
– layout_constraintBottom_toTopOf
– layout_constraintBottom_toBottomOf
– layout_constraintBaseline_toBaselineOf – layout_constraintStart_toEndOf
– layout_constraintStart_toStartOf
– layout_constraintEnd_toStartOf
– layout_constraintEnd_toEndOf

(2)第二类属性
– android:layout_marginStart
– android:layout_marginEnd
– android:layout_marginLeft
– android:layout_marginTop
– android:layout_marginRight – android:layout_marginBottom

4.1.7 ListView(要打印)

<TextView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rowTextView" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" android:padding="10dp"
    android:textSize="16sp" >
</TextView>
public class MainActivity extends AppCompatActivity {
    private ListView mainListView ;
    // 通过一个适配器,往ListView每一项塞数据
    private ArrayAdapter<String> listAdapter ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);

        // 初始化ListView
        mainListView = (ListView) findViewById( R.id.mainListView );

        // 这是每一项需要展示的数据
        String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
        ArrayList<String> planetList = new ArrayList<String>();
        planetList.addAll( Arrays.asList(planets) );

        // 初始化适配器,传入R.layout.simplerow,planetList表示每一项需要显示这个布局,传入planetList告诉适配器每一项要显示什么数据
        listAdapter = new ArrayAdapter<String>(this,R.layout.simplerow, planetList);
        
        // Set the ArrayAdapter as the ListView's adapter.
        mainListView.setAdapter( listAdapter );
   }
}

4.2 控件(View)

4.2.1 Button

4.2.2 TextView

<TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Hello"
            android:textSize="19sp"/>
TextView tv = findViewById(R.id.tv);
tv.setText("Hello World!");

4.2.3 EditText

EditText et = findViewById(R.id.et);
String str = et.getText().toString();

4.2.4 ImageView

<ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/ic_launcher_background"/>
ImageView image = findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher_background);

4.2.5 RadioGroup、RadioButton

image.png
<RadioGroup 
    android:id="@+id/radioGroup" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content">
    <RadioButton 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"   
        android:text="男" 
        android:checked="true">
    </RadioButton>
    <RadioButton 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="女">
    </RadioButton>    
</RadioGroup>

// 第一个RadioButton 中的 checked="true" 表示第一次打开页面时,这个项目是被选中的

        RadioGroup group = (RadioGroup)this.findViewById(R.id.radioGroup);
         // 绑定一个监听器,当单选框的任何一个项目(男或女)被选择时,onCheckedChanged里的代码都会被执行,
        group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
             @Override
             public void onCheckedChanged(RadioGroup arg0, int arg1) {
                 // 如果选中单选框的“男”
                 int radioButtonId = arg0.getCheckedRadioButtonId();
                 RadioButton rb = (RadioButton)MyActiviy.this.findViewById(radioButtonId);
                 String sex = rb.getText());
             }
         });

4.3 通用属性

(1)width、height、layout_width、layout_height:

(3)margin(外边距):表示自身的位置偏移

(4)padding(内边距):用于指定容器内部元素距离容器边框的距离

(5)gravity = center:如果写在普通控件上,表示该控件在父容器里是居中的,如果写在TextView上,表示文字内容在TextView是居中的

(6)layout_gravity = center:不同于gravity ,layout_gravity 是作用于容器,表示该容器中所有的子元素都是居中排列的

(7)gravity和layout_gravity还有两个值:centerHouriziontal(水平方向居中)、centerVertical(垂直方向居中)

4.4 Dimension 单位说明

(1)px:像素
(2)dp:在屏幕像素密度(dpi)是160的屏幕上,1dp=1px;在320dpi的屏幕上,1dp=2px;也就是说,dp和px是按照160的比例缩放。(这个要记住,可能会给你dpi的数值,让你做dp和px的换算)
(3)sp:和dp类似,但是用于描述文字大小(TextView、EditText中的textSize属性: android:textSize = 16sp


6、Sample Move Image(主要看onClick方法内部的代码)

public class MainActivity extends AppCompatActivity {

  ImageView img;
  Button btnMoveLeft;
  Button btnMoveRight;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    img = findViewById(R.id.img);
    btnMoveLeft = findViewById(R.id.btnMoveLeft);
    btnMoveRight = findViewById(R.id.btnMoveRight);

    btnMoveLeft.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int screen_width = size.x;
        int screen_height = size.y;

        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) img.getLayoutParams();
        if (lp.leftMargin - 5 > 0) {
          lp.leftMargin -= 5;
          img.setLayoutParams(lp);
        }
      }
    });

    btnMoveRight.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int screen_width = size.x;
        int screen_height = size.y;

        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) img.getLayoutParams();
        if (lp.leftMargin + 5 > screen_width - lp.width) {
          lp.leftMargin += 5;
          img.setLayoutParams(lp);
        }
      }
    });
  }
}

7、Sample Dragging Image(主要理解Touch事件的类型、Down、Moce和Cancel)

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ImageView image = findViewById(R.id.img);

    final RelativeLayout.LayoutParams par
            = (RelativeLayout.LayoutParams) image.getLayoutParams();

    image.setOnTouchListener(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
          case MotionEvent.ACTION_DOWN:
            break;

          case MotionEvent.ACTION_MOVE:
            int x_cord = (int) event.getRawX();
            int y_cord = (int) event.getRawY();
            par.leftMargin = x_cord - par.width / 2;
            par.topMargin = y_cord - par.height / 2;
            image.setLayoutParams(par);
            break;

          case MotionEvent.ACTION_CANCEL:
            break;
        }
        return true;
      }
    });
  }
}

8、Playing Background Music(要打印,包括步骤)

(1)Create folder “res/raw” on your project
(2)Place xxx.mp3 into “res/raw”
(3)然后代码如下:

Button btnStart;
Button btnPause;
Button btnStop;

MediaPlayer mediaPlayer;
mediaPlayer = MediaPlayer.create(this, R.raw.xxx);

btnStart.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          if (!mediaPlayer.isPlaying())
          mediaPlayer.start(); 
      }
});

// btnPause(监听器我就省略不写了)
if (mediaPlayer.isPlaying())
    mediaPlayer.pause();

// btnStop
if (mediaPlayer.isPlaying())
    mediaPlayer.stop();

9、Vibration

(1)需要在AndroidManifest.xml配置权限(要打印)

<uses-permission android:name="android.permission.VIBRATE"/>

(2)震动 1000 毫秒

Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(1000);

(3)按规律震动

long[] pattern = { 100, 200, 500,100,200 }; // 等待100,震动200,等待500,震动100,等待200
v.vibrate(pattern, -1);// -1 代表不重复震动
v.vibrate(pattern, 0); // 0代表重复震动

(4)取消震动

v.cancel();

10、Network communications(要打印)

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
public class MainActivity extends AppCompatActivity {

  private TextView textView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // 需要访问的URL
    String stringUrl = "http://www.hku.hk/";
    // 获取网络连接和网络信息
    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    // 判断网络是否可用
    if (networkInfo != null && networkInfo.isConnected()) {
      new DownloadWebpageTask().execute(stringUrl);
    } else {
      // 表示网络不可用
      textView.setText("No network connection available.");
    }
  }

  // 需要定义一个执行网络访问任务的类
  private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
      try {
        // 调用下载网络内容的方法,返回下载的内容
        return downloadUrl(urls[0]);
      } catch (IOException e) {
        // 如果下载失败,会执行到这里
        return "Unable to retrieve web page. URL may be invalid.";
      }
    }

    @Override
    protected void onPostExecute(String result) {
      // 下载网页内容成功,显示在textView上
      textView.setText(result);
    }
  }

  // 下载网页内容,传入的参数就是网址URL
  private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    try {
      // 连接网络并下载网页内容,中间代码不用理解,抄下来就好
      URL url = new URL(myurl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000);
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("GET");
      conn.setDoInput(true);
      conn.connect();
      is = conn.getInputStream();
      String contentAsString = readIt(is, len);
      return contentAsString;
    } finally {
    }
  }
}

11、Timer function

public class MainActivity extends AppCompatActivity { 
    Long startTime;
    Long duration = new Long(1800000);
    Handler handler = new Handler();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView time = (TextView) findViewById(R.id.timer); 
        startTime = System.currentTimeMillis();
        handler.postDelayed(updateTimer, 1000);
    }
    
    private Runnable updateTimer = new Runnable() {
        public void run() {
            Long spentTime = System.currentTimeMillis() - startTime; 
            Long remainTime = duration - spentTime;
            Long minutes = (remainTime / 1000) / 60;
            Long seconds = (remainTime / 1000) % 60; 
            time.setText(minutes + ":" + seconds); 

            if (remainTime > 0) {
                handler.postDelayed(this, 1000);
            }

            if (remainTime == 0) {
                Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                v.vibrate(10000); 
            }
    } };
}
上一篇下一篇

猜你喜欢

热点阅读