在Android的編輯框(EditText)中插入圖片或表情符號,你可以按照以下步驟操作:
<uses-permission android:name="android.permission.READ_INPUT_METHOD_STATE" />
<uses-permission android:name="android.permission.WRITE_INPUT_METHOD_STATE" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine|textCapSentences" />
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
}
public void insertImage(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
InputStream inputStream = getContentResolver().openInputStream(selectedImage);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] imageBytes = byteArrayOutputStream.toByteArray();
editText.getText().insert(editText.getSelectionStart(), " ");
editText.getText().insert(editText.getSelectionEnd(), " ");
editText.setCompoundDrawablesWithIntrinsicBounds(BitmapFactory.decodeResource(getResources(), R.drawable.ic_image), null, null, null);
editText.setSelection(editText.getSelectionEnd());
File tempFile = new File(getCacheDir(), "temp_image.jpg");
FileOutputStream outputStream = new FileOutputStream(tempFile);
outputStream.write(imageBytes);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
<Button
android:id="@+id/buttonInsertImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert Image"
android:onClick="insertImage" />
現在,當你點擊"Insert Image"按鈕時,應用會打開一個文件選擇器,讓你選擇一個圖片。選擇圖片后,圖片將被插入到編輯框中,并顯示一個插入圖片的圖標。你可以使用以下代碼將圖片保存到設備的相冊中:
private void saveImageToGallery(File imageFile) {
Uri imageUri = FileProvider.getUriForFile(this, "com.example.yourapp.fileprovider", imageFile);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(imageUri);
sendBroadcast(mediaScanIntent);
}
注意:在Android 6.0(API級別23)及更高版本中,需要在運行時請求存儲權限。你可以使用以下代碼請求存儲權限:
private static final int REQUEST_CODE_STORAGE = 1;
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_STORAGE);
} else {
saveImageToGallery(tempFile);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_STORAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
saveImageToGallery(tempFile);
} else {
Toast.makeText(this, "Permission denied. Can't save image to gallery.", Toast.LENGTH_SHORT).show();
}
}
}
在onCreate()
方法中調用requestStoragePermission()
方法以請求存儲權限。