The program sends data via bluetooth at each button clicked. It works on the MainActivity, but how could I achieve the same result if the Button is inside a Fragment?
I have this in Main Acitivity:
btnTimeMinus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Connection) {
connectedThread.sendData("TurnOnLedMinus");
}
else {
Toast.makeText(getApplicationContext(), "Bluetooh not conneceted", Toast.LENGTH_LONG).show();
}
}
});
In which this is called:
public void sendData(String DataSend) {
byte[] msgBuffer = DataSend.getBytes();
try {
mmOutStream.write(msgBuffer);
}
catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error: " + erro, Toast.LENGTH_LONG).show();
}
}
In other words I think I have to call "SendData" with the proper String, just like on "connectedThread.sendData("TurnOnLedMinus");" but put it inside the fragment. The problem is that there is no "Connection" or "connectThread" inside the fragment. That can only be called inside the MainActivity.
EDITED:
public class frag_light extends Fragment {
Button btAmanMenos;
ChecaBotaoClicado checaBotaoClicado;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
view = inflater.inflate(R.layout.fragment_frag_light, container, false);
btAmanMenos.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checaBotaoClicado.BotaoClicado("AmanhecerMenos");
}
});
checaBotaoClicado.BotaoClicado("AmanhecerMenos");
return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
checaBotaoClicado = (ChecaBotaoClicado)activity;
}
catch(Exception erro) {}
}
public interface ChecaBotaoClicado {
public void BotaoClicado(String DadosBotao);
}
}
The interface is working fine. If I put the "checaBotaoClicado.BotaoClicado("AmanhecerMenos");" inside the OnAttach it sends correctly. But I have plenty of buttons to add, with all sort of messages to send through Bluetooth. Why is it not working just inside a OnClick?