如何在 android 中對字串進行編碼?
本例演示如何在 android 中對字串進行編碼。
步驟 1 - 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新專案並填寫所有必需的詳細資訊以建立一個新專案。
<?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" /> </LinearLayout>
在上面的程式碼中,我們採用了編輯文字、按鈕和文字視窗。當用戶在編輯文字中插入值後點擊按鈕時,它將進行編碼。
步驟 3 - 將以下程式碼新增到 src/MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView text;
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);
findViewById(R.id.buttonPanel).setOnClickListener(new View.OnClickListener() {
@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);
}
}
});
}
}讓我們嘗試執行你的應用程式。我假設你已將你的實際安卓移動裝置與計算機連線。要從 android studio 執行應用程式,開啟專案的一個活動檔案,然後從工具欄中單擊執行
圖示。選擇你的移動裝置作為選項,然後檢查將顯示預設螢幕的移動裝置 -

在上方的結果中,我們已對文字視窗進行編碼並附加到其中。
單擊 此處 下載專案程式碼
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP