无法在另一个片段中设置Textview

时间:2017-03-14 06:00:20

标签: java android

我有一个PinDialogFragment,可以在输入密码时从MainActivity.java类加载。我在fragment类中创建了一个静态全局,设置为适当的Textview,然后我从MainActivity设置它。它应显示您在Textview

中留下的尝试次数

我没有获得NPE,但它没有设置任何内容,尽管它已被调用,但文本保持不变。

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");

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

1 个答案:

答案 0 :(得分:0)

在没有此类要求时,请勿使用静态字段 - Static fields are evil

在您的情况下,您可以在fragment中创建PinDialogFragment方法 -
例如:
public void updateTextView(String text) { textView.setText(text); } 创建方法: -

MainActivity

PinDialogFragment更新textView,因为您有PinDialogFragment pinDialog = PinDialogFragment.newInstance("your desired text"); pinDialog.updateTextView("Your desired text"); -

的实例
ACCESS_NETWORK_STATE);
    int FourthPermission = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_WIFI_STATE);
    int SecondPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
    int ThirdPermissionResult = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);