在OnTouch中更改页面

时间:2012-05-16 20:21:52

标签: java android android-intent ontouchevent

我知道如何制作它以便你打开一个新页面onClick但是当我把相同的代码放入onTouch它不起作用?这是我的代码...如果我点击错误,我会得到一条消息说“构造函数Intent(Tab3,Class)未定义”并且它要我将其设置为“= new Intent”但对我有任何帮助那不是我的意思。

public boolean onTouch(View v, MotionEvent event) 
    {
        if(rect2.contains((int) event.getX(),(int) event.getY()))
        {
            Intent SectionManager = new Intent (this, SectionManager.class);
            startActivity (SectionManager);
        }
        return true;
    }

EDIT 有关我的代码的更多信息!

public class Tab3 extends View implements OnTouchListener
{
    LinearLayout myLayout;
    int x1, x2, y1, y2, x, y;
    // x, y;
    Rect rect2 = new Rect();

    public Tab3(Context context, AttributeSet attrs)
    {
        super (context, attrs);

        myLayout = (LinearLayout) findViewById(R.id.myLayout);

        x1 = 0;
        x2 = 300;               //1280 by 748
        y1 = 0;
        y2 = 300;




        setFocusable(true);
        setFocusableInTouchMode(true); 
        setOnTouchListener(this);
        requestFocus();
    }

    @Override
    protected void onDraw(Canvas canvas) 
    {
        super.onDraw(canvas);

        Paint blue = new Paint();
        blue.setColor(Color.BLUE);
        canvas.drawRect(rect2, blue);
        rect2.set(x1, y1, x2, y2);

        invalidate();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) 
    {
        if(rect2.contains((int) event.getX(),(int) event.getY()))
        {
            Intent SectionManager = new Intent (Tab3.this, SectionManager.class);
            startActivity (SectionManager);
        }
        return true;
    }
}

1 个答案:

答案 0 :(得分:1)

您的上下文错误,您需要在YourClassName.this内部使用this而不仅仅是this。目前Tab3表示名为public class MyActivity extends Activity{ . all your activity stuff here . . public class Tab3 extends View implements OnTouchListener{ LinearLayout myLayout; int x1, x2, y1, y2, x, y; // x, y; Rect rect2 = new Rect(); public Tab3(Context context, AttributeSet attrs) { super (context, attrs); myLayout = (LinearLayout) findViewById(R.id.myLayout); x1 = 0; x2 = 300; //1280 by 748 y1 = 0; y2 = 300; setFocusable(true); setFocusableInTouchMode(true); setOnTouchListener(this); requestFocus(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint blue = new Paint(); blue.setColor(Color.BLUE); canvas.drawRect(rect2, blue); rect2.set(x1, y1, x2, y2); invalidate(); } @Override public boolean onTouch(View v, MotionEvent event) { if(rect2.contains((int) event.getX(),(int) event.getY())) { Intent SectionManager = new Intent (MyActivity.this, SectionManager.class); startActivity (SectionManager); } return true; } } //end Tab3 Class } //end MyActivity 的视图,而不是上下文

{{1}}

Tab3现在是MyActivity的子类,你应该能够做MyActivity.this