Android Fragments 在片段中调用setText方法时出现NullPointerException

u4dcyp6a  于 11个月前  发布在  Android
关注(0)|答案(1)|浏览(121)

我试图在主类的片段中设置TextView中的文本,但得到了NullPointerException。我已经在oncloud View(...)中初始化了TextView,但没有帮助。
以下是我的片段:

<?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"
        >

    <TextView
            android:text="@string/back_card"
            android:gravity="center"
            android:layout_width="217dp"
            android:layout_height="290dp"
            android:id="@+id/cardBack"
            app:layout_constraintBottom_toBottomOf="parent"
            android:layout_marginBottom="221dp"
            app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="97dp"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_marginTop="221dp"
            android:layout_marginEnd="97dp"
            app:layout_constraintEnd_toEndOf="parent"
            android:background="@drawable/bg_rounded"
            android:textSize="28sp"
            android:textColor="@color/black"
            android:fontFamily="@font/spy_font"/>
</androidx.constraintlayout.widget.ConstraintLayout>

字符串
以下是活动:

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

    <FrameLayout
            android:layout_width="317dp"
            android:layout_height="465dp"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_marginTop="1dp"
            app:layout_constraintStart_toStartOf="parent"
            android:layout_marginStart="1dp"
            app:layout_constraintBottom_toBottomOf="parent"
            android:layout_marginBottom="1dp"
            android:layout_marginEnd="1dp"
            app:layout_constraintEnd_toEndOf="parent"
            android:id="@+id/container">

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>


下面是活动代码:

public class PlayersCards extends AppCompatActivity {

    private boolean showingBack;
    public static List<Role> roles = new ArrayList<>();
    FrameLayout card;

    CardBackFragment cardBackFragment = new CardBackFragment();
    CardFrontFragment cardFrontFragment = new CardFrontFragment();

    TextView playerLabel;

    public static class CardFrontFragment extends Fragment {

        TextView roleLabel, wordLabel;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view;
            view = inflater.inflate(R.layout.fragment_card_front, container, false);

            roleLabel = (TextView) view.findViewById(R.id.roleTextView);
            wordLabel = (TextView) view.findViewById(R.id.wordTextView);

            return view;
        }

        public CardFrontFragment setRoleLabel(String text) {
            roleLabel.setText(text);

            return this;
        }

        public CardFrontFragment setWordLabel(String text) {
            wordLabel.setText(text);

            return this;
        }
    }

    public static class CardBackFragment extends Fragment {

        TextView playerLabel;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view;
            view = inflater.inflate(R.layout.fragment_card_back, container, false);
            playerLabel = (TextView) view.findViewById(R.id.cardBack);
            return view;
        }

        public CardBackFragment setPlayerLabel(String text) {
            playerLabel.setText(text);

            return this;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_players_cards);

        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.container, cardBackFragment)
                    .commit();
        }

        for (int i = 0; i < MainActivity.finalCountOfSpies; i++) {
            roles.add(Role.SPY);
        }

        for (int i = 0; i < MainActivity.finalCountOfPlayers - MainActivity.finalCountOfSpies; i++) {
            roles.add(Role.PLAYER);
        }

        Collections.shuffle(roles);

        card = findViewById(R.id.container);
        playerLabel = card.findViewById(R.id.cardBack);
        playerLabel.setText("TEXTTEXTTEXT");

        card.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flipCard();
            }
        });
    }

    private void flipCard() {
        if (showingBack) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .setCustomAnimations(
                            R.anim.card_flip_right_in,
                            R.anim.card_flip_right_out,
                            R.anim.card_flip_left_in,
                            R.anim.card_flip_left_out
                    )
                    .replace(R.id.container, cardBackFragment.setPlayerLabel("BLABLABLA"))
                    .addToBackStack(null)
                    .commit();

            showingBack = false;
        } else {
            getSupportFragmentManager()
                    .beginTransaction()
                    .setCustomAnimations(
                            R.anim.card_flip_left_in,
                            R.anim.card_flip_left_out,
                            R.anim.card_flip_right_in,
                            R.anim.card_flip_right_out
                    )
                    .replace(R.id.container, cardFrontFragment.setRoleLabel("ROLELABEL").setWordLabel("WORDWORDWORD"))
                    .addToBackStack(null)
                    .commit();

            showingBack = true;
        }
    }
}


我得到了这个错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dadry.spygame/com.name.spygame.PlayersCards}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                                                                                                        at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                                        at android.os.Looper.loop(Looper.java:164)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
                                                                                                        at com.dadry.spygame.PlayersCards.onCreate(PlayersCards.java:102)
                                                                                                        at android.app.Activity.performCreate(Activity.java:7009)
                                                                                                        at android.app.Activity.performCreate(Activity.java:7000)
                                                                                                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)


我尝试在fragment类中初始化TextView。我也尝试创建fragments对象作为Activity类的属性。没有任何变化。

pgky5nke

pgky5nke1#

第一件事是你的“架构”很糟糕。为什么你要为你的片段使用静态类?为什么不在活动之外为片段创建单独的类并将它们分开?在android开发的各个方面,它看起来都很糟糕,而且是错误的。第二件事是,playerLabel将为null,因为你不能在layout中添加fragment,然后使用container的id在fragment中找到视图。(这太疯狂了),然后要将文本设置为textView,你应该从CardBackFragment中调用setter。只需调用cardBackFragment. setPlayerLabel()。它应该可以工作。

相关问题