使用 Android 模拟器更新 TextView 失败

Failing at updating a TextView with Android Emulator

我正在尝试通过调用 setText() 方法来更新 TextView 对象的文本。我直接向它提供了一个字符串值,但我无法让它在模拟器上的应用 运行 的 UI 上更新。

这是在片段上发生的(在 Android Studio 上创建具有简单 activity 的项目时自动生成的片段之一)

到目前为止我的情况有几点:

简而言之,无论我尝试做什么,UI 元素都会坚持在 XML 片段文件上设置的任何字符串值(或者没有值,如果我删除 android:text 属性)。 Stack Overflow 上与此问题类似的其他帖子也没有帮助我。知道它可能是什么吗?

此外,我将发布与 java 代码相关的整个片段:

public class FirstFragment extends Fragment
{
    public Gson serializer;
    public TextView textView;

    private NetworkManager networkManager;
    private boolean serviceIsBound;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        textView = (TextView) view.findViewById(R.id.main_window);
        textView.setText(R.string.app_name);

        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    @Override
    public void onStart() {
        super.onStart();

        Intent bindIntent = new Intent(getActivity(), NetworkManager.class);
        getActivity().bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onStop()
    {
        super.onStop();
        getActivity().unbindService(serviceConnection);
        serviceIsBound = false;
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.v("DEV UPDATE", "Starting Request ");

                if (serviceIsBound)
                {
                    GetAPIStatusResult result = networkManager.GetAPIStatus();
                    if (result.GetStatus())
                    {
                        Log.v("REQUEST RESULT", "API is Fine");

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textView.setText("Service online");

                            }
                        });
                    }
                    else
                    {
                        Log.v("REQUEST RESULT", "API is Down or a problem occurred");
                        textView.setText("Service down");
                    }
                }
            }
        });
    }

    private ServiceConnection serviceConnection = new ServiceConnection()
    {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service)
        {
            NetworkManager.NetworkManagerServiceBinder binder = (NetworkManager.NetworkManagerServiceBinder) service;
            networkManager = binder.GetService();
            serviceIsBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg)
        {
            serviceIsBound = false;
        }
    };
}

片段的关联 XML:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FirstFragment">

    <TextView
        android:id="@+id/main_window"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Here will appear API status"
        app:layout_constraintBottom_toTopOf="@id/button_first"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_first"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="SendRequest"
        android:text="@string/SendRequest"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/main_window" />

    </androidx.constraintlayout.widget.ConstraintLayout>



您正在尝试引用属于 activity 的视图。如果您想更新 activity 中的某些内容,您需要查看其他方法,而不是尝试直接引用视图。

一个好的起点是传递给 activity 创建的片段的接口。当你想设置下一个时,从片段中调用接口方法。然后让 activity 处理更新。这也更干净,因为每个视图只负责自己的元素。

您也不需要使用 runOnUIThread,因为 onViewCreated 不是同步函数,您已经在 UI 线程上了。

希望对您有所帮助。

正如用户 Cheticamp 评论的那样,我的 onCreateView() 方法有问题,我在其中调用了 infalter.inflate() 方法两次,而不是 return 我的视图对象。

我用视图对象的 return 替换了第二个 inflate() 方法调用,它立即起作用了!我的 UI 现在正在按预期更新!