147

我正在尝试将 Activity 转换为片段。上的错误标记runOnUiThread。关于过去:

GoogleActivityV2 从 Activity 扩展而来。ExecuteTask 类中的 runOnUiThread。类 ExecuteTask 嵌套在活动上。

(运行正常)现在:

GoogleActivityV2 从 Fragment 扩展而来。ExecuteTask 类中的 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
    }
}

错误说: 日食错误

我该如何解决这个错误?

4

6 回答 6

315

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

这是因为:

this1)您调用中的隐含runOnUiThread指的是AsyncTask,而不是您的片段。

2)Fragment没有runOnUiThread。

然而,Activity确实如此。

请注意,如果您已经在主线程上,则只Activity执行,否则它使用. 如果您不想担心 的上下文,可以在片段中实现 a,这实际上非常简单:RunnableHandlerHandlerthis

// 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,那已经在主线程上。

于 2013-05-07T17:35:58.707 回答
12

使用 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()
        }
    }
}
于 2020-01-09T00:16:38.563 回答
10

对于片段上的 Kotlin,只需执行此操作

activity?.runOnUiThread(Runnable {
        //on main thread
    })
于 2020-08-20T10:04:58.467 回答
4

在 Xamarin.Android 中

对于片段:

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

对于活动:

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

快乐编码:-)

于 2018-09-27T09:09:15.387 回答
2

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

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());
            }
        }
    };
}
于 2019-02-25T23:58:20.607 回答
1

您还可以使用来自任何其他线程的视图发布可运行文件。但请确保视图不为空:

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

根据文档:

“boolean post (Runnable action) 将 Runnable 添加到消息队列中。runnable 将在用户界面线程上运行。”

于 2019-11-04T05:40:09.270 回答