简体   繁体   中英

Can't set Textview in another fragment

I have a PinDialogFragment which loads from the MainActivity.java class when it is time to enter a password. I created a static global in the fragment class which is set to the appropriate Textview and I then set it from MainActivity . It should display the amount of attempts you have left in the Textview .

I am not getting a NPE's but it doesn't set anything and the text remains the same despite the fact that it has been called.

In MainActivity :

 final PinDialogFragment pinDialog = PinDialogFragment.newInstance(2);
    pinDialog.setCheckRsaPinCallback(new checkPin()
    {
        @Override
        public boolean checkPin(char[] pin) throws Exception
        {
            boolean pinIsCorrect = RSA.checkIfPinIsCorrect(pin);
            System.out.println("is the pin correct: " + pinIsCorrect);

            if (pinIsCorrect)
            {
                pinDialog.dismiss();
                return true;
            }
            else if (numberOfAttempts < 3) //pin is not correct
            {
                //this does nothing
                PinDialogFragment.enterPinView.setText("Incorrect Password: number of" +
                        " attempts left: " + numberOfAttempts);

                PinDialogFragment.enterPinView.invalidate();
                System.out.println("pin dialog: " + PinDialogFragment.enterPinView.getText());
                numberOfAttempts++;
                openExistingUserPinDialog();
            }
            else
            {
                //if wrong 3 times then crash the app
                android.os.Process.killProcess(android.os.Process.myPid());
            }

            return false;
        }
    });

    pinDialog.show(getFragmentManager(), "PinDialogFragment");

In PinDialogFragment :

public static TextView enterPinView;

private void initKeys(View v)
{
    editPin = (EditText) v.findViewById(R.id.edit_pin_confirm);
    enterPinView = (TextView) v.findViewById(R.id.enterPin);
    .......
}

Don't use static fields when there is no such requirement as - Static fields are evil

In your case you can create a public method in your fragment -
For example:
In your PinDialogFragment create a method:-

public void updateTextView(String text) {
    textView.setText(text);
}

Update your textView from MainActivity as you have an instance of PinDialogFragment -

PinDialogFragment pinDialog = PinDialogFragment.newInstance("your desired text");
pinDialog.updateTextView("Your desired text");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM