代码之家  ›  专栏  ›  技术社区  ›  Egor Vasilyev

进程读取中未显示片段中的ProgressBar

  •  0
  • Egor Vasilyev  · 技术社区  · 7 年前

    我的 ProgressBar 在流程执行期间不显示。

    我的应用程序读取NFC消息。有必要显示 进度条 在阅读过程中,并在 TextView 关于它。阅读完成后, 进度条 消失并显示“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();
        }
    }
    

    有必要显示 进度条 在阅读过程中。 目前,它仅在进入第二个活动之前显示。

    3 回复  |  直到 7 年前
        1
  •  0
  •   Zayid Mohammed    7 年前

    你的 onNfcDetected() 方法仅在获取NFC详细信息后调用,而不是在读取NFC时调用。您可以删除 M程序。设置可见性(View.GONE); 来自片段 initViews() 方法

        2
  •  0
  •   Luís Henriques    7 年前

    您经常通过以下方式隐藏进度条:

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

    因为它在每个循环中运行。 在代码中创建一些日志以进行验证。我会添加一些日志。d()每次我都将视图设置为“消失”,以便知道发生了什么。

    为什么不在AsyncTask和call视图中完成所有工作。onPostExecute()?它干净多了。

        3
  •  0
  •   milkdz    7 年前

    可以使用隐藏进度条

    M程序。设置可见性(视图不可见);

    不要用GONE ,一旦使用它,下一步就不能使用此ProgressBar。

    因此,ProgressBar不会显示在procress阅读中。

    您可以尝试以下操作:

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