android中的OnTouchEvent上的TextView的getTag()

时间:2013-11-27 19:33:11

标签: android

我在线性布局中显示四个textView。我是每个textView的用户setTag() 当我ACTION_UP然后ACTION_MOVE然后ACTION_UP。活动正常。但getTag的{​​{1}}是相同的。意味着视图对象不起作用。

textView

以下是我的日志。

public class MainActivity extends Activity { TextView t[] = new TextView[4]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout linear = (LinearLayout) findViewById(R.id.linear); for(int i=0;i<t.length;i++) { t[i] = new TextView(this); t[i].setTag(i); String s = "Hello : "+i; t[i].setText(s); t[i].setTag(i); linear.addView(t[i]); t[i].setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { if(arg1.getAction() == MotionEvent.ACTION_UP) { Log.d("up ", "tag: "+arg0.getTag()); } else if(arg1.getAction() == MotionEvent.ACTION_DOWN) { Log.d("down ", "tag: "+arg0.getTag()); } else if(arg1.getAction() == MotionEvent.ACTION_MOVE) { Log.d("move ", "tag: "+arg0.getTag()); } return true; } }); } } ACTION_DOWN移至textview0。活动正常。但是视图的标签不会改变。我在每个触摸事件上都获得相同的标记。我的日志是:

textview2

有什么问题?

1 个答案:

答案 0 :(得分:0)

尝试将您的观点设为最终结果:

LinearLayout linear = (LinearLayout) findViewById(R.id.linear);
    for(int i=0;i<t.length;i++)
    {
        final TextView t = new TextView(this);
        t[i] = t
        t[i].setTag(i);
        String s = "Hello :  "+i;
        t[i].setText(s);
        t[i].setTag(i);
        linear.addView(t[i]);
        t[i].setOnTouchListener(new OnTouchListener()
        {

            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) 
            {

                if(arg1.getAction() == MotionEvent.ACTION_UP)
                {
                    Log.d("up ", "tag: "+arg0.getTag());
                }
                else if(arg1.getAction() == MotionEvent.ACTION_DOWN)
                {
                    Log.d("down ", "tag: "+arg0.getTag());
                }
                else if(arg1.getAction() == MotionEvent.ACTION_MOVE)
                {
                    Log.d("move ", "tag: "+arg0.getTag());
                }
                return true;
            }
        });
    }