简体   繁体   中英

getItem function calling twice in FragmentStatePagerAdapter?

I Have a problem with getItem() function why because it is called twice in FragmentStatePagerAdapter class. Actually the main reason is in application having TextoSpeech functionality so getItem() function twice the text also speech twice. This is my code can u please assist me....Great thanks in advance.

Here is the code

This is MainActivity class:

    public class MainActivity extends FragmentActivity{

   PagerFragment pagerFragment;
   Cursor mCursor;

   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.rhymes_activity_main);

        DBUtils utils = new DBUtils(getApplicationContext());

        new DBUtils(getApplicationContext());
        try {
            DBUtils.createDatabase();
        } catch (IOException e) {
            Log.w(" Create Db "+e.toString(),"===");
        }

        DBUtils.openDatabase();
        mCursor = utils.getResult("select * from Cflviewpagerdata order by title");

        final ArrayList<PageData> myList = new ArrayList<PageData>();

        while (mCursor.moveToNext()) {
            myList.add(new PageData(mCursor.getInt(
                    mCursor.getColumnIndex("_id")), 
                    mCursor.getString(mCursor.getColumnIndex("title")),
                    mCursor.getString(mCursor.getColumnIndex("view"))));
        }
        mCursor.close();

      ListView lv = (ListView) findViewById(R.id.list_view);
      ListViewAdapter lva = new ListViewAdapter(this, R.layout.list_item, myList);
      lv.setAdapter(lva);
      lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

         public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //peace of code that create launch new fragment with swipe view inside
            PagerFragment pagerFragment = new PagerFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("CURRENT_POSITION", position);
            bundle.putParcelableArrayList("DATA_LIST", myList);
            pagerFragment.setArguments(bundle);
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction ft = fragmentManager.beginTransaction();
            ft.replace(R.id.container, pagerFragment, "swipe_view_fragment").commit();
         }
      });
      DBUtils.closeDataBase();
   }
   @Override
   public void onBackPressed() {
      FragmentManager fm = getSupportFragmentManager();
      Fragment f = fm.findFragmentByTag("swipe_view_fragment");
      if(f!=null){
         fm.beginTransaction().remove(f).commit();
      }else{
         super.onBackPressed();
      }
   }
}

This is PagerFragment class:

    public class PagerFragment extends Fragment{

       private ArrayList<PageData> data;
       private int currentPosition;
       private String mTitle;
       private FragmentActivity context;

       @Override public void onAttach(Activity activity) {
                context = (FragmentActivity) activity;
            super.onAttach(activity);
        }

       @Override
       public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          View v = inflater.inflate(R.layout.fragment_pager, container, false);
          ViewPager mViewPager = (ViewPager) v.findViewById(R.id.pager_view);
          currentPosition = getArguments().getInt("CURRENT_POSITION");
          mTitle = getArguments().getString("T_TITLE");

          data = getArguments().getParcelableArrayList("DATA_LIST");

          FragmentItemPagerAdapter fragmentItemPagerAdapter = new FragmentItemPagerAdapter(getFragmentManager(), data);
          mViewPager.setAdapter(fragmentItemPagerAdapter);
          mViewPager.setCurrentItem(currentPosition);
          return v;
       }
    }

This is FragmentItemPagerAdapter class:

public class FragmentItemPagerAdapter extends FragmentStatePagerAdapter{
   private static ArrayList<PageData> data;

   public FragmentItemPagerAdapter(FragmentManager fm, ArrayList<PageData> data){
      super(fm);
      this.data = data;
   }

   @Override
   public Fragment getItem(int position) {
      Fragment fragment = new PageFragment();
      Bundle args = new Bundle();
      args.putString(PageFragment.TITLE, data.get(position).getTitle());
      args.putString(PageFragment.DESCRIPTION, data.get(position).getDes());
      args.putInt("CURRENT_POSITION", position);
      fragment.setArguments(args);
      return fragment;
   }

   void deletePage(int position) {
        if (canDelete()) {
            data.remove(position);
            notifyDataSetChanged();
        }
    }

    boolean canDelete() {
        return data.size() > 0;
    }

   @Override
    public int getItemPosition(Object object) {
        // refresh all fragments when data set changed
        return PagerAdapter.POSITION_NONE;
    }

   @Override
   public int getCount() {
      return data.size();
   }

   public static class PageFragment extends Fragment implements OnInitListener{
      public static final String TITLE = "title";
      public static final String DESCRIPTION = "view";
      String om;

      TextToSpeech tts;

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
         Bundle savedInstanceState) {

         View rootView = inflater.inflate(R.layout.fragment_item, container, false);
         ((TextView) rootView.findViewById(R.id.item_label)).setText(getArguments().getString(TITLE));

         View tv = rootView.findViewById(R.id.item_des);

         ((TextView) tv).setText(getArguments().getString(DESCRIPTION));

         Bundle bundle = getArguments();

         int currentPosition = bundle.getInt("CURRENT_POSITION");

         tts = new TextToSpeech( getActivity(), PageFragment.this);
         om = data.get(currentPosition).getDes();
         tts.speak(om, TextToSpeech.QUEUE_FLUSH, null);

         return rootView;
      }

     @Override
      public void onDestroy() {
          if (tts != null) {
              tts.stop();
              tts.shutdown();

          }
          super.onDestroy();
      }

    public void onInit(int status) {
        // TODO Auto-generated method stub
        if (status == TextToSpeech.SUCCESS) {
            tts.speak(om, TextToSpeech.QUEUE_FLUSH, null);
        }
    }
   }
}

This is PageData class: This class is Object class

public class PageData implements Parcelable{
   private String title;
   private String view;

   public PageData(){
   }

   public PageData(Parcel in){
      title = in.readString();
      view = in.readString();
   }

   public int describeContents() {
      return 0;
   }

   public void writeToParcel(Parcel dest, int flags) {
      dest.writeString(title);
      dest.writeString(view);
   }

   public PageData(int picture, String title, String description){
      this.title = title;
      this.view = description;
   }

   public String getTitle() {
      return title;
   }

   public String getDes() {
          return view;
   }
}

This is Xml code fragment_item.xml:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:padding="8dp"
   android:orientation="vertical">

   <TextView
      android:id="@+id/item_label"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="10sp"
      android:text="Image Name"
      android:textColor="@android:color/black"
      android:textSize="18sp"
      android:layout_gravity="center_horizontal" />

   <TextView
      android:id="@+id/item_des"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="10sp"
      android:text="Image Name"
      android:textColor="@android:color/black"
      android:textSize="18sp"
      android:layout_gravity="center_horizontal" />

</LinearLayout>

This is fragment_pager.xml: This is viewpager layout

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="#ffffff">
    <android.support.v4.view.ViewPager
     android:id="@+id/pager_view"
     android:layout_width="match_parent"
     android:layout_height="match_parent" />
</FrameLayout>

This is rhymes_activity_main.xml: This is for listview of application.

    <?xml version="1.0" encoding="utf-8"?>
   <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

      <ListView android:scrollbarAlwaysDrawVerticalTrack="true"
       android:id="@+id/list_view"
       android:scrollbars="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent"/>
   </FrameLayout>

This images are my application look 申请清单 应用查看器

This image is logcat of my application Highlighted is my problem.

请检查突出显示的文字

This is my code can you please help me any one. I am new one of Android so please help

FragmentStatePagerAdapter preloads always at least 1 page. You can try to use setUserVisibleHint to handle your logic only for visible fragment:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
       // Your code
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM