我已经按照教程操作并设法构建了一个包含三个框架的ViewPager。我还注册了一个按钮的点击(使用xml onClick),每次都将按钮的文本更改为“Clicks:1”,“Clicks:2”等...我唯一没有成功的是立即更新ViewPager以显示按钮的新文本(按钮永不更新)。
我的主要灵感来源:
http://thepseudocoder.wordpress.com/2011/10/05/android-page-swiping-using-viewpager/
这是我的FragmentActivity:
package com.fragmentviewpager;
import java.util.List;
import java.util.Vector;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MainActivity extends FragmentActivity {
private PagerAdapter pagerAdapter;
ViewPager pager;
Button buttonLeft;
int clickCounter = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewpager_layout);
pager = (ViewPager) findViewById(R.id.viewpager);
buttonLeft = (Button) findViewById(R.id.buttonLeft);
//initialise the viewpager
initialisePaging();
}
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, FragmentLeft.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentMiddle.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentRight.class.getName()));
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), fragments);
pager.setAdapter(this.pagerAdapter);
pager.setCurrentItem(1);
}
// THIS IS THE PLACE WHERE I NEED TO ADD SOMETHING FOR WANTED RESULT
public void buttonClick(View v) {
++clickCounter;
buttonLeft.setText("Clicks: " + clickCounter);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
这是我的FragmentPageAdapter:
package com.fragmentviewpager;
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public PagerAdapter(FragmentManager fm, List<Fragment> frags) {
super(fm);
fragments = frags;
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
我尝试过像
这样的事情pagerAdapter.notifyDataSetChanged();
和
pagerAdapter.startUpdate((ViewGroup)findViewById(R.layout.viewpager_layout));
pagerAdapter.instantiateItem((ViewGroup)findViewById(R.layout.viewpager_layout), 0);
pagerAdapter.finishUpdate((ViewGroup)findViewById(R.layout.viewpager_layout));
但似乎没有任何效果,我怀疑我误解了ViewPager或Fragments的本质中必不可少的东西。
我已经阅读了这个问题ViewPager PagerAdapter not updating the View,但这只会让我更加困惑。我想alvarolb可能会有所作为,但我无法在我的代码中实现他的建议。