Fragment 中的 ProgressBar 未在进程读取中显示

ProgressBar in Fragment not showing in proccess reading

我的ProgressBar在执行过程中不显示。

我的应用程序读取 NFC 消息。需要在阅读过程中显示ProgressBar,并在TextView中显示相关信息。读数结束后,ProgressBar消失,显示"Success"。 但这对我不起作用。

public class NFCReadFragment extends DialogFragment {

    public static final String TAG = NFCReadFragment.class.getSimpleName();

    public static NFCReadFragment newInstance() {
        return new NFCReadFragment();
    }

    private TextView mTvMessage;
    private Listener mListener;
    private ProgressBar mProgres;

    OnReadDataPass onReadDataPass;

    public interface OnReadDataPass {
        void onReadDataPass(byte[][] data);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_read,container,false);
        initViews(view);
        return view;
    }

    private void initViews(View view) {

        mTvMessage = (TextView) view.findViewById(R.id.tv_message);
        mProgres = (ProgressBar) view.findViewById(R.id.progressBarRead);
        mProgres.setVisibility(View.GONE);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mListener = (MainActivity) context;
        mListener.onDialogDisplayed();
        onReadDataPass = (OnReadDataPass) context;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener.onDialogDismissed();
    }

    public void passReadData(byte[][] data){

        onReadDataPass.onReadDataPass(data);
    }

    public void onNfcDetected(Ndef ndef){

        mProgres.setVisibility(View.VISIBLE);

        byte[][] buf = readFromNFC(ndef);
        if(buf != null) {
            passReadData(buf);
        }
    }

    private byte[][] readFromNFC(Ndef ndef) {

        mTvMessage.setText("Идёт процесс считывания");

        try {
            ndef.connect();
            NdefMessage ndefMessage = ndef.getNdefMessage();
            if(ndefMessage != null) {
                byte buf[][] = new byte[ndefMessage.getRecords().length][];
                for (int i = 0; i < ndefMessage.getRecords().length; i++) {
                    buf[i] = ndefMessage.getRecords()[i].getPayload();
                }
                Log.d(TAG, "readFromNFC: " + "success");
                mTvMessage.setText("Успешно");
                ndef.close();

                return buf;
            }

            else{
                Log.d(TAG, "readFromNFC: " + "NFC tag null");
                mTvMessage.setText("Ошибка чтения");
                return null;
            }

        } catch (IOException | FormatException e) {
            e.printStackTrace();
            mTvMessage.setText("Ошибка чтения");
            return null;
        }
        finally {
            mProgres.setVisibility(View.GONE);
        }
    }
}

xml片段

  <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="@dimen/activity_horizontal_margin">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Чтение тэга NFC"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    <ImageView
        android:id="@+id/logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/activity_horizontal_margin"
        android:src="@drawable/ic_nfc"
        android:tint="@color/colorAccent"/>

    <ProgressBar
        android:id="@+id/progressBarRead"
        style="?android:attr/progressBarStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/activity_horizontal_margin"
        android:text="Приложите телефон к метке NFC"/>
    `enter code here`  </LinearLayout>

主要活动

    public class MainActivity extends AppCompatActivity  implements Listener, 
    NFCReadFragment.OnReadDataPass {

    private Button mBtRead;
    private NFCReadFragment mNfcReadFragment;
    public static final String TAG = MainActivity.class.getSimpleName();
    private boolean isDialogDisplayed = false;
    private boolean isWrite = false;
    private NfcAdapter mNfcAdapter;


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

        initViews();
        initNFC();
    }

    private void initViews() {
        final Animation animAlpha = AnimationUtils.loadAnimation(this, 
    R.anim.anim_alfa);

        mBtRead = (Button) findViewById(R.id.button);
        mBtRead.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View view){
                view.startAnimation(animAlpha);
                showReadFragment();
            }
        });
        //  mBtRead.setOnClickListener(view -> showReadFragment());
    }

    private void initNFC(){
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
    }

    private void showReadFragment() {

        mNfcReadFragment = (NFCReadFragment) 
     getFragmentManager().findFragmentByTag(NFCReadFragment.TAG);

        if (mNfcReadFragment == null) {
            mNfcReadFragment = NFCReadFragment.newInstance();
        }
        mNfcReadFragment.show(getFragmentManager(),NFCReadFragment.TAG);

    }

    @Override
    public void onDialogDisplayed() {

        isDialogDisplayed = true;
    }

    @Override
    public void onDialogDismissed() {

        isDialogDisplayed = false;
        isWrite = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter tagDetected = new 
     IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        IntentFilter ndefDetected = new 
     IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        IntentFilter techDetected = new 
    IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        IntentFilter[] nfcIntentFilter = new IntentFilter[]{techDetected,tagDetected,ndefDetected};

        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, new Intent(this, 
    getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        if(mNfcAdapter!= null)
            mNfcAdapter.enableForegroundDispatch(this, pendingIntent, 
    nfcIntentFilter, null);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mNfcAdapter!= null)
            mNfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        Log.d(TAG, "onNewIntent: "+intent.getAction());

        if(tag != null) {
            Toast.makeText(this, getString(R.string.message_tag_detected), Toast.LENGTH_SHORT).show();
            Ndef ndef = Ndef.get(tag);

            if (isDialogDisplayed) {
                mNfcReadFragment = (NFCReadFragment)getFragmentManager().findFragmentByTag(NFCReadFragment.TAG);
                mNfcReadFragment.onNfcDetected(ndef);
            }
        }
    }

    public void transfToData(byte[][] buf){
        Intent intent = new Intent(MainActivity.this, Tabs.class);
        intent.putExtra("record_ndef", buf);

        startActivity(intent);
    }

    private byte[][] readFromNFC(Ndef ndef) {

        try {
            ndef.connect();
            NdefMessage ndefMessage = ndef.getNdefMessage();
            byte buf[][] = new byte[ndefMessage.getRecords().length][];

            //ID[i] = GetId();
            //i++;
            String f;
            for (int i = 0; i < ndefMessage.getRecords().length; i++) {
                buf[i] = ndefMessage.getRecords()[i].getPayload();
                f = new String(buf[i]);
            }

            ndef.close();

            return buf;

        } catch (IOException | FormatException e) {
            e.printStackTrace();
            return null;
        }

    }

    private String GetId(){
        Tag myTag = (Tag) getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
        String ID = bytesToHexString(myTag.getId());
        return ID;
    }

    private String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("0x");
        if(src == null || src.length <= 0){
            return null;
        }

        char[] buffer = new char[2];
        for(int i = 0; i < src.length; i++){
            buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
            buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
            System.out.println(buffer);
            stringBuilder.append(buffer);
        }

        return stringBuilder.toString();
    }

    @Override
    public void onReadDataPass(byte[][] data) {
        if(data != null) {
            Intent intent = new Intent(this, Tabs.class);
            intent.putExtra("record_ndef", data);
            startActivity(intent);
        }
    }

    @Override
    public void onBackPressed(){
        openQuitDialog();
    }

    private void openQuitDialog(){
        AlertDialog.Builder quitDialog = new AlertDialog.Builder(MainActivity.this);
        quitDialog.setTitle("Закрыть приложение?");

        quitDialog.setPositiveButton("Закрыть", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                System.runFinalization();
                System.exit(0);
            }
        });

        quitDialog.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
            }
        });

        quitDialog.show();
    }
}

需要在阅读过程中显示ProgressBar。 目前,它仅在进入第二个之前显示 activity.

您的 onNfcDetected() 方法仅在获取 NFC 详细信息后调用,而不是在读取 NFC 时调用。您可以从片段 initViews() 方法中删除 mProgres.setVisibility(View.GONE);

您经常隐藏进度条:

finally {
    mProgres.setVisibility(View.GONE);
}

因为它在每个周期都运行。 在您的代码中创建一些日志来验证它。每次将视图设置为 GONE 时,我都会添加一些 Log.d(),这样我就知道发生了什么。

为什么不在 AsyncTask 中完成所有工作并调用 View.GONE onPostExecute()?更干净了。

您可以使用

隐藏进度条

mProgres.setVisibility(View.INVISIBLE);

不要用GONE,一旦用了就不能再用这个ProgressBar了

所以,你的ProgressBar在阅读过程中不会显示。

您可以尝试以下方法:

private void initViews(View view) {
    mTvMessage = (TextView) view.findViewById(R.id.tv_message);
    mProgres = (ProgressBar) view.findViewById(R.id.progressBarRead);
    mProgres.setVisibility(View.INVISIBLE);
}