我在容器布局中使用片段管理器在活动中加载了一个片段。在我的活动中,我启动一项服务,连接到其他蓝牙设备,并通过发送和接收某些数据与之通信。当应用程序打开并且服务连接到蓝牙设备时,一切正常。
但是当我点击按钮并重新打开我的应用程序时,虽然我的服务仍然连接到其他蓝牙设备,我正在使用的片段显示相同的节目,它处于断开状态。 我在使用
将文本设置到我片段的子文本视图之前进行了检查fragment.isVisible()
并返回false(?)
所以,我认为如果我没有错,那么每次打开应用程序时,活动都会在原始片段上创建一个不同的片段实例。
这是我活动的onCreate()..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt_dashboard);
System.out.println("OnCreate() of BTDashboardActivity........");
if (findViewById(R.id.fragmentContainer) != null) {
if (savedInstanceState != null) {
System.out.println("ListFragmetn allready exist...");
return;
}
System.out.println("adding listfragment to view...");
listFragment = new BTDashboardListFragment();
listFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.fragmentContainer, listFragment).commit();
}
}
修改
这是活动的onStart()的代码..
@Override
public void onStart() {
super.onStart();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent,
Constants.REQUEST_ENABLE_BT);
} else {
if (mBluetoothService == null) {
startBluetoothService();
Log.d(TAG, "Chat service Started...@@@@@@@@@@@@");
showDisconnectedUI();
System.out.println("showing disconnceted status to the user..");
} else {
if (mBluetoothService.getState() == Constants.STATE_CONNECTED) {
System.out.println("showing connection status to the user..");
showConnectedUI();
} else {
System.out.println("showing disconnceted status to the user..");
showDisconnectedUI();
}
}
}
}
这是将数据设置为片段子视图的代码..
protected void handleResponse(String readMessage) {
System.out.println("response from device: " + readMessage);
if (readMessage != null) {
if (listFragment != null && listFragment.isInLayout()) {
System.out.println("List fragment is found...");
System.out.println("Setting response text to listFragment...");
if(listFragment.isVisible()) // prints not visible after reopening the app
System.out.println("listFragment is visible ...");
else
System.out.println("listFragment is not visible...");
listFragment.setResponseText(readMessage);
}
}
感谢任何帮助..
答案 0 :(得分:0)
使片段实例静态解决了我的问题。 我知道这只是一种解决方法 但现在对我来说就像是一种魅力..