Fragment中的ProgressBar没有显示在proccess阅读中

时间:2018-03-29 07:39:49

标签: android progress-bar nfc

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

我的应用程序读取NFC消息。有必要在阅读过程中显示ProgressBar,并在TextView中显示有关它的消息。阅读完成后,ProgressBar消失,"成功"被展示。 但它对我不起作用。

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 Fragment

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

MainActivity

    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。 目前,它只在进入第二个活动之前显示。

3 个答案:

答案 0 :(得分:0)

只有在阅读NFC后才能获取NFC详细信息后,才会调用 onNfcDetected()方法。您可以从片段 initViews()方法中删除 mProgres.setVisibility(View.GONE);

答案 1 :(得分:0)

您不断隐藏进度条:

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

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

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

答案 2 :(得分:0)

您可以使用

隐藏进度条
  

mProgres.setVisibility(View.INVISIBLE);

不要使用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);
}