Home » Android » android – How to implement button in ViewPager?

android – How to implement button in ViewPager?

Posted by: admin May 14, 2020 Leave a comment

Questions:

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" />

How to&Answers:

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

Answer:

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;
    }

    }
}