如何在 Android 中解碼字串?
本例展示如何在 Android 中解碼字串。
步驟 1 - 在 Android Studio 中建立一個新專案,依次轉到檔案 ⇒ 新專案,然後填寫所有必需的詳細資訊來建立一個新專案。
步驟 2 - 向 res/layout/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:gravity="center_horizontal" android:layout_marginTop="30dp" tools:context=".MainActivity"> <EditText android:id="@+id/edit_query" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/buttonPanel" android:text="Check" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/text1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
在上面的程式碼中,我們已經取了 editext、button 和 textview。當用戶在編輯文字框中插入值後單擊按鈕時,它將進行編碼和解碼。
步驟 3 - 向 src/MainActivity.java 中新增以下程式碼
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.nio.charset.StandardCharsets;
public class MainActivity extends AppCompatActivity {
TextView text,text1;
EditText edit_query;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_query = findViewById(R.id.edit_query);
text = findViewById(R.id.text);
text1 = findViewById(R.id.text1);
findViewById(R.id.buttonPanel).setOnClickListener(new View.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onClick(View v) {
if (!edit_query.getText().toString().isEmpty()) {
String encode = Base64.encodeToString(edit_query.getText().toString().getBytes(), Base64.DEFAULT);
text.setText(encode);
byte[] data = Base64.decode(encode, Base64.DEFAULT);
String text = new String(data, StandardCharsets.UTF_8);
text1.setText(text);
}
}
});
}
}我們嘗試執行你的應用程式。我假設你已經將你實際的 Android 手機裝置與計算機相連。要從 android studio 執行應用程式,請開啟你的一個專案活動檔案,然後單擊工具欄中的執行
圖示。選擇你的移動裝置作為一個選項,然後檢查將顯示你的預設螢幕的移動裝置 -

在上方的結果中,我們已經編碼和解碼。
點選 這裡 下載專案程式碼
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP