我正在尝试分享我在viewpager上点击按钮时显示的文字,但是它正在从下一页发送文本。就像在viewpager的第一页上一样,它显示了' 0'当我将它分享到什么应用程序或短信时,它发送文本' 1'即字符串数组中的下一个文本 这是我的代码。
SampleFragmant.java
public class SampleFragmant extends Fragment {
ViewPager viewPager;
SampleAdapter adapter;
ImageView shareButton, saveButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sample,
container, false);
viewPager = (ViewPager) rootView
.findViewById(R.id.view_pager);
shareButton = (ImageView) rootView.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent sharingIntent = new Intent(
android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = adapter.textposition;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Test Application:");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,
shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
adapter = new SampleAdapter(getActivity());
viewPager.setAdapter(adapter);
return rootView;
}
}
SampleAdapter.java
public class SampleAdapter extends PagerAdapter {
Context context;
public String textposition;
private String[] textToDisplay = new String[] {
"0","1","2","3","4","5","6"};
@Override
public int getCount() {
// TODO Auto-generated method stub
return textToDisplay.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view == ((TextView) object);
}
@Override
public Object instantiateItem(View container, int position) {
// TODO Auto-generated method stub
TextView textView = new TextView(context);
textView.setText(textToDisplay[position]);
textposition= textToDisplay[position];
textView.setTextSize(16);
textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setGravity(Gravity.CENTER);
((ViewPager) container).addView(textView, 0);
return textView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((TextView) object);
}
}
答案 0 :(得分:0)
默认情况下,ViewPager会一次创建多个视图。例如,如果向用户显示位置为5的视图,则会创建位置为4,5和6的视图。这是平滑过渡动画所需,并由setOffscreenPageLimit(int limit)控制(默认限制为1)。因此,它将通过调用instantiateItem
方法实例化这些位置的视图。这就是为什么假设您在instantiateItem
中获得的位置是向用户显示的视图的位置是不正确的。
您应该使用ViewPager.OnPageChangeListener的onPageSelected(int position)
来确定当前视图的位置。