我正在製作一個應用程序,該應用程序正在使用片段並希望根據在與筆記本電腦通信的客戶端線程中收到的消息更改TextView中的文本。客戶端服務器通信不成問題,因爲客戶端線程正在接收字符串。嘗試從另一個線程訪問片段來更改TextView文本
我似乎無法正確計算出如何訪問碎片TextView並更改其文本。 這裏是我當前如何試圖這樣做:
class ClientThread implements Runnable {
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
LivingRoomFragment frag = (LivingRoomFragment)getSupportFragmentManager().findFragmentById(R.id.LivingRoomFragment);
frag.setText("Inside ClientThread right now");
}
});
}
}
public static class LivingRoomFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
TextView temp;
public LivingRoomFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_room_control_fragment1, container, false);
temp = (TextView) rootView.findViewById(R.id.textView5);
MainActivity main = new MainActivity();
new Thread(main.new ClientThread(requests)).start();
return rootView;
}
public void setText(String s){
temp.setText(s);
}
}
在這種情況下,MainActivity是延長FragmentActivity活動。
我正在使用模擬器,應用程序總是崩潰,說在使用frag.setText("Inside ClientThread right now")
的行上出現空指針異常,我認爲這意味着LivingRoomFragment的實例爲null。據我瞭解,這應該是使用Handler執行的,因爲如果不使用像這樣的方法,您無法從線程訪問UI。
我在做什麼錯?
您正在創建Fragments的新實例,而不是與當前Fragment進行通信。 –
好的,你如何與當前的片段進行溝通?我認爲'getFragmentById()'獲得了當前片段,但我猜它實際上是在使用該片段ID來創建一個新實例? – Toast
你是對的。使用ID創建一個新的實例,它是null,通過在開始將LivingRoomFragment提交給片段管理器時設置標記,我可以稍後使用'.getFragmentByTag(tag)'訪問該片段' – Toast