summaryrefslogtreecommitdiffstats
path: root/mobile/android/geckoview_example/src/main/java/org/mozilla/geckoview_example/LocationView.java
blob: c09d80509d8aa7674870d46a580b6c2ff4d965f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.geckoview_example;

import android.content.Context;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import androidx.appcompat.widget.AppCompatEditText;

public class LocationView extends AppCompatEditText {

  private CommitListener mCommitListener;
  private FocusAndCommitListener mFocusCommitListener = new FocusAndCommitListener();

  public interface CommitListener {
    void onCommit(String text);
  }

  public LocationView(Context context) {
    super(context);

    this.setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_URI);
    this.setSingleLine(true);
    this.setSelectAllOnFocus(true);
    this.setHint(R.string.location_hint);

    setOnFocusChangeListener(mFocusCommitListener);
    setOnEditorActionListener(mFocusCommitListener);
  }

  public void setCommitListener(CommitListener listener) {
    mCommitListener = listener;
  }

  private class FocusAndCommitListener implements OnFocusChangeListener, OnEditorActionListener {
    private String mInitialText;
    private boolean mCommitted;

    @Override
    public void onFocusChange(View view, boolean focused) {
      if (focused) {
        mInitialText = ((TextView) view).getText().toString();
        mCommitted = false;
      } else if (!mCommitted) {
        setText(mInitialText);
      }
    }

    @Override
    public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
      if (mCommitListener != null) {
        mCommitListener.onCommit(textView.getText().toString());
      }

      mCommitted = true;
      return true;
    }
  }
}