当前位置: 首页 > 知识库问答 >
问题:

用新内容刷新ViewPager的奇怪问题:

缪升
2023-03-14

我从web服务接收数据,这些数据被解析为应用程序类中的一个对象,在我的例子中,该对象是报表类,它包含一个选项卡列表,这些选项卡应该填充视图页。因此,该报告存储在Application类中的CurrentReport参数中。

每个选项卡都应该是viewpager中的一个页面。因此,当我第一次接收数据并对其进行解析时,所有工作都很完美,视图分页程序中填充了正确的数据并将其呈现出来。

public class TabsViewPagerFragmentActivity extends FragmentActivity implements    ViewPager.OnPageChangeListener, TabHost.OnTabChangeListener 
{
static final String TAG = TabsViewPagerFragmentActivity.class.getSimpleName();
private TabHost mTabHost;
private ViewPager mViewPager;
private HashMap<String, TabInfo> mapTabInfo;
public ViewPagerAdapter mPagerAdapter;
private TextView tvReportName, tvTabTitle;
private Button bBackToParameters;
private Dialog progressDialog;
private SGRaportManagerAppObj application;
private int numberOfTabs = 0;
private Display display;
public static final int POPUP_MARGIN = 6;
LeftSideMenu leftSideMenu;

public void NotifyTabActivityViewPagerAdapter()
{
    mPagerAdapter.notifyDataSetChanged();
}

public ViewPagerAdapter getTabActivityViewPagerAdapter()
{
    return mPagerAdapter;
}

public ViewPager getTabActivityViewPager()
{
    return mViewPager;
}

public void setCurrentTabTitle (String title)
{
    tvTabTitle.setText(title);
    Log.d(TAG, "set tab title from activity: "+title);
}


/**
* Maintains extrinsic info of a tab's construct
*/
private class TabInfo 
{
    private String tag;
    private Class<?> clss;
    private Bundle args;
    private Fragment fragment;

    TabInfo(String tag, Class<?> clazz, Bundle args) 
    {
        this.tag = tag;
        this.clss = clazz;
        this.args = args;
    }
}

/**
 * A simple factory that returns dummy views to the Tabhost
 */
class TabFactory implements TabContentFactory {

    private final Context mContext;

    /**
     * @param context
     */
    public TabFactory(Context context) {
        mContext = context;
    }

    /** (non-Javadoc)
     * @see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String)
     */
    public View createTabContent(String tag) {
        View v = new View(mContext);
        v.setMinimumWidth(0);
        v.setMinimumHeight(0);
        return v;
    }
}

/** (non-Javadoc)
 * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
*/
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    application = SGRaportManagerAppObj.getInstance();
    display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    // Inflate the layout
    setContentView(R.layout.tabs_screen_activity_layout);
    tvTabTitle = (TextView) findViewById(R.id.tvTabName);
    tvReportName = (TextView)findViewById(R.id.tvReportName);
    tvReportName.setText(application.currentReport.getName()+ " - ");
    bBackToParameters = (Button) findViewById(R.id.bBackToParameters);
    leftSideMenu = (LeftSideMenu) findViewById(R.id.leftSideMenu);
    applyOnClickListenerToLeftSideMenu();

    findViewById(R.id.showLeftMenuButton).setOnClickListener(new View.OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {               
            Display d = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
            int width = d.getWidth();

            View panel = findViewById(R.id.leftSideMenu);
            View appPanel = findViewById(R.id.appLayout);
            if (panel.getVisibility() == View.GONE){
                appPanel.setLayoutParams(new LinearLayout.LayoutParams(width, LayoutParams.FILL_PARENT));
                panel.setVisibility(View.VISIBLE);
                applyOnClickListenerToLeftSideMenu();
            }else{
                ToggleButton button = (ToggleButton) findViewById(R.id.showLeftMenuButton);
                button.setChecked(false);
                panel.setVisibility(View.GONE);
            }
        }
    });

    // Initialise the TabHost
    progressDialog = DialogUtils.createProgressDialog(this, this.getString(R.string.populating_view_pager));
    progressDialog.show();

    if (SGRaportManagerAppObj.getInstance().parametersRepository.getParametersRepository().size() == 0)
    {
        bBackToParameters.setText(R.string.back_to_report_list);
    }
    this.initialiseTabHost(savedInstanceState);

    if (savedInstanceState != null) {
        mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); //set the tab as per the saved state
    }
    // Intialise ViewPager
    this.intialiseViewPager();
    progressDialog.dismiss();
}

 /** (non-Javadoc)
 * @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
 */
protected void onSaveInstanceState(Bundle outState) {
    outState.putString("tab", mTabHost.getCurrentTabTag()); //save the tab selected
    super.onSaveInstanceState(outState);
}

/**
 * Initialise ViewPager
 */
public void intialiseViewPager() 
{

    List<Fragment> fragments = new Vector<Fragment>();

  // TabInfo tabInfo = null;

    if (application.getCurrentDataSource().equals(DataSource.SSRS))
    {
        numberOfTabs = application.currentReport.getTabsList().size();
    }
    else if (application.getCurrentDataSource().equals(DataSource.SGRDL))
    {
        numberOfTabs = application.currentReport.getODTabsList().size();
        Log.d(TAG, "CURRENT REPORT FROM VIEW PAGER: "+ application.currentReport.toString());
    }   

    Log.d(TAG,"Current Tabs number from TabsViewPager activity: " +numberOfTabs);

    if (application.getCurrentDataSource().equals(DataSource.SSRS))
    {
         for (int i = 0; i < numberOfTabs; i++)     
         {
            Tab tempTab = application.currentReport.getTabsList().get(i);
            if (tempTab.getTabTemplateId() == 7)
            {
                GridFragment gridFragment = new GridFragment(tempTab);
                fragments.add(gridFragment);
            }
            else  if (tempTab.getTabTemplateId() == 8)
            {
                NewChartFragment chartFragment = new NewChartFragment(tempTab, this);
                fragments.add(chartFragment);
            }
         }
    }
    else if (application.getCurrentDataSource().equals(DataSource.SGRDL))
    {
         for (int i = 0; i < numberOfTabs; i++)     
         {
            ODTab tempTab = application.currentReport.getODTabsList().get(i);
            if (tempTab.getTabType().equals(ODGrid.XML_GRID_ELEMENT))
            {
                GridFragment gridFragment = GridFragment.newInstance(tempTab.getTabId());
                fragments.add(gridFragment);
            }
            else  if (tempTab.getTabType().equals(ODChart.XML_CHART_ELEMENT))
            {
                NewChartFragment chartFragment = NewChartFragment.newInstance(tempTab.getTabId());
                fragments.add(chartFragment);
            }
         }
    }   

    Log.d(TAG, "Current report fragments set to adapter: "+fragments.toString());
   /*
    if (this.mPagerAdapter == null)
    {
        this.mPagerAdapter  = new ViewPagerAdapter(super.getSupportFragmentManager(), fragments);
    }
    else
    {
        this.mPagerAdapter.removeAllFragments();
        this.mPagerAdapter.addFragmentsListToAdapter(fragments);
    }
    */
    this.mPagerAdapter  = new ViewPagerAdapter(super.getSupportFragmentManager(), fragments);
    this.mViewPager = (ViewPager)super.findViewById(R.id.pager);
//    this.mViewPager.setAdapter(null);
    this.mViewPager.setAdapter(this.mPagerAdapter);
    this.mViewPager.setOffscreenPageLimit(0);
    this.mViewPager.setOnPageChangeListener(this);
    Log.d(TAG, "Adapter initialized!");
}

/**
 * Initialise the Tab Host
 */
public void initialiseTabHost(Bundle args) {
    mTabHost = (TabHost)findViewById(android.R.id.tabhost);

    /*
    //new edit
    if (mTabHost.getChildCount() > 0)
    {
        mTabHost.removeAllViews();
    }
    */

    mTabHost.setup();
    TabInfo tabInfo = null;
    mapTabInfo = new HashMap<String, TabsViewPagerFragmentActivity.TabInfo>();
    if (args != null)
    {}
    else
    {
        if (application.getCurrentDataSource().equals(DataSource.SSRS))
        {
            int numberOfTabs = application.currentReport.getTabsList().size();
            for (int i = 0; i < numberOfTabs; i++)      
            {
                Tab tempTab = application.currentReport.getTabsList().get(i);
                if (tempTab.getTabTemplateId() == 7)
                {
                    //GridFragment gridFragment = new GridFragment(tempTab);
                    TabsViewPagerFragmentActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab "+String.valueOf(i)).setIndicator("Tab "+String.valueOf(i)), ( tabInfo = new TabInfo("Tab "+String.valueOf(i), GridFragment.class, args)));
                    this.mapTabInfo.put(tabInfo.tag, tabInfo);
                }
                else  if (tempTab.getTabTemplateId() == 8)
                {
                    TabsViewPagerFragmentActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab "+String.valueOf(i)).setIndicator("Tab "+String.valueOf(i)), ( tabInfo = new TabInfo("Tab "+String.valueOf(i), NewChartFragment.class, args)));
                    this.mapTabInfo.put(tabInfo.tag, tabInfo);
                }
            }
        }

        else if (application.getCurrentDataSource().equals(DataSource.SGRDL))
        {
            int numberOfTabs = application.currentReport.getODTabsList().size();
            for (int i = 0; i < numberOfTabs; i++)      
            {
                ODTab tempTab = application.currentReport.getODTabsList().get(i);
            //  Log.d(TAG,"Crashed Tab type: "+ tempTab.getTabType());
                if (tempTab.getTabType().equals(ODGrid.XML_GRID_ELEMENT))
                {
                    //GridFragment gridFragment = new GridFragment(tempTab);
                    TabsViewPagerFragmentActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab "+String.valueOf(i)).setIndicator("Tab "+String.valueOf(i)), ( tabInfo = new TabInfo("Tab "+String.valueOf(i), GridFragment.class, args)));
                    this.mapTabInfo.put(tabInfo.tag, tabInfo);
                }
                else  if (tempTab.getTabType().equals(ODChart.XML_CHART_ELEMENT))
                {
                    TabsViewPagerFragmentActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab "+String.valueOf(i)).setIndicator("Tab "+String.valueOf(i)), ( tabInfo = new TabInfo("Tab "+String.valueOf(i), NewChartFragment.class, args)));
                    this.mapTabInfo.put(tabInfo.tag, tabInfo);
                }
            }
        }
    }
    // Default to first tab
    //this.onTabChanged("Tab1");
    //
    mTabHost.setOnTabChangedListener(this);
}

/**
 * Add Tab content to the Tabhost
 * @param activity
 * @param tabHost
 * @param tabSpec
 * @param clss
 * @param args
 */
private static void AddTab(TabsViewPagerFragmentActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) 
{
    // Attach a Tab view factory to the spec       
    ImageView indicator = new ImageView(activity.getBaseContext());
    indicator.setPadding(10, 10, 10, 10);
    indicator.setImageResource(R.drawable.tab_select_icon_selector);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(10, 10, 10, 10);
    indicator.setLayoutParams(lp);
    tabSpec.setIndicator(indicator); 
    tabSpec.setContent(activity.new TabFactory(activity));
    tabHost.addTab(tabSpec);
}

/** (non-Javadoc)
 * @see android.widget.TabHost.OnTabChangeListener#onTabChanged(java.lang.String)
 */
public void onTabChanged(String tag) {
    //TabInfo newTab = this.mapTabInfo.get(tag);
    int pos = this.mTabHost.getCurrentTab();
    this.mViewPager.setCurrentItem(pos);
}

/* (non-Javadoc)
 * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrolled(int, float, int)
 */
@Override
public void onPageScrolled(int position, float positionOffset,
        int positionOffsetPixels) {
    // TODO Auto-generated method stub

}

/* (non-Javadoc)
 * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageSelected(int)
 */
@Override
public void onPageSelected(int position) {
    // TODO Auto-generated method stub
    this.mTabHost.setCurrentTab(position);
}


/* (non-Javadoc)
 * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrollStateChanged(int)
 */
@Override
public void onPageScrollStateChanged(int state) {
    // TODO Auto-generated method stub

}
public class ViewPagerAdapter extends FragmentPagerAdapter 
{
private List<Fragment> fragments;

/**
 * @param fm
 * @param fragments
 */
public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
    super(fm);
    this.fragments = fragments;
}

/* (non-Javadoc)
 * @see android.support.v4.app.FragmentPagerAdapter#getItem(int)
 */

@Override
public Fragment getItem(int position) {
    return this.fragments.get(position);
}

/* (non-Javadoc)
 * @see android.support.v4.view.PagerAdapter#getCount()
 */

@Override
public int getCount() {
    return this.fragments.size();
}

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
} 
public class ParseSGRDLReportDataAsyncTask extends AsyncTask<String, Object, Report>{

static final String TAG = ParseSGRDLReportDataAsyncTask.class.getSimpleName();
private Activity activity;  
private Exception exception;
private ResponseHandler responseHandler = new ResponseHandler();
private SGRaportManagerAppObj application;
private Dialog progressDialog;

public ParseSGRDLReportDataAsyncTask(LoginScrActivity activity) {
    super();
    this.activity = activity;
}

public ParseSGRDLReportDataAsyncTask(Activity currentActivity) {
    super();
    this.activity = currentActivity;
}

public void onPreExecute() {
    application = SGRaportManagerAppObj.getInstance();
    progressDialog = DialogUtils.createProgressDialog(activity, activity.getString(R.string.parse_data_dialog_message));
    progressDialog.show();
}

@Override
protected Report doInBackground(String... params) {

    String ReportDataString = params[0];
    try{
        return DataAccessManager.parseSGRDLReportData(ReportDataString);            
    }
    catch (Exception e) {
        exception = e;
        return null;
    }
}

@Override
public void onPostExecute(Report result) {
    progressDialog.dismiss();

    if (exception == null) 
    {
        if (activity.getClass() == TabsViewPagerFragmentActivity.class)
        {
            application.currentReport = result;
            Log.d(TAG, "Current report parsed is: "+result);

            ((TabsViewPagerFragmentActivity)activity).intialiseViewPager();

            ((TabsViewPagerFragmentActivity)activity).initialiseTabHost(null);

            ((TabsViewPagerFragmentActivity)activity).NotifyTabActivityViewPagerAdapter();

            }
        else
        {
            responseHandler.handleProcessSGRDLReportDataResult(result, activity);       
        }
    }
    else {
        processException();
    }
}

private void processException() {
    Toast.makeText(activity,   activity.getString(R.string.error_when_parsing_data), 3000).show();
}
}
if (activity.getClass() == TabsViewPagerFragmentActivity.class)
{
                TabsViewPagerFragmentActivity tempActivity = ((TabsViewPagerFragmentActivity)activity);
                application.currentReport = result;
                Log.d(TAG, "Current report parsed is: "+result);
                List<Fragment> frags =  tempActivity.getTabActivityViewPagerAdapter().getFragments(); // getter method in your adapter
                FragmentTransaction ft = tempActivity.getSupportFragmentManager().beginTransaction();
                for (int i = 0; i < frags.size(); i++) 
                {
                    ft.remove(frags.get(i));
                }
                ft.commit(); 
                tempActivity.intialiseViewPager();
                tempActivity.getTabHost().getTabWidget().removeAllViews();
                tempActivity.initialiseTabHost(null);
                tempActivity.NotifyTabActivityViewPagerAdapter();
}

当主要两点是从fragmentManager/supportfragmentManager中删除以前添加的片段时,使用fragmenttransactionviewpager中显示正确的片段集,以及在添加新的视图之前从tabwidget中删除所有视图。

共有1个答案

逄征
2023-03-14

我将发布一些我的代码,这样你就会得到一些想法。

适配器初始化并将其设置为视图分页程序。

vfPageContainer = (ViewPager)findViewById(R.id.vfPageContainer);
mAdapter = new TestFragmentAdapter(this,getSupportFragmentManager()); 
vfPageContainer.setAdapter(mAdapter);

每次出现新数据时,我调用以下方法:

private void updateUi()
{   
    for(int i=0 ; i < alDataPages.size() ; i++)
    {
        mAdapter.addFragment(TestFragment.newInstance(this));
    }

    mAdapter.notifyDataSetChanged();
}
class TestFragmentAdapter extends FragmentStatePagerAdapter {

    private Context context;

    private ArrayList<Fragment> views = new ArrayList<Fragment>();

    public TestFragmentAdapter(Context context,FragmentManager fm)
    {
        super(fm);

        this.context = context;

        views = new ArrayList<Fragment>();
    }

    @Override
    public Fragment getItem(int position)
    {
        return views.get(position);
    }

    public void addFragment (Fragment v)
    {
        views.add(v);
    }

    public void clear()
    {

        for(int i = 0 ; i < views.size() ; i++)
        {
            views.clear();
        }

    }

    @Override
    public int getCount() 
    {
        return views.size();
    }


}
public final static class TestFragment extends Fragment {


    private Context context;

    public void setContext(Context c)
    {
        context = c;
    }

    public static TestFragment newInstance(Context context)
    {
        TestFragment f = new TestFragment();

        f.setContext(context);

        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {
        WebView webView_viewpage = new WebView(context);

        return webView_viewpage;
    }


}
 mAdapter.clear(); // previously it was not working so i created new adapter and set it to the viewpager.
 mAdapter = new TestFragmentAdapter(this,getSupportFragmentManager()); 
 vfPageContainer.setAdapter(mAdapter);

希望这对你有帮助,你会找到解决办法。

 类似资料:
  • 我在Chrome Developer Tools中出现这个错误已经有一段时间了,我似乎就是找不到不安全的http://请求。它指向我的域,但没有https://。http://www.example.com/不是一个脚本,所以我不明白它是从哪里来的。 内容混杂:“HTTPS://www.example.com/categoy/a-product.html”页面是通过HTTPS加载的,但请求的脚本“

  • 我痛苦了3天。我正在使用兼容性库中的视图分页程序。我已经成功地让它显示了几个视图。我的问题是,当我交换视图时,不会在它的回收器视图中按片段更新数据。但当我关闭应用程序时,打开碎片会按回收器视图显示更新内容。我使用了所有方法,如setnotifydatachanged()和许多其他方法,但viewpager中的片段不更新内容。感谢所有的帮助,这是我的主要活动

  • 问题内容: 我正在编写一个应用程序,它是Angular和jQuery的一部分。我通过在iFrame中加载jQuery内容来分离它们。 在某个事件(例如,单击ng)时,我需要刷新iFrame。我的控制器包含以下代码: 而iFrame是: 问题答案: 正如Paulo Scardine所说,正确的方法是通过指令,因为您不应该使用控制器来操纵DOM。 这样的事情可以做: 然后可以这样使用: 和:

  • 问题内容: 我想在单击按钮时重新加载div。我不想重新加载整个页面。 这是我的代码: HTML: 单击按钮后,应该重新加载而不加载或刷新整个页面。 以下是我尝试过但无法正常工作的Jquery:- 请提出建议。 这是我页面上的DIV,其中包含一些产品的图片和序列号…这将是第一次加载时来自数据库的信息。但是,如果用户遇到问题,他将单击“再次捕获”按钮“ ”,这将再次加载这些信息。 Div的HTML代码

  • 问题内容: 在弄乱Eclipse中的自定义格式设置选项的同时,在示例代码之一中,我看到了如下代码: 我从未见过像这样使用过,并且我从事Java编程已有9年了!有谁知道你为什么要这么做?这样做的可能用例/好处是什么? 我看到的另一段代码,我认为这是一个非常有用的速记,因此我也在这里共享了它,它的作用很明显: 问题答案: 它是在Java 7中添加的。它称为try-with- resources 语句。

  • 问题内容: 我正在评估用于构建Web应用程序的Spring MVC&Boot和AngularJs。我遇到了一个问题,当我修改静态内容(html,js,css)时,每次都必须重新启动应用程序。我希望有某种解决方法,因为重新启动整个应用程序以进行静态内容更改效率不高。我尝试过的所有其他Web应用程序框架都允许即时更新静态内容文件(甚至只是Spring MVC和普通的旧WAR应用程序)。 我已经从“使用