Android中同一片段的多个实例中的事件处理程序

时间:2015-01-15 09:22:56

标签: android android-fragments android-viewpager

我有一个由Button和TextView组成的片段。通过单击按钮,我需要更改TextView。但我需要创建该片段的18个实例并将其设置为ViewPager。我的问题是如何编写按钮处理程序。因为我单击按钮时无法更改相应的TextView。它总是改变相同页面的TextView,无论当前页面是什么。我的代码如下:

fragment_first.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.mycompany.redotgolf.FirstFragment">

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.mycompany.redotgolf.HoleRecord">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/unfilled_red_circle"
        android:id="@+id/par_button"
        android:layout_below="@+id/par_label"
        android:layout_centerHorizontal="true"
        android:gravity="center_vertical|center|center_horizontal" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/par"
        android:id="@+id/par_label"
        android:textSize="40dp"
        android:editable="false"
        android:gravity="center"
        android:layout_below="@+id/flag"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

FirstFragme.java

public class FirstFragment extends Fragment implements View.OnClickListener {
    // Store instance variables
    private String title;
    private int page;
    public ContentItem contentItem;

    public static FirstFragment newInstance(int page, String title,ContentItem contentItem) {
    FirstFragment fragmentFirst = new FirstFragment();
    fragmentFirst.contentItem=contentItem;
    Bundle args = new Bundle();
    args.putInt("someInt", page);
    args.putString("someTitle", title);
    fragmentFirst.setArguments(args);
    return fragmentFirst;
}

// Store instance variables based on arguments passed
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    page = getArguments().getInt("someInt", 0);
    title = getArguments().getString("someTitle");
}

// Inflate the view for the fragment based on layout XML
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_first, container, false);
    v.setId(page);
    View tv = v.findViewById(R.id.num_par);
    ((TextView)tv).setText(contentItem.par.toString());
    return v;
}
@Override
public void onClick(View v) {
    switch(v.getId()){
        case R.id.par_button: {
            Integer par;
            View view=getView();
            TextView textView=(TextView)view.findViewById(R.id.num_par);
            if((par=Integer.parseInt(textView.getText().toString()))<5){

                par++;
                contentItem.par++;
                textView.setText(par.toString());
            }else{
                textView.setText("3");
                contentItem.par=3;
            }
            System.out.println(par);
            break;
        }
     }
  }

}

HoleRecord.java

public class HoleRecord extends FragmentActivity {

   public FragmentPagerAdapter adapterViewPager;
   static ArrayList<ContentItem> contentItems=getSampleContent();
   @Override
   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hole_record);
       // Retrieve the ViewPager from the content view
       ViewPager vp = (ViewPager) findViewById(R.id.viewpager);

       // Set an OnPageChangeListener so we are notified when a new item is selected
       vp.setOnPageChangeListener(mOnPageChangeListener);

       // Finally set the adapter so the ViewPager can display items
        adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
        vp.setAdapter(adapterViewPager);
        vp.setCurrentItem(1);
        adapterViewPager.getItem(1);
   }


   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
       // Inflate the menu; this adds items to the action bar if it is present.
       getMenuInflater().inflate(R.menu.menu_hole_record, menu);
       return true;
   }



public static class MyPagerAdapter extends FragmentPagerAdapter {
    private static int NUM_ITEMS = 18;
    //public FirstFragment f;
    public MyPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    // Returns total number of pages
    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    // Returns the fragment to display for that page
    @Override
    public Fragment getItem(int position) {
        FirstFragment f= FirstFragment.newInstance(position, "Page"+position,contentItems.get(position));
        return f;

    }
    // Returns the page title for the top indicator
    @Override
    public CharSequence getPageTitle(int position) {
        return "Page " + position;
    }

}

/ * private final PagerAdapter mPagerAdapter = new PagerAdapter(){         LayoutInflater mInflater;

    @Override
    public int getCount() {
        //return mItems.size();
        return 10;
    }

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

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // Just remove the view from the ViewPager
        container.removeView((View) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        // Ensure that the LayoutInflater is instantiated
        if (mInflater == null) {
            mInflater =(LayoutInflater) container.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
                // Inflate item layout for images
        View iv = (View) mInflater.inflate(R.layout.score_par_view, container, false);

                // Add the view to the ViewPager
         container.addView(iv);
         return iv;

    }
};*/

/**
 * A OnPageChangeListener used to update the ShareActionProvider's share intent when a new item
 * is selected in the ViewPager.
 */
private final ViewPager.OnPageChangeListener mOnPageChangeListener
        = new ViewPager.OnPageChangeListener() {

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        // NO-OP

    }

    @Override
    public void onPageSelected(int position) {
        //setShareIntent(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        // NO-OP
    }
 };
   static ArrayList<ContentItem> getSampleContent() {
      ArrayList<ContentItem> items = new ArrayList<ContentItem>();
      for(int i=1;i<=18;i++) {
          items.add(new ContentItem(i));
       }
      return items;
  }

}

activity_hole_record.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="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.mycompany.redotgolf.HoleRecord">

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

</LinearLayout>

在上面的代码中,ContentItem类用于存储要在TextView

中显示的值

0 个答案:

没有答案