Android Activity詳解

一、Activity概述

Activity,實現程序的交互。

Activity,代表手機或平板中的一屏。

Activity的4種狀態:
在這裏插入圖片描述
Activity的生命週期:
在這裏插入圖片描述
更正:OnRestart應該接到Onstart方法。

二、創建、啓動和關閉Activity

1、創建Activity

  1. 創建繼承自Activity的Activity
  2. 重寫需要的回調方法
  3. 設置要顯示的視圖
//extends Activity,即步驟一
public class DetailActivity extends Activity {
    //onCreate(),即步驟二
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView,即步驟三
        setContentView(R.layout.activity_main);
    }
}

創建了Activity後需要配置才能使用。即要在Manifests中添加此acitivity

<activity  android:name=".DetailActivity" > </activity>
//在配置name屬性時,如果配置的Activity與上面的包路徑一樣,直接.類名
//如果是在上面包的子包中,則.子包序列加上類名

android提供的創建Activity的嚮導,步驟簡單
要在某個包中創建Acitivity,則單擊鼠標右鍵,選擇“New”→“Activity”→“Empty Activity”→"Finish",則完成了Activity的創建,並自動創建了佈局文件,並進行了配置。

2、啓動和關閉Activity

當創建和配置一個Activity後,它不會自動顯示在屏幕上,需要我們啓動它。

要啓動Activity,分成兩種情況:

  1. 入口Activity
  2. 其他Activity
① 入口Activity

要在AndroidManifest.xml中進行配置。

        <activity android:name=".MainActivity">
            <!--通過下面4句代碼,可把該Acitivity配置成程序的入口-->
            <!--下面4句代碼,是用來配置intent過濾器的。-->
            <intent-filter>
                <!--action標記:指定響應的動作名,這條代碼把一個activity指定爲程序的主體動向-->
                <action android:name="android.intent.action.MAIN" />
                <!--category標記:指定在什麼環境下,動作會響應。這條代碼可把某個Activity作爲應用程序的啓動項-->
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Activity需要通過Intent來表達自己的意圖。

② 其他Activity

需要startActivity()方法來啓動

例子:

	//單擊按鈕後,啓動另一個Activity
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //此處不能使用this,因爲此處使用了匿名內部類,若用this就會指向匿名內部類對象了。
                Intent intent=new Intent(MainActivity.this,DetailActivity.class);
                startActivity(intent);
            }
        });

關閉Activity
使用finish()方法。

如果通過finish方法關閉的不是主活動,則執行關閉後就會回到調用它的Activity中,否則回到主界面中。

刷新當前的Activity
調用下列代碼

onCreate(null);

三、啓動和關閉Activity實例——模擬喜馬拉雅忘記密碼頁面跳轉功能。

Intent intent =new Intent(MainActivity.this,另一個活動的名.class)

效果如下:
點擊忘記密碼,跳轉至圖二;點擊×,跳轉至圖一

圖一
圖二

activity_main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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="com.mingrisoft.forgetpassword.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"
        android:gravity="center_horizontal"
        android:textSize="25sp"
        android:text="登錄" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/q2"/>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="25dp">
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="top"
                android:layout_marginLeft="10dp"
                android:textSize="20sp"
                android:text="賬號"
                 />

            <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:hint="郵箱或手機號"
                />
        </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="25dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top"
            android:layout_marginLeft="10dp"
            android:textSize="20sp"
            android:text="密碼"
            />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:hint="輸入6~16位數字或字母"
            />
    </TableRow>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="25dp">
        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:text="註冊"
            />

        <Button
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp"
            android:text="登錄"
            android:background="#f4b144"
            />
    </TableRow>

    <TextView
        android:text="忘記密碼?"
        android:gravity="right"
        android:layout_margin="10dp"
        android:id="@+id/forget"/>
</TableLayout>

MainActivity.java文件

package com.mingrisoft.forgetpassword;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //使該佈局文件就會跟這個activity綁定在一起
        setContentView(R.layout.activity_main);
        TextView textView= (TextView) findViewById(R.id.forget);
        //設置文本框單擊事件監聽器
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Intent表意圖
                Intent intent=new Intent(MainActivity.this,PassWord.class);
                //啓動另一個Activity
                startActivity(intent);
            }
        });
    }
}

activity_password.xml文件

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="10dp"
    >

    <TableRow>
        <ImageButton
            android:id="@+id/close"
            android:layout_width="15dp"
            android:layout_height="15dp"
            android:scaleType="centerCrop"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="120dp"
            android:src="@drawable/close2"
            android:background="#0000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal"
            android:text="找回密碼"
            android:textColor="#161615"
            android:textSize="15sp"
            />
    </TableRow>

    <TextView
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="你的郵箱或手機號"/>

    <EditText
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="請輸入郵箱或手機號"/>

    <Button
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="提交"
        android:background="#ec9640"/>
</TableLayout>

PassWord.java文件

package com.mingrisoft.forgetpassword;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;

/**
 * Created by Asus on 2020/2/13.
 */
public class PassWord extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_password);
        ImageButton imageButton= (ImageButton) findViewById(R.id.close);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //返回上一界面
                finish();
            }
        });
    }
}

不要忘了manifests哦!

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mingrisoft.forgetpassword">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".PassWord"></activity>
    </application>

</manifest>

四、使用Bundle在Activity之間交換數據

什麼是Bundle?
Bundle可以理解爲鍵值對的組合,讀取時通過key找到value值。
在這裏插入圖片描述

在Android中,我們把數據存放在Bundle當中,把要攜帶的數據保存到Intent中,再啓動Activity。流程圖如下:
在這裏插入圖片描述

實例:模擬淘寶的填寫並顯示收穫地址的功能。

效果如下:
在這裏插入圖片描述

在這裏插入圖片描述

activity_main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:layout_margin="10dp"
    tools:context="com.mingrisoft.taobaoadress.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:text="收貨地址管理" />

    <EditText
        android:id="@+id/et_site1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:hint="請輸入所在地區"
        android:layout_weight="1" />

    <EditText
        android:id="@+id/et_site2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:hint="請輸入街道"
        android:layout_weight="1" />

    <EditText
        android:id="@+id/et_site3"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:hint="請輸入詳細地址"
        android:layout_weight="1" />

    <EditText
        android:id="@+id/et_site4"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:hint="請輸入收件人姓名"
        android:layout_weight="1" />

    <EditText
        android:id="@+id/et_site5"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:hint="請輸入收件人聯繫電話"
        android:layout_weight="1" />

    <EditText
        android:id="@+id/et_site6"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:hint="請輸入郵箱"
        android:layout_weight="1" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_gravity="right"
        android:layout_marginTop="30dp"
        android:text="保存"
        android:background="#f1a945"
        android:layout_weight="1" />
</LinearLayout>

MainActivity.java文件

package com.mingrisoft.taobaoadress;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //獲取保存按鈕
        Button button= (Button) findViewById(R.id.button);
        //設置單擊事件監聽器
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //獲取數據
                String site1=((EditText)findViewById(R.id.et_site1)).getText().toString();
                String site2=((EditText)findViewById(R.id.et_site2)).getText().toString();
                String site3=((EditText)findViewById(R.id.et_site3)).getText().toString();
                String name=((EditText)findViewById(R.id.et_site4)).getText().toString();
                String phone=((EditText)findViewById(R.id.et_site5)).getText().toString();
                String email=((EditText)findViewById(R.id.et_site6)).getText().toString();
                //判斷信息是否填完整
                if(!"".equals(site1)&&!"".equals(phone)&&!"".equals(site3)&&
                        !"".equals(name)&&!"".equals(phone)&&!"".equals(email))
                {
                    //若完整,創建一個Intent對象
                    Intent intent=new Intent(MainActivity.this,ShowAdress.class);
                    //創建一個Bundle對象,將數據放入Bundle中
                    Bundle bundle=new Bundle();
                    bundle.putCharSequence("name",name);
                    bundle.putCharSequence("phone",phone);
                    bundle.putCharSequence("site1",site1);
                    bundle.putCharSequence("site2",site2);
                    bundle.putCharSequence("site3",site3);
                    //將Bundle給intent
                    intent.putExtras(bundle);
                    //啓動另一個活動。
                    startActivity(intent);
                }

                else {
                    Toast.makeText(MainActivity.this, "請將收貨地址填寫完整", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

ShowAdress.xml文件

package com.mingrisoft.taobaoadress;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.widget.TextView;

public class ShowAdress extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_adress);
        //獲取Intent
        Intent intent=getIntent();
        //通過Intent獲取Bundle
        Bundle bundle=intent.getExtras();
        //提取Bundle中的數據
        String name=bundle.getString("name");
        String phone=bundle.getString("phone");
        String site=bundle.getString("site1")+bundle.getString("site2")+bundle.getString("site3");
        //獲取xml中的文本框
        TextView tv_name= (TextView) findViewById(R.id.name);
        TextView tv_phone= (TextView) findViewById(R.id.phone);
        TextView tv_site= (TextView) findViewById(R.id.site);
        //將數據放入文本框中
        tv_name.setText(name);
        tv_phone.setText(phone);
        tv_site.setText(site);
    }
}

activity_showadress.xml文件

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:layout_margin="10dp"
    tools:context="com.mingrisoft.taobaoadress.ShowAdress">

    <TextView
        android:id="@+id/top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:text="收貨地址管理" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:layout_below="@+id/top"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:id="@+id/phone"
        android:layout_below="@+id/top"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/site"
        android:layout_below="@id/name"
        />

</RelativeLayout>

別忘了manifests哦!

五、調用另一個Activity並返回結果

使用startActivityForResult()方法,啓動另一個Activity,在另一個Activity中選擇一些內容之後,關閉新啓動的Activit時,將選擇結果返回到原來的Activity中。

方法的基本格式:

public void startActivityForResult(Intent intent,int requestCode)
//intent用來指定想啓動的Activity,第二個參數爲指定請求碼,標識請求的來源。如0x007。
實例:模擬喜馬拉雅FM選擇頭像功能。

android:horizontalSpacing:用於控制字體之間的水平間距。
效果如下:
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

activity_main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@drawable/timg"
    tools:context="com.mingrisoft.changetou.MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/t1" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_gravity="center_horizontal"
        android:text="選擇頭像"
        />
</LinearLayout>

MainActivity.java文件

package com.mingrisoft.changetou;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends ActionBarActivity {

    @Override
    //活動返回
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0x11&&resultCode==0x11) //如果返回
        {
            //獲取Bundle
            Bundle bundle=data.getExtras();
            //獲取此時頭像
            int imageId=bundle.getInt("imageId");
            //獲取xml中的ImageView
            ImageView imageView= (ImageView) findViewById(R.id.imageView);
            //將數據放入ImageView框中
            imageView.setImageResource(imageId);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button= (Button) findViewById(R.id.btn);
        button.setOnClickListener(new View.OnClickListener() {
                @Override
            public void onClick(View view) {
                Intent intent=new Intent(MainActivity.this,Choose.class);
                    //請求碼爲0x11
                startActivityForResult(intent,0x11);
            }
        });

    }
}

activity_choose.xml文件

<?xml version="1.0" encoding="utf-8"?>
<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="com.mingrisoft.changetou.choose">
    <!-- 網格佈局管理器 -->
    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/gridView"
        android:layout_marginTop="10dp"
        android:horizontalSpacing="3dp"
        android:numColumns="4"
        ></GridView>

</RelativeLayout>

Choose.java文件

package com.mingrisoft.changetou;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class Choose extends ActionBarActivity {

    public int imageId[]=new int[]{
            R.drawable.t2,R.drawable.t3,R.drawable.t4,
            R.drawable.t5
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose);
        //獲取網格佈局管理器
        GridView gridView= (GridView) findViewById(R.id.gridView);
        //設置適配器
        BaseAdapter adapter=new BaseAdapter() {
            @Override
            public int getCount() {
                return imageId.length;
            }

            @Override
            public Object getItem(int i) {
                return i;
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public View getView(int position, View view, ViewGroup viewGroup) {
                ImageView imageView;
                //如果沒有選擇
                if(view==null)
                {
                    imageView=new ImageView(Choose.this);
                    imageView.setAdjustViewBounds(true);
                    imageView.setMaxWidth(158);
                    imageView.setMaxHeight(150);
                    imageView.setPadding(5,5,5,5);
                }
                else
                {
                    imageView=(ImageView)view;
                }
                //改變圖片
                imageView.setImageResource(imageId[position]);
                return imageView;
            }
        };

        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=getIntent();
                Bundle bundle=new Bundle();
                bundle.putInt("imageId",imageId[i]);
                intent.putExtras(bundle);
                setResult(0x11,intent);
                //返回上一級
                finish();
            }
        });

    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章