gpt4 book ai didi

android - 使用 View Pager Adapter 的位置更改全局变量

转载 作者:行者123 更新时间:2023-11-30 00:52:16 24 4
gpt4 key购买 nike

我正在尝试使用 View 寻呼机的页面位置更改全局变量。

在我的 View 寻呼机适配器中:

 public Object instantiateItem(ViewGroup container, int position) {

...

Global global = new Global();
switch(position){
case 0: global.setLocation("0");
break;
case 1: global.setLocation("1");
break;
case 2: global.setLocation("2");
break;
case 3: global.setLocation("3");
break;
default: global.setLocation("");
break;
}
return item_view;
}

如果我切换页面,位置也会...但是,当我 toast 位置时,它是不正确的位置。

示例:我在第 3 页,global.getLocation = "2"或者我在第 1 页,global.getLocation = "3"; (答案似乎随机变化)

使用 View 分页器的位置来更改全局变量有什么不正确的地方?

我怎样才能正确完成这个任务?

尝试解决方案的更多代码...

public class Location extends AppCompatActivity {
ViewPager viewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location2);

viewPager = (ViewPager)findViewById(R.id.myViewPager);
adapterLocation = new CustomSwipeAdapterLocation(this);
viewPager.setAdapter(adapterLocation);

int position = viewPager.getCurrentItem();
Toast.makeText(this, position,
Toast.LENGTH_LONG).show();
}
...

错误:

     FATAL EXCEPTION: main
Process: andrewnguyen.finishedmoietyapp, PID: 5463
java.lang.RuntimeException: Unable to start activity ComponentInfo{andrewnguyen.finishedmoietyapp/andrewnguyen.finishedmoietyapp.Location}: android.content.res.Resources$NotFoundException: String resource ID #0x0

错误指的是行“int position = viewPager.getCurrentItem();

最佳答案

您可以使用 OnPageChangeListener并获取 onPageSelected() 方法中的位置:

   viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {
Global global = new Global();
switch(position){
case 0: global.setLocation("0");
break;
case 1: global.setLocation("1");
break;
case 2: global.setLocation("2");
break;
case 3: global.setLocation("3");
break;
default: global.setLocation("");
break;
}
}

@Override
public void onPageScrollStateChanged(int state) {

}
});

另一个选项使用getCurrentItem()获取真实项目位置:

viewPager.getCurrentItem();

如果您使用 instantiateItem()position 变量,则在实例化新页面时位置值会发生变化

关于android - 使用 View Pager Adapter 的位置更改全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40813396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com