使用scrollview生成从数据库到viewpager布局文件的textview

时间:2018-05-10 05:16:10

标签: android

我正在创建一个文本转语音应用程序,它在viewpager中有一个滚动视图,用于选择频繁的单词和短语等。我希望选择来自数据库并在N个查询结果上生成N个textview到具有适用于每页类别的适配器的布局。

这是viewpager的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/tvTTSSlideHeading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="16dp"
    android:text="Category"
    android:textColor="@android:color/black"
    android:textSize="18sp" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="50dp">

    <LinearLayout
        android:id="@+id/TTSSLLinearLayoutMain"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginEnd="8dp"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/TTSGenerateLL"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"></LinearLayout>
    </LinearLayout>
</ScrollView>
</RelativeLayout>

这是用于更改类别的适配器

public class TTSSliderAdapter extends PagerAdapter{

Context context;
LayoutInflater layoutInflater;

public TTSSliderAdapter(Context context){
    this.context = context;
}

//Arrays
public static String[] TTSSlideCategory = {
    "POPULAR",
    "PHRASES",
    "QUESTIONS OR INQUIRIES",
    "NAMES"
};

@Override
public int getCount() {
    return TTSSlideCategory.length;
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == (RelativeLayout) object;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    View view = layoutInflater.inflate(R.layout.tts_slide_layout, container, false);

    TextView tvTTSSlideHeading = (TextView)view.findViewById(R.id.tvTTSSlideHeading);

    tvTTSSlideHeading.setText(TTSSlideCategory[position]);

    container.addView(view);

    return view;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((RelativeLayout)object);
}

}

这是主要活动

<?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"
android:background="@color/colorPrimary"
tools:context="com.example.ralph.speechhelper.TextToSpeechActivity"
android:focusable="true"
android:focusableInTouchMode="true">

<android.support.design.widget.TextInputLayout
    android:id="@+id/textInputLayout"
    android:layout_width="match_parent"
    android:layout_height="75dp"
    android:layout_marginTop="16dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/etText"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:ems="10"
        android:hint="Text to Speech"
        android:inputType="textMultiLine"
        android:maxLines="6"
        android:minLines="1" />
</android.support.design.widget.TextInputLayout>

<Button
    android:id="@+id/btnSpeak"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="31dp"
    android:layout_marginTop="17dp"
    android:background="@color/colorAccent"
    android:enabled="false"
    android:onClick="btnTTS"
    android:text="Speak"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textInputLayout" />

<Button
    android:id="@+id/btnStop"
    android:layout_width="wrap_content"
    android:layout_height="50dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="15dp"
    android:background="@color/colorAccent"
    android:enabled="false"
    android:onClick="btnTTS"
    android:text="Stop"
    app:layout_constraintEnd_toStartOf="@+id/btnClear"
    app:layout_constraintHorizontal_bias="0.472"
    app:layout_constraintStart_toEndOf="@+id/btnSpeak"
    app:layout_constraintTop_toBottomOf="@+id/textInputLayout" />

<Button
    android:id="@+id/btnClear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="28dp"
    android:layout_marginTop="17dp"
    android:background="@color/colorAccent"
    android:enabled="false"
    android:onClick="btnTTS"
    android:text="Clear"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textInputLayout" />

<android.support.v4.view.ViewPager
    android:id="@+id/TTSSlideViewPager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginBottom="8dp"
    android:layout_marginTop="8dp"
    android:background="@color/colorAccent"
    app:layout_constraintBottom_toTopOf="@+id/TTSDotsLayout"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/btnStop"
    app:layout_constraintVertical_bias="0.0">

</android.support.v4.view.ViewPager>

<LinearLayout
    android:id="@+id/TTSDotsLayout"
    android:layout_width="100dp"
    android:layout_height="40dp"
    android:layout_marginEnd="206dp"
    android:layout_marginStart="205dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    android:gravity="center">

</LinearLayout>

</android.support.constraint.ConstraintLayout>

这是示例数据库和表

db = openOrCreateDatabase("SpeechHelperDB",Context.MODE_PRIVATE,null);
    db.execSQL("CREATE TABLE IF NOT EXISTS ttschoicestb(ttschoice_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, ttschoice VARCHAR, ttscategory VARCHAR);");
    db.execSQL("DELETE FROM ttschoicestb");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('Hello World','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('Good Bye','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('Good Morning','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('Good Afternoon','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('Good Evening','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('My name is Ralph Francis Pon-an','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('What a wonderful day','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('Good Evening','POPULAR');");

这是生成选择的功能

public void generateTTSChoices(){
    try {
        Cursor c = db.rawQuery("SELECT * FROM ttschoicestb WHERE ttscategory ='" + ttsSliderAdapter.TTSSlideCategory[currCategory] + "'", null);
        if (c.moveToFirst()) {
            Toast.makeText(TextToSpeechActivity.this, "Generating Choices", Toast.LENGTH_SHORT).show();
            generatedTextView = new TextView(this);
            generatedTextView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT));
            generatedTextView.setText(c.getString(1));
            generatedTextView.setTextSize(14);
            generatedTextView.setGravity(Gravity.CENTER);
            generatedTextView.setBackgroundColor(getResources().getColor(R.color.colorHoloBlueBright));
            generatedTextView.setOnClickListener(TTSChoices);
            TTSGenerateLL.addView(generatedTextView);
        }
    }
    catch (Exception ex){
        Toast.makeText(TextToSpeechActivity.this, "Error Generating Choices", Toast.LENGTH_SHORT).show();
    }
}

应用程序在生成选择阶段时崩溃,所以我尝试了一下try and toast来确定问题。

请帮我找到解决方案,为viewpager生成选择。

感谢提前!! :)

这是ex.printStackTrace();

时的错误
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference
W/System.err:     at com.example.ralph.speechhelper.TextToSpeechActivity.generateTTSChoices(TextToSpeechActivity.java:317)
W/System.err:     at com.example.ralph.speechhelper.TextToSpeechActivity$3.onPageSelected(TextToSpeechActivity.java:294)
W/System.err:     at android.support.v4.view.ViewPager.dispatchOnPageSelected(ViewPager.java:1939)
W/System.err:     at android.support.v4.view.ViewPager.scrollToItem(ViewPager.java:679)
W/System.err:     at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:663)
W/System.err:     at android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2255)
W/System.err:     at android.view.View.dispatchTouchEvent(View.java:8471)
W/System.err:     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2399)
W/System.err:     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2092)
W/System.err:     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
W/System.err:     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
W/System.err:     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
W/System.err:     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
W/System.err:     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
W/System.err:     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
W/System.err:     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
W/System.err:     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
W/System.err:     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
W/System.err:     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
W/System.err:     at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2405)
W/System.err:     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2106)
W/System.err:     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2369)
W/System.err:     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1719)
W/System.err:     at android.app.Activity.dispatchTouchEvent(Activity.java:2742)
W/System.err:     at android.support.v7.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:68)
W/System.err:     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2330)
W/System.err:     at android.view.View.dispatchPointerEvent(View.java:8666)
W/System.err:     at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4123)
W/System.err:     at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3989)
W/System.err:     at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
W/System.err:     at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
W/System.err:     at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
W/System.err:     at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3680)
W/System.err:     at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
W/System.err:     at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3737)
W/System.err:     at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
W/System.err:     at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3597)
W/System.err:     at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3563)
W/System.err:     at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3571)
W/System.err:     at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3544)
W/System.err:     at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5807)
W/System.err:     at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5781)
W/System.err:     at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5752)
W/System.err:     at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5897)
W/System.err:     at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
W/System.err:     at android.os.MessageQueue.nativePollOnce(Native Method)
W/System.err:     at android.os.MessageQueue.next(MessageQueue.java:143)
W/System.err:     at android.os.Looper.loop(Looper.java:122)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5254)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at java.lang.reflect.Method.invoke(Method.java:372)
W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

这是texttospeechactivity的所有代码,它是主要的活动

package com.example.ralph.speechhelper;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Locale;

public class TextToSpeechActivity extends AppCompatActivity{

EditText ettext;
TextToSpeech TTS;
int result;
String text, language;
Button btnSpeak, btnStop, btnClear;
float pitch, speed;
SharedPreferences sharedPref;

ViewPager TTSSlideViewPager;
LinearLayout TTSDotsLayout;
TTSSliderAdapter ttsSliderAdapter;
TextView[] TTSDots;
int currCategory=0;

//Linear layout of ttsslidelayout
LinearLayout TTSGenerateLL;
TextView generatedTextView;

SQLiteDatabase db;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_text_to_speech);
    getSupportActionBar().setTitle("Text to Speech");

    //database
    db = openOrCreateDatabase("SpeechHelperDB",Context.MODE_PRIVATE,null);
    db.execSQL("CREATE TABLE IF NOT EXISTS ttschoicestb(ttschoice_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, ttschoice VARCHAR, ttscategory VARCHAR);");
    db.execSQL("DELETE FROM ttschoicestb");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('Hello World','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('Good Bye','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('Good Morning','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('Good Afternoon','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('Good Evening','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('My name is Ralph Francis Pon-an','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('What a wonderful day','POPULAR');");
    db.execSQL("INSERT INTO ttschoicestb(ttschoice,ttscategory) VALUES('Good Evening','POPULAR');");

    ettext = (EditText)findViewById(R.id.etText);
    btnSpeak = (Button)findViewById(R.id.btnSpeak);
    btnStop = (Button)findViewById(R.id.btnStop);
    btnClear = (Button)findViewById(R.id.btnClear);

    TTSSlideViewPager = findViewById(R.id.TTSSlideViewPager);
    TTSDotsLayout = findViewById(R.id.TTSDotsLayout);

    ttsSliderAdapter = new TTSSliderAdapter(this);
    TTSSlideViewPager.setAdapter(ttsSliderAdapter);

    //Linear layout of ttsslidelayout
    TTSGenerateLL = (LinearLayout)findViewById(R.id.TTSGenerateLL);

    addDotsIndicator(0);
    TTSSlideViewPager.addOnPageChangeListener(viewListener);


    sharedPref = getSharedPreferences("myPref", 0);

    //generateTTSChoices();

    //Check if Google TTS is Installed and will install if not
    if(isPackageInstalled(getPackageManager(), "com.google.android.tts")){
        boolean ttsInstalled = true; // This would be good to have it as a static member
    }
    else{
        installTTSDialog();
    }

    //Text to speech
    TTS = new TextToSpeech(TextToSpeechActivity.this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if(status == TextToSpeech.SUCCESS){
                result = TTS.setLanguage(Locale.UK);
            }
            else{
                Toast.makeText(TextToSpeechActivity.this, "Feature not supported on your device", Toast.LENGTH_LONG).show();
            }
        }
    });

    //Button State change
    ettext.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if(ettext.getText().toString().equals("")){
                btnClear.setEnabled(false);
                btnSpeak.setEnabled(false);
                btnStop.setEnabled(false);
            }
            else{
                btnClear.setEnabled(true);
                btnSpeak.setEnabled(true);
                btnStop.setEnabled(true);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });
}

//TTS engine checker
public static boolean isPackageInstalled(PackageManager pm, String packageName) {
    try {
        pm.getPackageInfo(packageName, 0);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
    return true;
}


//3 Dots Options menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()){
        case R.id.mitem1:
            Intent settingsIntent = new Intent(this, Settings.class);
            /*settingsIntent.putExtra("pitchProg", pitch);
            settingsIntent.putExtra("speedProg", speed);*/
            startActivityForResult(settingsIntent, 1);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

//TTS languages
private void ttsLanguage() {
    switch (language){
        case "English (United Kingdom)":
            TTS.setLanguage(Locale.UK);
            break;
        case "English (United States)":
            TTS.setLanguage(Locale.US);
            break;
        case "Spanish":
            Locale SPAIN = new Locale ("spa", "ESP");
            TTS.setLanguage(SPAIN);
            break;
        case "France":
            TTS.setLanguage(Locale.FRANCE);
            break;
        case "German":
            TTS.setLanguage(Locale.GERMAN);
            break;
        case "Italian":
            TTS.setLanguage(Locale.ITALIAN);
            break;
        case "Filipino":
            TTS.setLanguage(new Locale("fil_PH"));
        default:
            TTS.setLanguage(Locale.UK);
            break;
    }
}

//Buttons Funtions
public void btnTTS(View v){
    switch (v.getId()){
        case R.id.btnSpeak:
            if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
                Toast.makeText(TextToSpeechActivity.this, "Feature not supported on your device", Toast.LENGTH_LONG).show();
            }
            else{
                pitch = sharedPref.getFloat("pitch", 1);
                speed = sharedPref.getFloat("speed", 1);
                language = sharedPref.getString("language", "UK");
                text = ettext.getText().toString();
                TTS.setPitch(pitch);
                TTS.setSpeechRate(speed);
                ttsLanguage();
                TTS.speak(text,TextToSpeech.QUEUE_FLUSH, null);
            }
            break;
        case R.id.btnStop:
            if (TTS != null){
                TTS.stop();
            }
            break;
        case R.id.btnClear:
            if (!ettext.getText().toString().equals("")){
                ettext.setText("");
            }
            break;
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if(TTS!=null){
        TTS.stop();
        TTS.shutdown();
    }
}

//Page Dots
public void addDotsIndicator(int position) {
    TTSDots = new TextView[ttsSliderAdapter.TTSSlideCategory.length];
    TTSDotsLayout.removeAllViews();

    for (int i = 0; i < TTSDots.length; i++) {
        TTSDots[i] = new TextView(this);
        TTSDots[i].setText(Html.fromHtml("&#8226;"));
        TTSDots[i].setTextSize(35);
        TTSDots[i].setTextColor(getResources().getColor(R.color.colorTransparentWhite));

        TTSDotsLayout.addView(TTSDots[i]);
    }

    if (TTSDots.length > 0) {
        TTSDots[position].setTextColor(getResources().getColor(R.color.colorWhite));
    }
}

ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        addDotsIndicator(position);
        currCategory = position;
        Toast.makeText(TextToSpeechActivity.this, currCategory+ "\n" + ttsSliderAdapter.TTSSlideCategory[currCategory], Toast.LENGTH_SHORT).show();
        generateTTSChoices();
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
};

//Generate TTS Choices
public void generateTTSChoices(){
    try {
        Cursor c = db.rawQuery("SELECT * FROM ttschoicestb WHERE ttscategory ='" + ttsSliderAdapter.TTSSlideCategory[currCategory] + "'", null);
        if (c.moveToFirst()) {
            Toast.makeText(TextToSpeechActivity.this, "Generating Choices", Toast.LENGTH_SHORT).show();
            generatedTextView = new TextView(this);
            generatedTextView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT));
            generatedTextView.setText(c.getString(1));
            generatedTextView.setTextSize(14);
            generatedTextView.setGravity(Gravity.CENTER);
            generatedTextView.setBackgroundColor(getResources().getColor(R.color.colorHoloBlueBright));
            generatedTextView.setOnClickListener(TTSChoices);
            TTSGenerateLL.addView(generatedTextView);
        }
    }
    catch (Exception ex){
        Toast.makeText(TextToSpeechActivity.this, "Error Generating Choices", Toast.LENGTH_SHORT).show();
        ex.printStackTrace();
    }
}


//TTS Choices Clicked
private View.OnClickListener TTSChoices = new View.OnClickListener() {
    public void onClick(View v) {
        TextView tv = findViewById(v.getId());
        //Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show();
        ettext.setText(tv.getText().toString());
        pitch = sharedPref.getFloat("pitch", 1);
        speed = sharedPref.getFloat("speed", 1);
        language = sharedPref.getString("language", "UK");
        text = ettext.getText().toString();
        TTS.setPitch(pitch);
        TTS.setSpeechRate(speed);
        ttsLanguage();
        TTS.speak(tv.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
    }
};

//Install TTS Engine Dialog
public void installTTSDialog(){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Install High Quality Voice");
    builder.setMessage("Recommended Text To Speech Engine is not Installed, Please Manually Install It");
    builder.setPositiveButton("Install", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            try {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + "com.google.android.tts")));
            } catch (android.content.ActivityNotFoundException anfe) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + "com.google.android.tts")));
            }
        }
    });
    builder.setNegativeButton("Use Default", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // do nothing
        }
    });
    builder.setIcon(android.R.drawable.ic_dialog_alert);
    AlertDialog dialog = builder.create();
    dialog.show();
    Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
    Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
    positiveButton.setTextColor(Color.parseColor("#ff4081"));
    negativeButton.setTextColor(Color.parseColor("#ff4081"));
}

}

0 个答案:

没有答案