11

I have a ViewPager and I need to use a button there. Button has to recognize the voice, and show it in a TextView. I implement the same layout for VoiceRecognition and for ViewPager.

The question is: how to activate button to run VoiceRecognition after click. I try to set a tag on a Button and TextView, but I do this wrong, it doesn't work.

ViewPager:

public class SwipeAdapter extends PagerAdapter{

private int[] car = {R.string.car1, R.string.car2,
        R.string.car3, R.string.car4, R.string.car5};
private Context context;
private LayoutInflater layoutInflater;

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

@Override
public int getCount() {
    return car.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 itemView = layoutInflater.inflate(R.layout.carSwipe, container, false);

    //Implement the Button

    Button carBut = (Button)itemView.findViewById(R.id.buttonCar);
    carButton.setTag("car");

     TextView textView = (TextView) itemView.findViewById(R.id.interTextView);
textView.setTag("text");
    textView.setText(car[position]);
    container.addView(itemView);
    return itemView;
}

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

Voice Recognition

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.carSwipe);
    Button recognizeButton = (Button)findViewById(R.id.button1);
    recognizeButton.setOnClickListener(this);
}

@Override
public void setContentView(View context) {
    final DisplayMetrics dm = context.getResources().getDisplayMetrics();
    final Configuration conf = context.getResources().getConfiguration();
    conf.locale = new Locale("en");
    context.getResources().updateConfiguration(conf, dm);
}

@Override
public void onClick(View v) {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "You may speak!");
    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
    startActivityForResult(intent, 1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1 && resultCode == RESULT_OK) {
        ArrayList<String> results;
        results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

        //Set a tag here
        TextView speechText = (TextView) mPager.findViewWithTag("text" + results);
        String str="";
        for(int i=0;i<results.size();i++){
            str+= results.get(i);
        }
        speechText.setText(str);
    }
}
}

xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:gravity="center|center_horizontal"
    android:id="@+id/linearLayout">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/interTextView" />
</LinearLayout>

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="recognition"
    android:id="@+id/buttonRec"
    android:layout_above="@+id/linearLayout"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

trincot
  • 317,000
  • 35
  • 244
  • 286
JohnPix
  • 1,595
  • 21
  • 44
  • Does the speech recognition work on its own without the viewpager? Like can you log the words it recognized? – OneCricketeer Nov 12 '15 at 04:09
  • Is it an option to switch to using fragments? You can then extend from FragmentStatePagerAdapter and just return the correct fragment in "getItem(int position)". That fragment can then easily start the correct activity when the button is pressed and respond to the result. – Jeroen Mols Nov 18 '15 at 14:03
  • Have a look at this tutorial: https://developer.android.com/training/animation/screen-slide.html (SubClassing PagerAdapter is much harder than simply using FragmentStatePagerAdapter or FragmentPagerAdapter and hence not a recommended approach) – Jeroen Mols Nov 18 '15 at 14:06

2 Answers2

1

You can find view with required tag inside onActivityResult and modify it as required:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1 && resultCode == RESULT_OK) {
         .... Get required ID
         TextView linearLayout=(TextView) pager.findViewWithTag("page" + requiredId);
         ..... preform required chagnes
    }
}

You need to set the tags when you instantiate:

public Object instantiateItem(ViewGroup container, int position) {
      ....
      textView.setTag("page" + position);
      ....
}

How to access views from view pager

Community
  • 1
  • 1
Nikolay Shmyrev
  • 24,897
  • 5
  • 43
  • 87
1

You can have onClickListener inside instantiateItem method only.

import android.view.View.OnClickListener;

public class SwipeAdapter extends PagerAdapter{

private int[] car = {R.string.car1, R.string.car2,
    R.string.car3, R.string.car4, R.string.car5};
private Context context;
private LayoutInflater layoutInflater;
private final int REQ_CODE_SPEECH_INPUT = 100;
public SwipeAdapter(Context context){
    this.context = context;
}

@Override
public int getCount() {
   return car.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 itemView = layoutInflater.inflate(R.layout.carSwipe, container, false);

//Implement the Button

    Button carBut = (Button)itemView.findViewById(R.id.buttonCar);
    carBut.setTag("car");

    TextView textView = (TextView) itemView.findViewById(R.id.interTextView);
    textView.setTag("text");
    textView.setText(car[position]);
    container.addView(itemView);

     carBut.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Log.d("pager position", ""+position);

                    //do onClick event stuff here!!
            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
            intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"You may Speak!!");
            try {
            context.startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
             } catch (ActivityNotFoundException a) {
                Toast.makeText(context,"Speech not supported!!",
                Toast.LENGTH_SHORT).show();
                  }
                }
                });         

    return itemView;

}

Then onActivityResult may look like this.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
    case REQ_CODE_SPEECH_INPUT: {
        if (resultCode == RESULT_OK && null != data) {

            ArrayList<String> result = data
                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            Log.d("SPEECHINPUT",""+result.get(0));

        }
        break;
    }

    }
}
  • Thank's for your answer! But what do you mean by saying: `//do onClick event stuff here!!`? What should I put there? I try to implement here `onClick` method from `VoiceRecognition`, but it underscore `startActivityForResult`. – JohnPix Nov 17 '15 at 13:29
  • When I run it without implementing (like in your example) it crashes. Log: `java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setTag(java.lang.Object)' on a null object reference` – JohnPix Nov 17 '15 at 13:30
  • The button name is invalid, reason for the null object reference. Change the button name from "carButton" to ""carBut" at the line carButton.setTag("car"); – Devendra Vaja Nov 17 '15 at 22:52