Intent 範例

YH Lin
Dec 19, 2020

這個例子,簡單來實作一下Intent的範例,首先使用者輸入帳號密碼後,按下登入,跳轉到下一個頁面

首先來看一下頁面配置,

b

這邊簡單用一個AppCompatEditText 元件,來取代BMI的例子中的LinearLayout的組合

<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/user"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="使用者名稱"
/>

在密碼的部分,設定android:inputType=”textPassword” 來隱藏密碼。

<androidx.appcompat.widget.AppCompatEditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="50dp"
android:inputType="textPassword"
android:hint="密碼"

在下面再加一個元件AppCompatCheckBox來決定是否要顯示密碼。

<androidx.appcompat.widget.AppCompatCheckBox
android:id = "@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密碼顯示"
/>

在MainActicity.java 中

c

一樣在onCreate的方法中,要載入所需要的元件。在checkbox中需要傾聽onCheckedChangedLitstener,

在password 中利用setTransformationMethod(HideReturnsTransformationMethod.getInstance()) 跟setTransformationMethod(PasswordTransformationMethod.getInstance())

來隱藏或顯示密碼。

checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
ed_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
} else {
ed_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
}

}
});

在btnClick中,當使用者按下登入後,執行檢查user帳號/密碼。帳號密actic碼都正確時就會利用Intent 的方式將資料利用putExtra 包起來,再利用startActivity 的方式送給ProfileActivity.class

public void btnClick(View view) {
if (ed_user.getText().toString().equals("Jacky") && ed_password.getText().toString().equals("12345678"))
{
Intent it = new Intent(this,ProfileActivity.class);
it.putExtra("user",ed_user.getText().toString());
it.putExtra("stage",1);
it.putExtra("role","魔關羽");
startActivity(it);

}else{
Toast.makeText(this,"帳號或密碼錯誤",Toast.LENGTH_SHORT).show();
}

}

在ProfileActivity 中 利用Intent it = getIntent();取得MainActivity 傳來的Intent,再利用getStringExtra()跟getIntExtra()來解析

最後別忘了加上layout配置

--

--