我有很多TextViews,我想为所有项目更改颜色,因为用户只需点击一下即可将光标拖到它们上。
我使用了setontouchlistener
,但此方法仅针对第一个按钮调用操作。无论如何,当用鼠标滑过它们时,同一个点击的所有人都可以做到吗?
这是我的代码:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView tv1,tv2,tv3,tv4,tv5;
Button bu,bu1,bu2;
MyTouchListener touchListener = new MyTouchListener();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1.setId(1);
tv2.setId(2);
tv3.setId(3);
tv4.setId(4);
tv5.setId(5);
tv1.setOnTouchListener(touchListener);
tv2.setOnTouchListener(touchListener);
tv3.setOnTouchListener(touchListener);
tv4.setOnTouchListener(touchListener);
tv5.setOnTouchListener(touchListener);
}
public class MyTouchListener implements View.OnTouchListener {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(v.getId()){
case 1:
tv1.setTextColor(0xffff0000);
break;
case 2:
tv2.setTextColor(0xffff0000);
break;
case 3:
tv3.setTextColor(0xffff0000);
break;
case 4:
tv4.setTextColor(0xffff0000);
break;
case 5:
tv5.setTextColor(0xffff0000);
break;
}
return true;
}
}
}
答案 0 :(得分:0)
如果我正确理解您,您希望在用户触摸屏幕或在触摸屏幕时将手指移动到TextView的内容上时执行代码。由于默认情况下所有触摸事件都不会传递给子视图,因此处理此问题的一种方法是覆盖活动的onTouchEvent方法并检查每个TextView的位置。我为你做了一个例子:
pulic class SomeActivity extends Activity {
private TextView tv01;
...
@Override
public boolean onTouchEvent(MotionEvent event) {
// Get the center location of the TextView.
int[] tv01pos = {(int) tv01.getX(), (int) tv01.getY()};
// Some debuging logs, may be deleted.
Log.d("position TV x", String.valueOf(tv01pos[0]));
Log.d("position TV y", String.valueOf(tv01pos[1]));
// Get the width and height of textView 01 for calculating the right and bottom boundaries.
int tv01Wide = tv01.getWidth();
int tv01High = tv01.getHeight();
// Get the location of the touch event, event may be of type Donw, Move, or Up.
// Keep in mind there are a LOT of these generated.
int[] touchPos = new int[2];
touchPos[0] = (int) event.getAxisValue(MotionEvent.AXIS_X);
touchPos[1] = (int) event.getAxisValue(MotionEvent.AXIS_Y);
// More debug logs.
Log.d("position Tch x", String.valueOf(touchPos[0]));
Log.d("position Tch y", String.valueOf(touchPos[1]));
// Check if the touch event is in the boundaries of TextView 01
if ( (touchPos[0] > tv01pos[0] ) &&
(touchPos[0] < tv01pos[0] + tv01Wide) &&
(touchPos[1] > tv01pos[1] ) &&
(touchPos[1] < tv01pos[1] + tv01High)) {
// A toast letting you know it's working. Put your code here.
Toast.makeText(view.getContext(), "In TextView01", Toast.LENGTH_SHORT).show();
}
return true;
}
}