我有一个包含三个标签的主要活动,这三个标签正在填充回收者视图,同时使用带有Volley的JSONHttp请求获取数据。但是,问题是第一次获取数据时,它会被填充。但是,当我从一个选项卡切换到另一个选项卡时,我无法找到再次获取数据的方法(如刷新它)。
我正在做的一个片段如下:
public class MainActivity extends AppCompatActivity {
// Class name TAG to be used for logging
private static final String TAG = MainActivity.class.getSimpleName();
// Variables
private User user;
private static ArrayList<> items;
private Fragment Fragment1, Fragment2;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
user = getIntent().getParcelableExtra("USER");
fetchItems();
mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
@Override
public void onPageSelected(int position) {
Log.d("Main", "Switching tab");
// Update the view
super.onPageSelected(position);
}
});
}
public void fetchJobs(){
items = new ArrayList<>();
JsonArrayRequest getItems = new JsonArrayRequest(Request.Method.GET, url + "items.json?", null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray o) {
// Get JSon from Http request, this code works fine..
// items array is populated with the desired response
mSectionsPagerAdapter.notifyDataSetChanged();
....
}
如果我切换到选项卡刷新列表时调用fetchItems(),则不会重新填充新条目。
答案 0 :(得分:0)
尝试使用
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
//Do what you want to do here
}
}
在viewPager的每个子片段中,因此每次在viewpager中显示片段时都会调用它。并可以做出必要的改变。谢谢,如果它没有,请记下来。