首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法更改进度条的可见性

无法更改进度条的可见性
EN

Stack Overflow用户
提问于 2018-06-03 02:04:51
回答 1查看 539关注 0票数 0

我已经看过与这个问题相关的所有其他问题,但似乎都没有帮助。我想要实现的一切,非常非常简单。

我希望在OnCreate()方法中将不确定进度条的可见性更改为不可见。但出于某种原因,我一直在买NullPointerException。是的,我使用了正确的id来引用进度条。

public class MainActivity extends Activity implements
    RecognitionListener {

private static TextView txt;
ProgressBar pb;

/* Named searches allow to quickly reconfigure the decoder */
private static final String KWS_SEARCH = "wakeup";

/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "hey iris";


/* Used to handle permission request */
private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1;

private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;

@Override
public void onCreate(Bundle state) {
    super.onCreate(state);
    setContentView(R.layout.activity_main);
    txt = (TextView) findViewById(R.id.result_text);

    pb = (ProgressBar) findViewById(R.id.pbar);
    pb.setVisibility(View.GONE);
    System.out.println(pb.getVisibility());

    captions = new HashMap<>();
    captions.put(KWS_SEARCH, R.string.kws_caption);
    setContentView(R.layout.activity_main);

    ((TextView) findViewById(R.id.caption_text))
            .setText("Preparing the application");

    // Check if user has given permission to record audio
    int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
        return;
    }
    // Recognizer initialization is a time-consuming and it involves IO,
    // so we execute it in async task
    new SetupTask(this).execute();
}

private static class SetupTask extends AsyncTask<Void, Integer, Exception> {
    WeakReference<MainActivity> activityReference;
    SetupTask(MainActivity activity) {
        this.activityReference = new WeakReference<>(activity);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        System.out.println(values[0]);
    }

    @Override
    protected Exception doInBackground(Void... params) {
        try {
            Assets assets = new Assets(activityReference.get());
            File assetDir = assets.syncAssets();
            activityReference.get().setupRecognizer(assetDir);
        } catch (IOException e) {
            return e;
        }
        return null;
    }
    @Override
    protected void onPostExecute(Exception result) {
        if (result != null) {
            ((TextView) activityReference.get().findViewById(R.id.caption_text))
                    .setText("Failed to init recognizer " + result);
        } else {
            activityReference.get().switchSearch(KWS_SEARCH);
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       @NonNull String[] permissions, @NonNull  int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == PERMISSIONS_REQUEST_RECORD_AUDIO) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Recognizer initialization is a time-consuming and it involves IO,
            // so we execute it in async task
            new SetupTask(this).execute();
        } else {
            finish();
        }
    }
}

@Override
public void onDestroy() {
    super.onDestroy();

    if (recognizer != null) {
        recognizer.cancel();
        recognizer.shutdown();
    }
}

/**
 * In partial result we get quick updates about current hypothesis. In
 * keyword spotting mode we can react here, in other modes we need to wait
 * for final result in onResult.
 */
@Override
public void onPartialResult(Hypothesis hypothesis) {
    if (hypothesis == null)
        return;

    String text = hypothesis.getHypstr();
    if (text.equals(KEYPHRASE)) {
        recognizer.stop();
        Intent intent = new Intent(this, ListenActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity ( intent );
        recognizer.cancel();
        recognizer.shutdown();
        finish();
    }

}

/**
 * This callback is called when we stop the recognizer.
 */
@Override
public void onResult(Hypothesis hypothesis) {
    ((TextView) findViewById(R.id.result_text)).setText("");
    if (hypothesis != null) {

    }
}

@Override
public void onBeginningOfSpeech() {
}

/**
 * We stop recognizer here to get a final result
 */
@Override
public void onEndOfSpeech() {
    if (!recognizer.getSearchName().equals(KWS_SEARCH))
        switchSearch(KWS_SEARCH);
}

private void switchSearch(String searchName) {
    recognizer.stop();

    // If we are not spotting, start listening with timeout (10000 ms or 10 seconds).
    if (searchName.equals(KWS_SEARCH))
        recognizer.startListening(searchName);
    else
        recognizer.startListening(searchName, 1000);

    String caption = getResources().getString(captions.get(searchName));
    ((TextView) findViewById(R.id.caption_text)).setText(caption);

}

private void setupRecognizer(File assetsDir) throws IOException {
    // The recognizer can be configured to perform multiple searches
    // of different kind and switch between them

    recognizer = SpeechRecognizerSetup.defaultSetup()
            .setAcousticModel(new File(assetsDir, "en-us-ptm"))
            .setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
            .getRecognizer();
    recognizer.addListener(this);

    /* In your application you might not need to add all those searches.
      They are added here for demonstration. You can leave just one.
     */

    // Create keyword-activation search.
    recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);

}

@Override
public void onError(Exception error) {
    ((TextView) findViewById(R.id.caption_text)).setText(error.getMessage());
}

@Override
public void onTimeout() {
    switchSearch(KWS_SEARCH);
}
}

activity_main

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context=".MainActivity">

<TextView
    android:id="@+id/result_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="@android:color/darker_gray"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/caption_text"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/caption_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="481dp"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:typeface="sans"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<ProgressBar
    android:id="@+id/pbar"
    style="?android:attr/progressBarStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:layout_editor_absoluteX="167dp"
    tools:layout_editor_absoluteY="258dp" />

</android.support.constraint.ConstraintLayout>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-03 02:07:38

您忘记在pb = (ProgressBar) findViewById(R.id.pbar);之前添加setContentView(R.layout.layoutWithProgressbar)

public class MainActivity extends Activity implements
    RecognitionListener {

    ProgressBar pb;

    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        setContentView(R.layout.layoutWithProgressbar);
        //^^^^^^^^^^^^^^^^^^^
        // without this, there is no layout or view hierarchy
        // attached with the MainActivity
        // or probably setContentView(R.layout.main_activity);
        pb = (ProgressBar) findViewById(R.id.pbar);
        //pb.setVisibility(View.INVISIBLE);
        pb.setVisibility(View.GONE);

    }
}

另一个问题是,您再次将布局重置为相同的新状态

setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.result_text);

pb = (ProgressBar) findViewById(R.id.pbar);
pb.setVisibility(View.GONE);
System.out.println(pb.getVisibility());

captions = new HashMap<>();
captions.put(KWS_SEARCH, R.string.kws_caption);
//setContentView(R.layout.activity_main); remove this
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50659748

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档