0

我知道怎么做,所以你会在 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;
    }

编辑有关我的代码的更多信息!

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;
    }
}
4

1 回答 1

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

Tab3 现在是 MyActivity 的子类,您应该可以执行 MyActivity.this

于 2012-05-16T20:26:26.453 回答