主要是使用handler来对ui界面进行实时更新
public class YourFragment extends Fragment {
private ListView mListView;
private YourAdapter mAdapter = new YourAdapter(getContext(), new ArrayList<YourData>()); //注意这一步的初始化如果闪退的话,可以放在onCreate方法中对适配器进行初始化
// Define a handler to handle UI updates
private Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
mAdapter.clear(); // Clear existing items from the adapter
mAdapter.addAll((List<YourData>) msg.obj); // Add new items to the adapter
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_layout,null);
// Find reference to the list view
mListView = view.findViewById(R.id.list_view);
// Set the adapter for the list view
mListView.setAdapter(mAdapter);
// Run a background thread to fetch data
new Thread(new Runnable() {
@Override
public void run() {
// Perform some background work to get a new list of data
List<YourData> newData = fetchData();
// Send the new data to the UI thread using Handler
Message message = Message.obtain();
message.obj = newData;
mHandler.sendMessage(message);
}
}).start();
return view;
}
}