单击按钮时,android onClick不会运行

时间:2016-08-07 01:26:02

标签: java android xml

所以我有这个类有5个按钮的处理程序。它们应该运行两次线程并从另一个类调用一个函数。但是,当我点击它们时,它们什么都不做。当用户点击按钮时,我缺少什么才能使按钮工作?

我定义处理程序的类:

function asyncFoo() {
  const p = asyncAction();
  p.reflect().then(inspection => {
    console.log('promise p fulfilled %s', inspection.isFulfilled());
  });
  return p;
}

具有按钮应该调用的函数的类:

package com.example.michael.bluetoothcontroll;


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice; 
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Set;
import java.util.UUID;
import java.lang.Runnable;

public class control extends ActionBarActivity {

BluetoothDevice mmDevice;
blueToothControl bt = new blueToothControl();

@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_control, 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);
}

// Define the Handler that receives messages from the thread and update the progress
@Override
public void onCreate(final Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_control);

    final Button fwd   = (Button) findViewById(R.id.FWD);
    final Button rev   = (Button) findViewById(R.id.REV);
    final Button left  = (Button) findViewById(R.id.Left);
    final Button right = (Button) findViewById(R.id.Right);
    final Button start = (Button) findViewById(R.id.settings);


    /**
     *
     * render thread
     * used to update the UI
     *
     */
    final class render implements Runnable {

        // what to send to the TextView
        public String message;

        // constructor
        public render(String msg){
            message = msg;
        }

        public void run(){

            setContentView(R.layout.activity_control);
            TextView tv = (TextView) findViewById(R.id.confirm);
            tv.setText(message);
        }
    }

    /**
     *
     * button handlers
     *
     * */
    //start start button handler
    start.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v)
        {
            bt.callConnectThread(mmDevice);
        }
    });
    //end start button handler

    // start fwd button handler
    fwd.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            String test = bt.callWorkThread("fwd");
            (new Thread(new render("sending fwd \n"))).start();
            (new Thread(new render(test))).start();
        }
    });
    //end fwd button handler

    //start left on button handler
    left.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            (new Thread(new render("sending left \n"))).start();
            (new Thread(new render(bt.callWorkThread("left")))).start();
        }
    });
    //end left button handler

    //start right  button handler
    right.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            (new Thread(new render("sending right \n"))).start();
            (new Thread(new render(bt.callWorkThread("right")))).start();

        }
    });
    // end right button handler

    //start reverse  button handler
    rev.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            (new Thread(new render("sending rev \n"))).start();
            (new Thread(new render(bt.callWorkThread("rev")))).start();

        }
    });
    // end reverse button handler

    /**
     *
     *  check on bluetooth adapter
     *
     */
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    if(mBluetoothAdapter != null) {

        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                if (device.getName().equals("raspberrypi")) //Note, you will need to change this to match the name of your device
                {
                    Log.e("Robo", device.getName());
                    mmDevice = device;
                    break;
                }
            }
        }
    } else{

        // failed send the response to user
        (new Thread(new render("Error: could not find device \n"))).start();
    }
}
}

主要活动的我的xml:

package com.example.michael.bluetoothcontroll;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
  * responsible for all bluetooth threads
 */
public class blueToothControl {

BluetoothSocket mmSocket;
String connectionConfirmation;
String workConfirmation;

/**
 *
 * connect thread
 * to establish the bluetooth socket
 */
final class connectThread implements Runnable{

    BluetoothDevice mmDevice;

    public connectThread(BluetoothDevice Device){

        mmDevice = Device;
    }

    @Override
    public void run() {

        // try and connect to pi
        connectBT(mmDevice);
    }
}

/**
 *
 * workerThread
 * for sending data over the bluetooth socket
 *
 */
final class workerThread implements Runnable {

    private String btMsg;

    public workerThread(String msg) {

        // chars that get sent to the pi
        btMsg = msg;
    }

    public void run()
    {
        try {

            if(mmSocket != null) {

                OutputStream mmOutputStream = mmSocket.getOutputStream();
                mmOutputStream.write(btMsg.getBytes());
                workConfirmation = "sent \n >";

            }else{

                workConfirmation = "Error: failed to send" + btMsg + "\n > ";
            }

        } catch (IOException e) {

            e.printStackTrace();
        }

    }
}

/**
 * connectBT
 * @param mmDevice
 * takes the device and trys to create a socket with it
 */
protected void connectBT(BluetoothDevice mmDevice) {

    //UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
    final UUID uuid = UUID.fromString("94f39d29-7d6d-437d-973b-fba39e49d4ee"); //Standard SerialPortService ID


    try {

        if(mmDevice != null) {
            mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
            if (!mmSocket.isConnected()) {
                mmSocket.connect();
            }
        }else{

            connectionConfirmation = "Error: failed to connect to device \n >";
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// this function never runs when I click
protected String callConnectThread(BluetoothDevice Device){

    (new Thread(new connectThread(Device))).start();

    return connectionConfirmation;
}

// this function never runs 
protected String callWorkThread(String msg){

    (new Thread(new workerThread(msg))).start();

    return workConfirmation;
}

}

我认为这与不属于同一类的功能有关,但我可能会错,任何帮助都会非常感激

3 个答案:

答案 0 :(得分:0)

你在哪里调用render

另外,在你的xml中,做android:onclick = functionName,它是一个更好的,更好的方式来确保你的按钮监听器被调用

答案 1 :(得分:0)

您需要添加

android:onClick="whatevermethodthatbuttonisconnectedtoo" 
<。>在.xml文件中。我会首先尝试这样做并将方法设置为(视图视图)进行测试。

答案 2 :(得分:0)

答案可以在我提问的评论中看到。 Mike.M建议只调用setContentView()一次并取出渲染线程。当我这样做时,应用程序工作。