背景
在Android中,自定义编辑器视图可以通过InputConnection
从系统键盘接收文本。我已经成功地创建了这样的视图。然而,当设备处于横屏模式时,系统有时会选择显示一个提取的文本视图。当用户在此模式下输入时,提取的文本视图应该更新为与自定义视图中相同的文本。
我尚未实现提取的文本视图功能。(这里是我尝试过的一些方法。)
我也没有找到任何清晰的文档或完整的示例来说明如何实现它。(以下是我阅读过的一些更好的内容:one、two、three、four。)
MCVE
我创建了最基本的自定义编辑器。下面的gif显示了其功能。它可以从键盘接收文本,但在横屏模式下不会更新提取的文本视图。因此,您必须关闭键盘才能看到更新后的文本。
MyCustomView.java
public class MyCustomView extends View {
SpannableStringBuilder mText;
Paint mPaint;
public MyCustomView(Context context) {
this(context, null, 0);
}
public MyCustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setFocusableInTouchMode(true);
mText = new SpannableStringBuilder();
mPaint = new Paint();
mPaint.setColor(Color.BLACK);
mPaint.setTextSize(60);
mPaint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(mText, 0, mText.length(), 50, 100, mPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) return false;
imm.showSoftInput(this, InputMethodManager.SHOW_FORCED);
}
return true;
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
outAttrs.inputType = InputType.TYPE_CLASS_TEXT;
return new MyInputConnection(this, true);
}
}
MyInputConnection.java
public class MyInputConnection extends BaseInputConnection {
private MyCustomView customView;
MyInputConnection(View targetView, boolean fullEditor) {
super(targetView, fullEditor);
customView = (MyCustomView) targetView;
}
@Override
public Editable getEditable() {
return customView.mText;
}
@Override
public boolean commitText(CharSequence text, int newCursorPosition) {
boolean returnValue = super.commitText(text, newCursorPosition);
customView.invalidate();
return returnValue;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<net.example.extractedtext.MyCustomView
android:id="@+id/myCustomView"
android:background="@android:color/holo_blue_bright"
android:layout_margin="50dp"
android:layout_width="300dp"
android:layout_height="150dp"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
摘要
我正在寻找一份规范的答案,描述并举例说明如何为自定义编辑器视图实现提取文本更新。
如果我自己找到了方法,我会添加我的答案。但是目前我能够做的最好的只是完全禁用提取的文本。这并不理想。
0
,但实际上需要设置它。 - Suragch