为未知数量的项目滑动标签

时间:2016-12-06 23:07:35

标签: android json android-layout listview swipeview

我会试着解释一下我在想做什么作为Android应用程序。但我真的很困惑,我将如何处理这个问题。

当您从某些Web API(例如位置)获取JSON时,假设JSON有5个不同的位置,并且您希望将每个位置作为单独的列表项存储在列表视图中。这很简单,您使用位置适配器类,然后将这5个项目存储为列表。例如,JSON在24小时后更新,现在有10个位置。没问题 - Android因为位置适配器等而处理这个问题(我知道所有这些)。基本上,我想告诉android在从JSON获取信息之前不需要知道有多少列表项。

现在,问题是我正在尝试创建一个滑动视图,它将代表每个列表项(1个完整视图= 1个列表项)。例如,如果有5个位置,我只能滑动4次,然后我将到达最后一个选项卡。如果有更新,并且有10个位置,我只能滑动9次,直到我到达结束。我希望你理解这个想法。

我的问题是 - 如何创建动态滑动视图,其中每个列表项都有自己独立的窗口并到达您要刷的另一个列表项?

我主要担心的是你怎么不告诉android你需要多少次滑动视图,当他读取JSON并知道位置数量时他会想出来。

非常感谢

2 个答案:

答案 0 :(得分:0)

让我们说你的数据是这样的:

{"India","Morocco","China","Russia"}

你可以得到JSON对象的长度。在这种情况下它是4.Save在一个静态变量.Suppose     max_swipes=4

然后在你的滑动方法

`if(position<=max_swipes || position==0){//code to swipe }
else
{
//cannot swipe last position
}`  

答案 1 :(得分:0)

要实现此类功能,您只需使用viewPager即可。您可以复制herehere中的代码。这是两个文件,您只需要按原样复制。在项目中添加这两个文件后,您需要创建一个适配器,这就是创建滑动视图的动态。

我正在添加代码段,希望它能为您提供帮助。

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

private DetailFragment page;
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created


// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm, CharSequence mTitles[], int mNumbOfTabsumb) {
    super(fm);
    this.Titles = mTitles;
    this.NumbOfTabs = mNumbOfTabsumb;
}

//This method return the fragment for the every position in the View Pager, This method is called only when we slide or change the tabs and not called upon rotating the screen
@Override
public Fragment getItem(int position) {
    if(position < NumbOfTabs) 
    {
        page= new DetailFragment();
        return page;
    }else {
        return null;
    }


}

// This method return the titles for the Tabs in the Tab Strip(in case you want to add title to each page.

@Override
public CharSequence getPageTitle(int position) {
    return Titles[position];
}

@Override
public int getCount() {
    return NumbOfTabs;
}

}

在创建此适配器的实例时,您可以通过计算JSON中的项目数来传递您需要的页数。

希望这会有所帮助。