目的
這裏主要開始接觸android的基本功能
(1)Intent:
Intent(意圖)主要是解決Android應用的各項組件之間的通訊。
Intent負責對應用中一次操作的動作、動作涉及數據、附加數據進行描述,Android則根據此Intent的描述,負責找到對應的組件,將 Intent傳遞給調用的組件,並完成組件的調用。
因此,Intent在這裏起着一個媒體中介的作用,專門提供組件互相調用的相關信息,實現調用者與被調用者之間的解耦。
(2)setOnClickListener方法功能:建立監聽機制,告訴我們有監聽
(3)OnClickListener()方法功能:如果監聽到了消息,我們應該採取的行動寫在該函數中
源代碼(有註釋)
(1)MainActivity
package com.myapplication;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);//得到buton的id
button.setOnClickListener(new View.OnClickListener(){//建立監聽機制
public void onClick(View v){//實現點擊button以後的功能
Intent i = new Intent();//intent實現通信
i.setAction("android.media.action.IMAGE_CAPTURE");//打開相機,指定action
i.addCategory("android.intent.category.DEFAULT");
startActivity(i);//尋找最合適的組件,激活
}
});
}
}
(2)對應的xml文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.myapplication.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!--button按鈕,點擊button打開照相機-->
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打開系統照相機"
tools:layout_editor_absoluteX="116dp"
tools:layout_editor_absoluteY="101dp" />
</android.support.constraint.ConstraintLayout>