TextView нельзя выбрать с помощью ontouchListener - PullRequest
1 голос
/ 06 июля 2019

Я включил ontouchListener в свою деятельность, чтобы обнаруживать пролистывание влево и вправо. Однако включение этой функции лишило меня возможности выбора текста и, соответственно, получения курсора выделения текста по умолчанию для Android, меню.

После многих испытаний теперь я могу прекрасно вызывать метод onLongClick () при длительном нажатии на textView. Тем не менее, текст по-прежнему нельзя выделить. Кроме того, всякий раз, когда я отключаю обнаружение прокрутки, выбор текста работает отлично.

public class PreviewActivity extends AppCompatActivity
{

TextView question;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_preview);
    question = (TextView)findViewById(R.id.question);
    question.setTextSize(TextViewSize);
    question.setTextIsSelectable(true);
    question.setLongClickable(true);
    question.setFocusableInTouchMode(true);
    View prev_act = (View) findViewById(R.id.question);
    prev_act.setOnTouchListener(new OnSwipeTouchListener(this) {
        @Override public void onSwipeLeft() {
            if(RowIndex>0){
                Qtitle = ListItems.get(RowIndex-1);
                Query();
                //text = Query();

            //question.setText(text);
            questionSC.scrollTo(0,0);
            RowIndex--;
             }
        }
        @Override public void onSwipeRight() {
            if(RowIndex<ListItems.size()-1){
                Qtitle = ListItems.get(RowIndex+1);
                Query();
                //text = Query();

                //question.setText(text);
                questionSC.scrollTo(0,0);
                RowIndex++;
            }
        }
        @Override public void onLongClick() {
            Log.v(this.toString(), "Long click.");
            question.setCursorVisible(true);
            question.performLongClick();
        }
    });
}

И класс OnSwipeTouchListener выглядит следующим образом:

public class OnSwipeTouchListener implements OnTouchListener {
    private final GestureDetector gestureDetector;

public OnSwipeTouchListener (Context ctx){
    gestureDetector = new GestureDetector(ctx, new GestureListener());
}

@Override public boolean onTouch(View v, MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}

private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 250;
private static final int SWIPE_VELOCITY_THRESHOLD = 200;

@Override
public void onLongPress(MotionEvent e) {
    onLongClick();
    super.onLongPress(e);
}

@Override
public boolean onDown(MotionEvent e) {
    return true;
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    boolean result = false;
    try {
        float diffY = e2.getY() - e1.getY();
        float diffX = e2.getX() - e1.getX();
        if (Math.abs(diffX) > Math.abs(diffY)) {
            if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                if (diffX > 0) {
                    onSwipeRight();
                } else {
                    onSwipeLeft();
                }
                result = true;
            }
        } 
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}
}

    public void onSwipeRight() {
    }
   public void onSwipeLeft() {
   }
   public void onSwipeTop() {
   }
   public void onSwipeBottom() {
   }

public void onLongClick() {
}

}

Я хочу иметь возможность выбрать часть (текст) из TextView и иметь детектор пролистывания вдоль него.

Отредактировано: добавлен XML-файл упомянутой операции

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_preview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="50dp"
android:paddingRight="20dp"
android:paddingLeft="20dp"
android:paddingBottom="30dp"
android:background="@drawable/bg"
>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageButton
        android:id="@+id/next"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="#0000"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_navigate_before_black_24dp" />

    <ImageButton
        android:id="@+id/share"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="#0000"
        android:padding="9dp"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_share_black_24dp" />

    <ImageButton
        android:id="@+id/star"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="#0000"
        android:padding="9dp"
        android:scaleType="fitCenter"
        android:src="@drawable/star_border" />

    <ImageButton
        android:id="@+id/copy"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="#0000"
        android:padding="9dp"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_content_copy_black_24dp" />

    <ImageButton
        android:id="@+id/previous"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:background="#0000"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_navigate_next_black_24dp" />

</LinearLayout>

<ScrollView
    android:id="@+id/questionSC"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="30dp"
    android:layout_marginTop="50dp">

    <LinearLayout
        android:id="@+id/question_lo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/question"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fontFamily="@font/ge_thameen_book"
            android:paddingBottom="20dp"
            android:paddingTop="10dp"
            android:textAlignment="center"
            android:textColor="#000000"
            android:textSize="20dp"
            android:autoLink="web"
            />

    </LinearLayout>

</ScrollView>

Ответы [ 2 ]

0 голосов
/ 06 июля 2019

Ответ был очень прост:

@Override
public boolean onDown(MotionEvent e) {
    return false;
}

Мне пришлось установить onDown () для возврата false.

0 голосов
/ 06 июля 2019

После некоторой попытки это сработало, выделив и выделив текст, который позволяет копировать, вставлять, выбирать все ... и т. Д.

вам нужно будет добавить фрагмент onTouch в prev_act.setOnTouchListener(new OnSwipeTouchListener(this) {

@Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                //do stuff here
                Log.i("clicking", "onActionDown");
            }else if(event.getAction() == MotionEvent.ACTION_UP) {

                question.performLongClick();
            }

            return false;
        }
        @Override public void onLongClick() {
        }
...