Android - 从自定义View类访问main中的方法

时间:2015-10-24 21:18:49

标签: java android

我在我的应用的MainActivity类上处理蓝牙连接。我想在自定义视图中发生触摸事件时发送数据。

public boolean onTouch(View v, MotionEvent event) {

    int action=event.getActionMasked();
    ...
    if(action==1){
        MainActivity.sendData("P,S," + stringvelocidad + ","+stringrotacion+"&");
    }

但是无法从静态方法访问非静态方法。我必须以适当的方式做到这一点?

这是sendData()方法:

public void sendData(String message) {
    try {
        outStream=btSocket.getOutputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }


    byte[] msgBuffer = message.getBytes();

    Log.d(TAG, "...Sending data: " + message + "...");


    try {
        outStream.write(msgBuffer);
    } catch (IOException e) {

    }
    try {
        outStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

我发布了整个代码

public class EjemploView extends View implements View.OnTouchListener {

private Drawable drawableFader, drawableSlider, drawableLogo;
private Grafico fader1, fader2, slider1, slider2,logo;
Paint pincel=new Paint();
private String stringvelocidad="0",stringrotacion="0";
private int slider1cero,slider2cero;
int oldvelocidad=0;
int oldrotacion=0;

// Cada cuanto queremos procesar cambios (ms)
private static long PERIODO_PROCESO = 1000000;
// Cuando se realizó el último proceso
private long ultimoProceso = 0;





public EjemploView(Context context, AttributeSet attrs) {
    super(context,attrs);
    setOnTouchListener(this);
    Resources res = context.getResources();
    drawableFader = res.getDrawable(R.drawable.fader);
    drawableSlider=res.getDrawable(R.drawable.slider);
    drawableLogo=res.getDrawable(R.drawable.logo);


    fader1 = new Grafico(this, drawableFader);
    fader2 = new Grafico(this, drawableFader);
    slider1 = new Grafico(this, drawableSlider);
    slider2 = new Grafico(this, drawableSlider);
    logo=new Grafico(this,drawableLogo);


    fader1.setAlto(350);
    fader1.setAncho(64);
    fader2.setAlto(350);
    fader2.setAncho(64);
    fader2.setAngulo(90);


    slider1.setAlto(90);
    slider1.setAncho(55);
    slider2.setAlto(90);
    slider2.setAncho(55);
    slider2.setAngulo(90);

    logo.setAncho(380);
    logo.setAlto(120);



}

@Override
protected void onSizeChanged(int ancho, int alto, int ancho_anter, int alto_anter) {
    super.onSizeChanged(ancho, alto, ancho_anter, alto_anter);

    // Una vez que conocemos nuestro ancho y alto.
    Hilo myThread = new Hilo();
    myThread.start();

    slider1cero=alto / 4 - 50;
    slider2cero=ancho - 277;
    fader1.setCenX(ancho / 4 - 31);
    fader1.setCenY(alto / 4 - 50);
    slider1.setCenX(ancho / 4 - 28);
    slider1.setCenY(alto / 4 - 50);
    fader2.setCenX(ancho - 271);
    fader2.setCenY(alto / 4 - 50);
    slider2.setCenX(ancho - 277);
    slider2.setCenY(alto / 4 - 50);

    logo.setCenX(ancho - 277);
    logo.setCenY(100);
}

@Override
synchronized protected void onDraw(Canvas canvas) {



    pincel.setColor(Color.BLACK);
    pincel.setTextSize(30);
    canvas.drawText("Velocidad:", 300, 390, pincel);
    canvas.drawText("Rotación:", 300, 430, pincel);
    canvas.drawText(stringvelocidad, 450, 390, pincel);
    canvas.drawText(stringrotacion, 450, 430, pincel);



    fader1.dibujaGrafico(canvas);
    fader2.dibujaGrafico(canvas);
    slider1.dibujaGrafico(canvas);
    slider2.dibujaGrafico(canvas);
    logo.dibujaGrafico(canvas);
}

@Override
public boolean onTouch(View v, MotionEvent event) {

    int action=event.getActionMasked();

    final float x=event.getX();
    final float y=event.getY();

    if(x>slider1.getCenX()-30 &&x<slider1.getCenX()+30 && y<fader1.getCenY()+fader1.getAlto()/2&&
            y>fader1.getCenY()-fader1.getAlto()/2) {
        slider1.setCenY((int) y);
    }
    if(y>fader2.getCenY()-30 &&y<fader2.getCenY()+31&& x<fader2.getCenX()+fader2.getAlto() / 2 &&
            x > fader2.getCenX()-fader2.getAlto()/2) {
        slider2.setCenX((int) x);
    }

    if(action==1){
        MainActivity.sendData("P,S," + stringvelocidad + "," +stringrotacion+"&");
    }
    return true;
}

public class Hilo extends Thread {
    public void run(){
        while(true){
            setspeed();
        }
    }
}

public void setspeed(){
    long ahora = System.currentTimeMillis();

    int velocidad=-1*(slider1.getCenY()-slider1cero);
    int rotacion=slider2.getCenX()-slider2cero;

    if (velocidad!=oldvelocidad||rotacion!=oldrotacion) {
        stringvelocidad = String.valueOf((int)(velocidad*0.3));
        stringrotacion = String.valueOf((int)(rotacion*0.3));

    }
    ultimoProceso = ahora;
    oldvelocidad=velocidad;
    oldrotacion=rotacion;


}

和活动代码

public class MainActivity extends Activity {

private static final String TAG = "mensajes";

//-------BLUETOOTH VARIABLES--------//
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;

// Well known SPP UUID
private static final UUID MY_UUID =
        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

// Insert your bluetooth devices MAC address
private static String address = "00:12:11:21:21:94";


//--------------------------------------//



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

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    checkBTState();

}

@Override
protected void onDestroy() {

    super.onDestroy();
}

@Override
public void onResume() {
    super.onResume();
    // Set up a pointer to the remote node using it's address.
    BluetoothDevice device = btAdapter.getRemoteDevice(address);

    // Two things are needed to make a connection:
    //   A MAC address, which we got above.
    //   A Service ID or UUID.  In this case we are using the
    //     UUID for SPP.
    try {
        btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
        errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }

    // Discovery is resource intensive.  Make sure it isn't going on
    // when you attempt to connect and pass your message.
    btAdapter.cancelDiscovery();

    // Establish the connection.  This will block until it connects.
    Log.d(TAG, "...Connecting to Remote...");
    try {
        btSocket.connect();
        Log.d(TAG, "...Connection established and data link opened...");
    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
        }
    }
    try {
        outStream=btSocket.getOutputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //sendData("P");
}

public void onPause() {
    super.onPause();
    Log.d(TAG, "...In onPause()...");

    if (outStream != null) {
        try {
            outStream.flush();
        } catch (IOException e) {
            errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
        }
    }

    try     {
        btSocket.close();
    } catch (IOException e2) {
        errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    }
}

private void checkBTState() {
    // Check for Bluetooth support and then check to make sure it is turned on

    // Emulator doesn't support Bluetooth and will return null
    if(btAdapter==null) {
        errorExit("Fatal Error", "Bluetooth Not supported. Aborting.");
    } else {
        if (btAdapter.isEnabled()) {
            Log.d(TAG, "...Bluetooth is enabled...");
        } else {
            //Prompt user to turn on Bluetooth
            Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

private void errorExit(String title, String message){
    Toast msg = Toast.makeText(getBaseContext(),
            title + " - " + message, Toast.LENGTH_SHORT);
    msg.show();
    finish();
}



public void sendData(String message) {
    try {
        outStream=btSocket.getOutputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }


    byte[] msgBuffer = message.getBytes();

    Log.d(TAG, "...Sending data: " + message + "...");


    try {
        outStream.write(msgBuffer);
    } catch (IOException e) {
        /*String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
        if (address.equals("00:00:00:00:00:00"))
            msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
        msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";

        errorExit("Fatal Error", msg);*/
    }
    try {
        outStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }

}






}

1 个答案:

答案 0 :(得分:0)

该解决方案一直在创建一个类来处理所有蓝牙连接,并在我的Activity中设置此类的公共静态对象。这使我从自定义视图中访问其方法。