I did it differently. My application works as follows:
After starting my application, I have MainActivity with the created HomeFragment. In HomeFragment, I have a Button and TextView for connecting / displaying BluetoothConnection status.
In HomeFragment, I implemented a handler to get information from BluetoothService. After receiving the message, I wanted to update the TextView and Button text. I created a public interface in HomeFragment using a method that receives String arguments for TextView and Button. In onAttach (Activity a), I created an mCallback object to discuss activity.
The next step implements this interface in MainActivity. From this action, I update the TextView and Button. Everything looks like this:
HomeFragment.java
public interface ViewInterface{ public void onViewUpdate(String buttonTxt, String txtTxt); } @Override public void onAttach(Activity a){ super.onAttach(a); try{ mCallback = (ViewInterface)a; }catch (ClassCastException e){ e.printStackTrace(); } } private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_STATE_CHANGE: if(true) Log.i(CLASS_TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1); switch (msg.arg1) { case BluetoothConnectionService.STATE_CONNECTED: threadTextString = "Connected to: " + connectedDeviceName; threadBtnString = "Disconnect"; mCallback.onViewUpdate(threadBtnString, threadTextString); break; case BluetoothConnectionService.STATE_CONNECTING: threadTextString = "Connecting..."; mCallback.onViewUpdate(threadBtnString, threadTextString); break; case BluetoothConnectionService.STATE_NONE: threadBtnString = "Connect"; threadTextString = "You're not connectedd"; mCallback.onViewUpdate(threadBtnString, threadTextString); break; } private void updateBtn(Button btn, String data){ btn.setText(data); Log.d(CLASS_TAG + "/" + "updateBtn", "Data: " + data); } private void updateTxt(TextView txt, String data){ txt.setText(data); Log.d(CLASS_TAG + "/" + "updateTxt", "Data: " + data); } public void update(String buttonTxt, String txtTxt){ this.updateTxt(connectTxt, txtTxt); this.updateBtn(connectButton, buttonTxt); }
MainActivity.java
@Override public void onViewUpdate(String buttonTxt, String txtTxt) { HomeFragment homeFragment = (HomeFragment)getSupportFragmentManager().findFragmentById(R.id.frame_container); if(homeFragment != null){ homeFragment.update(buttonTxt, txtTxt); } }
Pan wrona
source share