0

我有一个包含 TextView 的 FrameLayout,我将 OnTouchListener 添加到 FrameLayout 以执行 translateX 工作。然后我将 OnClickListener 添加到 TextView 以更改文本。然后 FrameLayout 不能 translateX。

如何解决这个冲突?我希望 TextView 可以执行单击操作,而 FrameLayout 可以 translateX。

谁能帮我?谢谢!

布局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/panel"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"/>
</FrameLayout>    

然后在 Activity

public class MainActivity3 extends AppCompatActivity {

    float downX = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_frame);

        FrameLayout panel = findViewById(R.id.panel);
        panel.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        downX = event.getX();
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        float dx = event.getX() - downX;
                        panel.setTranslationX(dx);
                        return true;
                    case MotionEvent.ACTION_UP:
                        return true;
                }
                return false;
            }
        });

        TextView textView = findViewById(R.id.textView);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("this is textview click");
            }
        });
      }
}
4

2 回答 2

0

首先你必须得到 textView 可见的 Rect

Rect visibleRect = new Rect();
yourTextView.getGlobalVisibleRect();

然后你检查你的触摸事件坐标,

if (event.getX()>= visibleRect.left and event.getX()<=visibleRect.right and 
   event.getY>=visibleRect.bottom and event.getY<= visibleRect.top)
   {
   //perform click on textView
   return
   }
于 2019-01-04T10:12:05.097 回答
0

您的问题是match_parentTextView 上的属性占用了整个可用空间。将 from 更改match_parentwrap_content,它应该可以正常工作。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/panel"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"/>
</FrameLayout>  

您的 FrameLayout 触发器隐藏在 TextView 后面,因为 TextView 已经占用了它的所有可用空间。

于 2019-01-04T10:00:16.087 回答