我正在開發從藍牙設備接收數據以便在viewpager中片段化的應用程序。 我的應用程序的過程中它Android:如何更改從MainActivity接收數據的片段中的視圖
MainActivity從藍牙設備接收數據
MainActivity的靜態字符串值改爲從藍牙設備中的數據
片段在viewpager進度在MainActivity刷新數據作爲MainActivity的數據(已更改的整數)
片段的進度條刷新數據並查看MainActivity的數據改變
public class BalanceFragment extends Fragment{ public static String data = "0"; private String old = data; private ProgressBar progressBar; private TextView textView; private Handler handler; private MyThread myThread; public BalanceFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_balance, container, false); } @Override public void onStop() { try{ myThread.stop(); } catch (Exception e){ e.printStackTrace(); } } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); progressBar = (ProgressBar) view.findViewById(R.id.progressBar); textView = (TextView) view.findViewById(R.id.balanceProgressText); myThread = new MyThread(); myThread.run(); } @Override public void onResume() { myThread.run(); } class MyThread extends Thread{ @Override public void run() { while(true) { try { this.sleep(5000); MainActivity.println("test", "test"); } catch (Exception e){ e.printStackTrace(); } if (old != data){ old = data; progressBar.setProgress(Integer.valueOf(data)); textView.setText(data); progressBar.invalidate(); textView.invalidate(); } } } } }
但是....當我啓動這個應用程序,查看被凍結...... 我不知道爲什麼我的應用程序被凍結
您不應該從單獨的線程更新視圖,這可能是錯誤行爲的原因。 – Egor