ViewPager似乎正在成倍增加

时间:2014-08-11 14:43:25

标签: android android-viewpager

我不太清楚这里发生了什么,但每次我的片段加载到ViewPager中时,我都会在日志中注意到一些奇怪的活动。

在片段的onResume中我有以下内容:

Log.d("onResume", tabName);

首次加载时,它会记录一个条目

D/onResume﹕ [Food]

如果我旋转我的屏幕,或者启动/停止另一个导致ViewPager /片段再次加载的活动,我会在我的logcat中得到它

D/onResume﹕ [Food]
D/onResume﹕ [Food]

如果我第三次这样做了

D/onResume﹕ [Food]
D/onResume﹕ [Food]
D/onResume﹕ [Food]

任何人都知道可能导致这种情况的原因吗?

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;

public class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {

    int listSize;
    String[] tabNames;
    String tabName;
    protected Context mContext;

    /** Constructor of the class */
    public MyFragmentPagerAdapter(FragmentManager fm, Context c) {
        super(fm);
        mContext = c;
    }

    /** This method will be invoked when a page is requested to create */
    @Override
    public Fragment getItem(int position) {

        MainFragment mainFragment = new MainFragment();
        final DatabaseHelper db = new DatabaseHelper(mContext);

        tabName = "[" + getPageTitle(position) + "]";
        Double balance = db.getSum(tabName);
        Bundle data = new Bundle();
        data.putInt("current_page", position + 1);
        data.putString("tabName", tabName);
        data.putDouble("balance", balance);
        data.putInt("tabCount", getCount());
        mainFragment.setArguments(data);
        return mainFragment;
    }

    /** Returns the number of pages */
    @Override
    public int getCount() {
        return listSize;
    }

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

    public void setCount(int count){
        listSize = count;
    }

    public void setNames(String[] names) {
        tabNames = names;
    }

    @Override
    public int getItemPosition(Object object) {
        return PagerAdapter.POSITION_NONE;
    }
}

这里是每个片段

import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.text.DecimalFormat;
import java.util.ArrayList;

public class MainFragment extends Fragment {

    int mCurrentPage;
    int tabCount;
    int tableCount;
    TextView tvBalanceDollar;
    TextView tvBalanceCent;
    String cents;
    Context mContext;
    String tabName;
    Double balance;

    DatabaseHelper db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /** Getting the arguments to the Bundle object */
        Bundle data = getArguments();

        /** Getting integer data of the key current_page from the bundle */
        mCurrentPage = data.getInt("current_page", 0);
        tabName = data.getString("tabName");
        balance = data.getDouble("balance", 0.0);
        tabCount = data.getInt("tabCount", 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContext = container.getContext();

        View v = inflater.inflate(R.layout.fragment_account, container, false);
        tvBalanceDollar = (TextView) v.findViewById(R.id.tvBalanceDollar);
        tvBalanceCent = (TextView) v.findViewById(R.id.tvBalanceCent);

        Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "Roboto-Thin.ttf");

        tvBalanceDollar.setTypeface(tf);
        tvBalanceCent.setTypeface(tf);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    public void onResume() {
        super.onResume();
        if (setTabCount() > 0) {
            updateFrag();
            Log.d("onResume", tabName);
        }
    }

    public void updateFrag() {
        db = new DatabaseHelper(getActivity().getApplicationContext());

        Log.d("TabName", tabName);
        balance = db.getSum(tabName);

        if (balance > 9999.99) {
            tvBalanceDollar.setTextSize(75);
            tvBalanceCent.setTextSize(37);
        } else {
            tvBalanceDollar.setTextSize(100);
            tvBalanceCent.setTextSize(50);
        }

        if (balance > 0) {
            tvBalanceDollar.setText("$" + new DecimalFormat("##.").format(Math.floor(balance)));
        } else if (balance < 0 && balance > -1) {
            tvBalanceDollar.setText("$-0.");
        } else {
            tvBalanceDollar.setText("$" + new DecimalFormat("##.").format(Math.ceil(balance)));
        }

        if ((balance - balance.intValue()) <= .1 && (balance - balance.intValue()) > 0) {
            cents = new DecimalFormat(".00").format(balance - balance.intValue()).substring(1);
        } else if ((balance - balance.intValue()) < 0) {
            cents = new DecimalFormat(".00").format(balance - balance.intValue()).substring(2);
        } else {
            cents = new DecimalFormat(".00").format(balance - balance.intValue()).substring(1);
        }

        tvBalanceCent.setText(cents);
    }

    public int setTabCount() {
        db = new DatabaseHelper(getActivity().getApplicationContext());
        ArrayList<String> a = db.listTables();
        tableCount = a.size();
        return tableCount;
    }

}

这是MainActivity

public class MainActivity extends FragmentActivity {

DatabaseHelper db = new DatabaseHelper(this);

MyFragmentPagerAdapter pagerAdapter;

int tableCount;
int RESET_TABS = 1;

ViewPager pager;

PagerTabStrip pagerTabStrip;

String tabName;
String transType;
public static String PACKAGE_NAME;
public static int PACKAGE_VERSION;

TextView tvWithdraw;
TextView tvDeposit;

MenuItem addAccount;
MenuItem deleteAccount;
MenuItem viewTransactions;
MenuItem editAccount;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setView();

    PackageInfo pinfo = null;
    try {
        pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    PACKAGE_VERSION = pinfo.versionCode;
    PACKAGE_NAME = pinfo.versionName;

    Typeface tfAlexBrush = Typeface.createFromAsset(getAssets(), "AlexBrush-Regular.ttf");
    int actionBarTitle = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
    TextView actionBarTitleView = (TextView) getWindow().findViewById(actionBarTitle);
    if(actionBarTitleView != null){
        actionBarTitleView.setTypeface(tfAlexBrush);
    }

}

public void onResume() {
    super.onResume();
    setView();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
    }

    if (resultCode == RESULT_CANCELED) {

    }

    if (resultCode == RESET_TABS) {
        setTabs();
        setView();
    }
}

public int setTabCount() {
    ArrayList<String> a = db.listTables();
    tableCount = a.size();
    return tableCount;
}

public String[] setTabNames() {
    ArrayList<String> a = db.listTables();
    String[] mStringArray = new String[a.size()];
    mStringArray = a.toArray(mStringArray);
    return mStringArray;
}

public void setTabs(){
    pager = (ViewPager) findViewById(R.id.pager);

    FragmentManager fm = getSupportFragmentManager();

    pagerAdapter = new MyFragmentPagerAdapter(fm, getApplicationContext());
    pagerAdapter.setCount(setTabCount());
    pagerAdapter.setNames(setTabNames());

    pager.setAdapter(pagerAdapter);
}

public void deleteAccount() {
    final String niceTabName = pagerAdapter.getPageTitle(pager.getCurrentItem()).toString();

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

    // set title
    alertDialogBuilder.setTitle("Delete Account");

    // set dialog message
    alertDialogBuilder
            .setMessage("Are you sure you wish to delete the account: " + niceTabName + "?" +
            "\n\nWARNING: You will lose all data for this account!")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    db.deleteTable(niceTabName);
                    db.close();
                    Toast.makeText(getApplicationContext(), "Account " + niceTabName + " has been deleted.",
                            Toast.LENGTH_LONG).show();
                    setTabs();
                    setView();

                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();

}

public void setView() {

    if (setTabCount() == 0) {

        getFragmentManager().beginTransaction()
                .add(R.id.mainFrameLayout, new PlaceholderFragment())
                .commit();
    } else {
        setContentView(R.layout.activity_main);

        Typeface tfThin = Typeface.createFromAsset(getAssets(), "Roboto-Thin.ttf");
        Typeface tfLight = Typeface.createFromAsset(getAssets(), "Roboto-Thin.ttf");



        tvWithdraw = (TextView) findViewById(R.id.tvWithdraw);
        tvDeposit = (TextView) findViewById(R.id.tvDeposit);
        pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_tab_strip);

        tvWithdraw.setTypeface(tfLight);
        tvDeposit.setTypeface(tfLight);

        for (int i = 0; i < pagerTabStrip.getChildCount(); ++i) {
            View nextChild = pagerTabStrip.getChildAt(i);
            if (nextChild instanceof TextView) {
                TextView textViewToConvert = (TextView) nextChild;
                textViewToConvert.setTypeface(tfLight);
            }
        }

        setTabs();

        tvWithdraw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    tabName = "[" + pagerAdapter.getPageTitle(pager.getCurrentItem()).toString() + "]";
                    transType = "debit";

                    Intent i = new Intent(v.getContext(), AmountDialogActivity.class);
                    i.putExtra("type", "debit");
                    i.putExtra("table", tabName);
                    startActivityForResult(i, RESULT_OK);
            }
        });

        tvDeposit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    tabName = "[" + pagerAdapter.getPageTitle(pager.getCurrentItem()).toString() + "]";
                    transType = "credit";

                    Intent i = new Intent(v.getContext(), AmountDialogActivity.class);
                    i.putExtra("type", "credit");
                    i.putExtra("table", tabName);
                    startActivityForResult(i, RESULT_OK);
            }
        });
    }
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        Typeface tfLight = Typeface.createFromAsset(getActivity().getAssets(), "Roboto-Light.ttf");
        Typeface tfThin = Typeface.createFromAsset(getActivity().getAssets(), "Roboto-Thin.ttf");
        Typeface tfAlexBrush = Typeface.createFromAsset(getActivity().getAssets(), "AlexBrush-Regular.ttf");

        TextView tvSimpleRegister = (TextView) rootView.findViewById(R.id.tvSimpleRegister);
        TextView tvCreateAccount = (TextView) rootView.findViewById(R.id.tvCreateAccount);
        TextView tvCurrentVersion = (TextView) rootView.findViewById(R.id.tvCurrentVersion);

        tvCurrentVersion.setText("Current Version: " + PACKAGE_NAME);

        tvSimpleRegister.setTypeface(tfAlexBrush);
        tvCreateAccount.setTypeface(tfLight);
        tvCurrentVersion.setTypeface(tfThin);

        return rootView;
    }
}

}

1 个答案:

答案 0 :(得分:0)

我在setView

中添加了多个setContentView(R.layout.activity_main);

为我删除这个已解决的多个问题...哇!