我有一個應用程序連接到藍牙,並從一個活動中的藍牙設備獲取數據,我想發送數據我得到的片段,我使用導航抽屜得到的片段,當我開始片段它發送數據時,創建片段,並沒有發送後,如何使片段接收數據後,它的活動變化我需要從這些更改通知我的片段,而不重新創建片段
她是我在哪裏開始片段和發送數據到片段
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
switch (id) {
case R.id.nav_car:
backgroundImageView.setVisibility(View.INVISIBLE);
//setup the car fragment
carFragment = new CarFragment();
fragmentTransaction.replace(R.id.fragment_container, carFragment);
fragmentTransaction.commit();
carFragment.sendData(recDataString.toString());
break;
}
這裏是接口
public interface sendToDataToFragment {
void sendData(String data);
}
這個片段代碼
public class CarFragment extends Fragment implements MainActivity.sendToDataToFragment {
private static final String LOG_TAG = CarFragment.class.getSimpleName();
public CarFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//address= getArguments().getString(EXTRA_DEVICE_ADDRESS);
View rootView = inflater.inflate(R.layout.fragment_car, container, false);
// Inflate the layout for this fragment
return rootView;
}
@Override
public void sendData(String data) {
if (data != null)
{
Log.e(LOG_TAG,data);
}
}
}
這裏是我從藍牙數據的代碼,我想這個數據發送到片段這些數據隨時改變
bluetoothHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
//if message is what we want
if (msg.what == handlerState) {
// msg.arg1 = bytes from connect thread
String readMessage = (String) msg.obj;
//keep appending to string until ~ char
recDataString.append(readMessage);
}
}
};
enter code here
檢查這個【答案】(http://stackoverflow.com/a/25392549/5993410)片段之間的[通信 –
可能的複製和一個活動 - 最佳實踐。](http://stackoverflow.com/questions/14247954/communicating-between-a-fragment-and-an-activity-best-practices) –
我想你的活動是你的碎片的容器。如果這是真的,只需在你想要更新的數據上創建public/protected(如果你在同一個包中)方法,然後在你的活動中調用它們,這很容易 – Catluc