Я хочу отобразить результат в виде строки для текстового представления в действии из пользовательского представления. Пожалуйста, найдите код ниже:
public class MainActivity extends AppCompatActivity {
TextView resultTextView;
InkRecognizer inkRecognizer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NoteTaker noteTaker = new NoteTaker(this);
setContentView(R.layout.activity_main);
resultTextView = findViewById(R.id.textResult);
RelativeLayout layout= findViewById(R.id.relative);
layout.addView(noteTaker);
}
}
Класс пользовательского просмотра
public class NoteTaker extends View {
private final Path path = new Path();
private final Paint brush = new Paint();
private InkStroke stroke;
private final InkRecognizer inkRecognizer;
private CountDownTimer analysisTimer = null;
private final DisplayMetrics metrics;
private TextView textView;
public NoteTaker(Context context) {
super(context);
String appKey = "";
String destinationUrl = "";
inkRecognizer = new InkRecognizer(appKey, destinationUrl, context);
brush.setAntiAlias(true);
brush.setColor(Color.BLACK);
brush.setStyle(Paint.Style.STROKE);
brush.setStrokeJoin(Paint.Join.ROUND);
brush.setStrokeWidth(3.0f);
this.metrics = getResources().getDisplayMetrics();
inkRecognizer.setMetrics(metrics);
}
private void startTimer() {
//The next 2 variables are used for the inactivity timer which triggers recognition
//after a certain period of inactivity.
int milliSeconds = 2000;//Time to wait
int countDownInterval = 1000;//interval
analysisTimer = new CountDownTimer(milliSeconds, countDownInterval) {
public void onTick(long millFinish) {
}
public void onFinish()
{
inkRecognizer.Recognize();
}
}.start();
}
private void cancelTimer() {
if (analysisTimer != null) {
analysisTimer.cancel();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(x, y);
stroke = new InkStroke(metrics);
stroke.addPoint(x, y);
cancelTimer();
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(x, y);
stroke.addPoint(x, y);
break;
case MotionEvent.ACTION_UP:
inkRecognizer.addStroke(stroke);
startTimer();
break;
default:
return false;
}
postInvalidate();
return false;
}
@Override
protected void onDraw(Canvas canvas)
{
canvas.drawPath(path, brush);
}
}
Класс модели:
public class InkRecognizer {
private final ArrayList<InkStroke> strokes = new ArrayList<>();
private final String app_key;
private final String url;
private InkRoot inkRoot; //the root holds the recognition units reported by the service
private DisplayMetrics metrics;
private final boolean displayTree = true;
private MainActivity mainActivity;
StringBuilder recognizedWords;
String name;
private Context getContext() {
return context;
}
private final Context context;
public void setMetrics(DisplayMetrics metrics) {
this.metrics = metrics;
}
InkRecognizer(String appKey, String destinationUrl, Context context) {
this.app_key = appKey;
this.url = destinationUrl;
this.context = context;
}
public void Recognize() {
//only attempt to analyze if we have strokes
if (strokes.size() != 0) {
new RecognitionRESTTask().execute(this);
}
}
public void addStroke(InkStroke stroke) {
strokes.add(stroke);
}
private InkRoot getRecognitionRoot()
{
return inkRoot;
}
private void buildResult(String jsonData, int httpResponseCode) {
this.inkRoot = new InkRoot(jsonData, metrics, httpResponseCode);
}
private String getJSONStrokes() throws JSONException {
JSONObject jsonAnalysisRequest = new JSONObject();
jsonAnalysisRequest.put("unit", "mm");
jsonAnalysisRequest.put("language", "en-US");
JSONArray jsonStrokes = new JSONArray();
for (int i=0 ; i<strokes.size(); i++) {
InkStroke stroke = strokes.get(i);
JSONObject jsonStroke = new JSONObject();
jsonStroke.put("id", stroke.strokeId);
jsonStroke.put("language", stroke.language); //The language is an optional field which can be used when dealing with multi-language apps.
if (stroke.kind != StrokeKind.UNKNOWN) {
jsonStroke.put("kind", strokeKindToString(stroke.kind));
}
StringBuilder points = new StringBuilder();
JSONArray jsonPoints = new JSONArray();
for (int r=0;
r < stroke.inkPoints.size();
r++) {
JSONObject jsonPoint = new JSONObject();
jsonPoint.put("x", stroke.inkPoints.get(r).x);
jsonPoint.put("y", stroke.inkPoints.get(r).y);
jsonPoints.put(jsonPoint);
}
jsonStroke.put("points", jsonPoints);
jsonStrokes.put(jsonStroke);
}
jsonAnalysisRequest.put("strokes", jsonStrokes);
return jsonAnalysisRequest.toString();
}
private String strokeKindToString(StrokeKind kind) {
String strokeKind;
switch(kind) {
case DRAWING:
strokeKind = "inkDrawing";
break;
case WRITING:
strokeKind = "inkWriting";
break;
default:
strokeKind = "UnKnown";
break;
}
return strokeKind;
}
private static class RecognitionRESTTask extends AsyncTask<InkRecognizer, Integer, InkRecognizer> {
@SuppressWarnings("SpellCheckingInspection")
@Override
protected InkRecognizer doInBackground(InkRecognizer... params) {
int responseCode;
InkRecognizer inkRecognizer = params[0];
try {
URL url = new URL(inkRecognizer.url);
HttpsURLConnection restConnection = (HttpsURLConnection) url.openConnection();
restConnection.setRequestProperty("Content-Type","application/json");
restConnection.setRequestProperty("Ocp-Apim-Subscription-Key", inkRecognizer.app_key);
restConnection.setRequestMethod("PUT");
restConnection.setDoOutput(true);
OutputStreamWriter jsonStrokesWriter = new OutputStreamWriter(restConnection.getOutputStream());
jsonStrokesWriter.write(inkRecognizer.getJSONStrokes());
jsonStrokesWriter.flush();
jsonStrokesWriter.close();
responseCode = restConnection.getResponseCode();
// read the output from the server
if (responseCode == HttpURLConnection.HTTP_OK ||
responseCode == HttpURLConnection.HTTP_BAD_REQUEST) {
InputStreamReader streamReader = new InputStreamReader(restConnection.getInputStream());
inkRecognizer.buildResult(getResponseString(streamReader), responseCode);
}
else {
String responseError = "{}";
if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
InputStreamReader streamReader = new InputStreamReader(restConnection.getErrorStream());
responseError = getResponseString(streamReader);
}
inkRecognizer.buildResult(responseError, responseCode);
}
}
catch (Exception e) {
e.printStackTrace();
inkRecognizer.buildResult("Error Occurred", 0);
}
return inkRecognizer;
}
private String getResponseString(InputStreamReader streamReader) throws Exception
{
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseBody.append(line).append("\n");
}
return responseBody.toString();
}
@Override
protected void onPostExecute(InkRecognizer analyzer) {
StringBuilder recognizedWords = new StringBuilder();
InkRoot inkRoot = analyzer.getRecognitionRoot();
if (inkRoot.getResultStatus() == RecognitionResultStatus.UPDATED) {
ArrayList<InkWord> words = inkRoot.getInkWords();
for (int i = 0; i < words.size(); i++) {
recognizedWords.append(words.get(i).getText());
recognizedWords.append(" ");
}
ArrayList<InkDrawing> drawings = inkRoot.getInkDrawings();
recognizedWords.append("\r\nRecognized Shapes:\r\n");
for (int i = 0; i < drawings.size(); i++) {
recognizedWords.append(drawings.get(i).getShape().toString()).append("\r\n");
}
if(analyzer.displayTree) {
InkRecognitionDetailsLogger.displayAnalysisTree(inkRoot);
}
} else {
recognizedWords.append(inkRoot.getRecognitionError().toString());
}
Toast toast = Toast.makeText(analyzer.getContext(), recognizedWords.toString(), Toast.LENGTH_LONG);
toast.show();
}
}
}
Основная деятельность 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="@+id/relative"
android:layout_width="match_parent"
android:layout_height="500dp">
</RelativeLayout>
<TextView
android:id="@+id/textResult"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Result"/>
</LinearLayout>
Я хочу отобразить «knownWords.toString ()» для MainActivity resultTextView. Я попытался установить текст, создав новый объект Main Activity, но он не работает. Могу ли я узнать, как мы можем достичь того же