片段中的 runOnUiThread

我正在尝试将一个活动转换为片段。 runOnUiThread上的错误标记。 过去:

GoogleActivityV2扩展了 Activy.runOnUiThread 在类中的应用 活动上嵌套的 ExecuteTask 类。

(跑吧) 现在:

GoogleActivityV2扩展了类中的 Fragment.runOnUiThread 嵌套在活动上的 ExecuteTask 类 RunOnUiThread)

这是我的密码

public class GoogleActivityV2 extends SherlockMapFragment implements OnMapClickListener , OnMapLongClickListener , OnCameraChangeListener , TextWatcher {




@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.activity_googlev2, container, false);
Init();
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line);
textView = (AutoCompleteTextView) getView().findViewById(R.id.autoCompleteTextView1);
return rootView;
}


public void onCameraChange(CameraPosition arg0){
// TODO Auto-generated method stub
}


public void onMapLongClick(LatLng arg0){
llLoc = arg0;
stCommand = "onTouchEvent";
lp = new ExecuteTask();
lp.execute();
}


public void onMapClick(LatLng arg0){
// TODO Auto-generated method stub
}


class ExecuteTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute(){
super.onPreExecute();
if(stCommand.compareTo("AutoCompleteTextView") != 0) {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading ..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
}


protected String doInBackground(String ... args){
do something
return null;
}


@Override
protected void onPostExecute(String file_url){
if(stCommand.compareTo("AutoCompleteTextView") != 0) pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run(){
do something
}
});
}
}
public void afterTextChanged(Editable s){
// TODO Auto-generated method stub
}


public void beforeTextChanged(CharSequence s, int start, int count, int after){
// TODO Auto-generated method stub
}


public void onTextChanged(CharSequence s, int start, int before, int count){
// TODO Auto-generated method stub
}
}

错误显示: Eclipse Error

我如何修复这个错误?

141849 次浏览

试试这个: getActivity().runOnUiThread(new Runnable...

因为:

1)对 runOnUiThread的调用中隐含的 this指的是 AsyncTask,而不是片段。

2) Fragment没有运行 OnUiThread。

然而,Activity可以。

注意,如果您已经在主线程上,那么 Activity只执行 Runnable,否则它将使用 Handler。在你的片段中的 您可以实现 Handler如果你不想担心 this的上下文,它实际上非常简单:

// A class instance
private Handler mHandler = new Handler(Looper.getMainLooper());


// anywhere else in your code
mHandler.post(<your runnable>);
// ^ this will always be run on the next run loop on the main thread.

编辑:@rciovati 是对的,你在 onPostExecute,这已经在主线上了。

在 Xamarin,安卓

片段:

this.Activity.RunOnUiThread(() => { yourtextbox.Text="Hello"; });

活动:

RunOnUiThread(() => { yourtextbox.Text="Hello"; });

快乐编码: -)

我用它来获取片段中的日期和时间。

private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {


// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_head_screen, container, false);


dateTextView =  root.findViewById(R.id.dateView);
hourTv = root.findViewById(R.id.hourView);


Thread thread = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
mHandler.post(new Runnable() {
@Override
public void run() {
//Calendario para obtener fecha & hora
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");


String currentDate = date_sdf.format(currentTime);
String currentHour = hour_sdf.format(currentTime);


dateTextView.setText(currentDate);
hourTv.setText(currentHour);
}
});
}
} catch (InterruptedException e) {
Log.v("InterruptedException", e.getMessage());
}
}
};
}

还可以使用来自任何其他线程的视图发布可运行的文章。但要确保这种观点不是无效的:

 tView.post(new Runnable() {
@Override
public void run() {
tView.setText("Success");
}
});

根据文件:

”boolean post (Runnable action) 导致 Runnable 被添加到消息队列中,这个 Runnable 将在用户界面线程上运行。”

使用 Kotlin 扩展函数

fun Fragment?.runOnUiThread(action: () -> Unit) {
this ?: return
if (!isAdded) return // Fragment not attached to an Activity
activity?.runOnUiThread(action)
}

然后,在任何 Fragment中,您都可以调用 runOnUiThread,这样可以保持跨活动和片段调用的一致性。

runOnUiThread {
// Call your code here
}

注意 : 如果 Fragment不再连接到 Activity,则不会调用回调,也不会抛出异常

如果您想从任何地方访问此样式,您可以添加一个公共对象并导入该方法:

object ThreadUtil {
private val handler = Handler(Looper.getMainLooper())


fun runOnUiThread(action: () -> Unit) {
if (Looper.myLooper() != Looper.getMainLooper()) {
handler.post(action)
} else {
action.invoke()
}
}
}

为了碎片上的 Kotlin 只要这样做

activity?.runOnUiThread(Runnable {
//on main thread
})

在“ android java”中,我完美地利用了这一点:

 try {
requireActivity().runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(requireView().getContext(), msg, Toast.LENGTH_LONG);
toast.show();
}
});
} catch (Exception ignored) {
}