我想检测我使用ViewPager设置的三个片段的特定片段何时出现在屏幕上。我在viewpager中有3个片段,并使用
设置了viewpagermViewPager.setOffscreenPageLimit(2);
因此所有三个片段一次构建(因为它在每一侧存储2个)。我检查了Fragment.onResume()只被调用一次而不是当每个片段到达前台时。是否有另一个回调以确保我可以捕获此事件并为其发送一些分析信号?
由于
答案 0 :(得分:1)
You can use the ViewPager.setOnPageChangeListener()
to set a ViewPager.OnPageChangeListener()
.
Use the listener for the selected page based on its position in the PagerAdapter.
Here's my sample app:
package net.ynotapps.testviewpagerfragment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class MainActivity extends ActionBarActivity {
@InjectView(R.id.pager)
ViewPager pager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
CustomPagerAdapter adapter = new CustomPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
// Put Code here //
// Example code //
if (position == 2) {
Toast.makeText(MainActivity.this, "Found Position 2 fragment", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
public static class CustomPagerAdapter extends FragmentPagerAdapter {
public CustomPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
CustomFragment fragment = new CustomFragment();
Bundle bundle = new Bundle();
bundle.putString("display_text", String.format("Fragment %d is here.", position));
fragment.setArguments(bundle);
return fragment;
}
@Override
public int getCount() {
return 5;
}
}
public static class CustomFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
TextView tv = new TextView(getActivity());
tv.setText(getArguments().getString("display_text"));
return tv;
}
}
}
答案 1 :(得分:0)
ViewPager源代码:
// Dispatch the change to any listeners
if (mAdapterChangeListeners != null && !mAdapterChangeListeners.isEmpty()) {
for (int i = 0, count = mAdapterChangeListeners.size(); i < count; i++) {
mAdapterChangeListeners.get(i).onAdapterChanged(this, oldAdapter, adapter);
}
}
因此,您可以使用ViewPager.addOnAdapterChangeListener
来监听回调。