片段中的runOnUiThread

时间:2013-05-07 17:32:37

标签: android android-fragments android-activity

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

  

GoogleActivityV2从Activity扩展而来。在课堂上runOnUiThread   ExecuteTask。 class ExecuteTask嵌套在activity上。

(运行确定) 现在:

  

GoogleActivityV2从Fragment扩展而来。在课堂上runOnUiThread   ExecuteTask。 class ExecuteTask嵌套在activity上。 (错误   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

我该如何解决此错误?

6 个答案:

答案 0 :(得分:229)

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

这是因为:

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

2)Fragment doesn't have runOnUiThread.

However, Activity does.

请注意,如果您已经在主线程上,Activity只执行Runnable,否则它会使用Handler。如果你不想担心this的上下文,你的片段中会You can implement a Handler,这实际上非常简单:

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

答案 1 :(得分:4)

使用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()
        }
    }
}

答案 2 :(得分:2)

对于Kotlin片段,只需这样做

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

答案 3 :(得分:1)

在Xamarin.Android中

对于片段:

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

活动:

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

快乐编码:-)

答案 4 :(得分:0)

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

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());
            }
        }
    };
}

答案 5 :(得分:0)

您还可以从任何其他线程使用该视图发布可运行项。但是请确保该视图不为空:

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

根据文档:

“布尔值发布(可运行操作) 使可运行对象添加到消息队列。可运行对象将在用户界面线程上运行。“