-
-
Save ShivamKumarJha/79acc6f9ca0a983e6b91d0f4b6393bda to your computer and use it in GitHub Desktop.
This EditText will support GBOARD for gifs and other attachments like "image/png", "image/gif", "image/jpeg","image/webp"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.app.ui | |
import android.content.Context | |
import android.os.Build | |
import android.os.Bundle | |
import android.util.AttributeSet | |
import android.view.inputmethod.EditorInfo | |
import android.view.inputmethod.InputConnection | |
import androidx.appcompat.widget.AppCompatEditText | |
import androidx.core.view.inputmethod.EditorInfoCompat | |
import androidx.core.view.inputmethod.InputConnectionCompat | |
import androidx.core.view.inputmethod.InputContentInfoCompat | |
class ImageEditText : AppCompatEditText { | |
constructor(context: Context) : super(context) | |
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) | |
var mimeTypes: Array<String> = arrayOf("image/png", | |
"image/gif", | |
"image/jpeg", | |
"image/webp") | |
private var keyBoardInputCallbackListener: KeyBoardInputCallbackListener? = null | |
override fun onCreateInputConnection(editorInfo: EditorInfo): InputConnection { | |
val ic: InputConnection = super.onCreateInputConnection(editorInfo) | |
EditorInfoCompat.setContentMimeTypes(editorInfo, mimeTypes) | |
val callback = | |
InputConnectionCompat.OnCommitContentListener { inputContentInfo, flags, opts -> | |
val lacksPermission = (flags and | |
InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0 | |
// read and display inputContentInfo asynchronously | |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 && lacksPermission) { | |
try { | |
inputContentInfo.requestPermission() | |
} catch (e: Exception) { | |
return@OnCommitContentListener false // return false if failed | |
} | |
} | |
var supported = false | |
for (mimeType in mimeTypes) { | |
if (inputContentInfo.description.hasMimeType(mimeType)) { | |
supported = true | |
break | |
} | |
} | |
if (!supported) { | |
return@OnCommitContentListener false | |
} | |
keyBoardInputCallbackListener?.onCommitContent(inputContentInfo, flags, opts) | |
true | |
} | |
return InputConnectionCompat.createWrapper(ic, editorInfo, callback) | |
} | |
interface KeyBoardInputCallbackListener { | |
fun onCommitContent(inputContentInfo: InputContentInfoCompat?, | |
flags: Int, opts: Bundle?) | |
} | |
fun setKeyBoardInputCallbackListener(keyBoardInputCallbackListener: KeyBoardInputCallbackListener) { | |
this.keyBoardInputCallbackListener = keyBoardInputCallbackListener | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment