如何从Android片段更新XML TextView?

3
我正在尝试从FragmentActivity中更新片段的TextView文本。在else语句中,我首先创建了一个Fragment,然后使用属于该片段的updateItemView()方法更新TextView,但是我得到的结果是空指针异常。

我可以从if语句中更新TextView,但为什么无法从else语句中更新TextView

这是FragmentActivity的代码:

public void toDeatailsBtn(View view){

    ItemFragment listFragment = (ItemFragment) getSupportFragmentManager()
    .findFragmentById(R.id.large_layout_list_item_fragment);

    if(listFragment != null){
        //The "if" code is working.
        listFragment.updateItemView();
    }

    // I'm swaping fragments here. I already added firstFragment to the
    //fragment_container FrameLayout in other code.
    else{
        ItemFragment secondFragment = new ItemFragment();
        FragmentTransaction transaction =
        getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, secondFragment);

        transaction.addToBackStack(null);
        transaction.commit();

        //This is giving me the null pointer exception, even though
        //secondFragment has been created in theory.
        secondFragment.updateItemView();
    }
}

包含 updateItemView() 方法的 Fragment:

public class ItemFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
        return inflater.inflate(R.layout.item_fragment, container, false);
    }

    public void updateItemView(){
        TextView name = (TextView) getActivity()
        .findViewById(R.id.list_item_fragment);
        name.setText("TEST");
    }
}

The TextView:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/list_item_fragment"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:freezesText="true" />
    </LinearLayout>
</ScrollView>

最后,我使用的FrameLayout来替换片段:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".MainFragmentActivity" />

错误日志:

01-06 00:59:08.425: E/AndroidRuntime(1610): java.lang.IllegalStateException: Could not execute method of the activity
01-06 00:59:08.425: E/AndroidRuntime(1610):     at android.view.View$1.onClick(View.java:3591)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at android.view.View.performClick(View.java:4084)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at android.view.View$PerformClick.run(View.java:16966)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at android.os.Handler.handleCallback(Handler.java:615)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at android.os.Looper.loop(Looper.java:137)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at android.app.ActivityThread.main(ActivityThread.java:4745)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at java.lang.reflect.Method.invokeNative(Native Method)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at java.lang.reflect.Method.invoke(Method.java:511)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at dalvik.system.NativeStart.main(Native Method)
01-06 00:59:08.425: E/AndroidRuntime(1610): Caused by: java.lang.reflect.InvocationTargetException
01-06 00:59:08.425: E/AndroidRuntime(1610):     at java.lang.reflect.Method.invokeNative(Native Method)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at java.lang.reflect.Method.invoke(Method.java:511)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at android.view.View$1.onClick(View.java:3586)
01-06 00:59:08.425: E/AndroidRuntime(1610):     ... 11 more
01-06 00:59:08.425: E/AndroidRuntime(1610): Caused by: java.lang.NullPointerException
01-06 00:59:08.425: E/AndroidRuntime(1610):     at com.site.myapp.ItemFragment.updateItemView(ItemFragment.java:27)
01-06 00:59:08.425: E/AndroidRuntime(1610):     at com.site.myapp.MainFragmentActivity.toDetailsBtn(MainFragmentActivity.java:90)
01-06 00:59:08.425: E/AndroidRuntime(1610):     ... 14 more
2个回答

0
myFragment 类中编写一个静态方法:
public static myFragment newInstance(String txt) {
        myFragment myfragment = new myFragment();

        Bundle args = new Bundle();
        args.putString("TEXT", txt);
        myfragment.setArguments(args);

        return myfragment;
    }

myFragment类的OnCreate方法中,首先使用inflate来创建textView tv
tv.setText(getArguments().getString("TEXT"));

在主要的FragmentActivity类中执行以下操作:
myFragment fragment = myFragment.newInstance(textToBeSent);

replace之前,

fragmentTransaction.replace(R.id.fr_dynamic, fragment);
fragmentTransaction.commit();

0

当您调用commit时,Fragment事务并不会立即完成,因此当您调用updateItemView()时无法立即找到TextView。尝试使用{{link1:FragmentManager.executePendingTransaction()}}来强制执行事务:

//...
transaction.addToBackStack(null);
transaction.commit();
getSupportFragmentManager().executePendingTransaction();
secondFragment.updateItemView();

只是想知道为什么在 commit() 后事务没有立即完成。 - user1952398
@user1952398 这就是 Fragment 系统的设计方式,异步执行。此外,你可能只需要从其中一个 Fragment 的回调函数中调用 updateItemView,而不是从外部调用,因为调用该方法更像是一个初始化过程。我不明白为什么你的问题会被投票降低,它提问得很好,而且你还提供了相关的代码和异常堆栈跟踪信息。 - user

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接