android - 当我旋转屏幕时出现奇怪的错误,viewpager 内的 ListView 将消失

标签 android listview android-fragments android-listview android-viewpager

好的,我有一个非常奇怪的错误!当我旋转屏幕两次时,viewPager 中的 ListView 将消失,但这只会在我更改 viewPager 的上下文时发生,它是一个 listView(但正如我所说,当我第一次旋转时它工作正常,当我不'通过按下 radioGroup 来改变 viewpager):

我认为问题应该是当我通过 radio 组更改 viewpager 内的适配器时 (我的意思是这段代码):

myViewpager.setAdapter(new ViewPagerAdapter(fragManag, false));
myViewpager.setCurrentItem(200);

或 fragment 内的 ListView (哪个 viewAdapter)使用: (这段代码):

public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    if (row == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(R.layout.list_view_in_money_manager, parent, false);
    }

    TextView category = (TextView) row.findViewById(R.id.textView1x);
    TextView amount = (TextView) row.findViewById(R.id.textView2x);

    category.setText(categoryArray[position]);
    amount.setText(amountArray[position] + MoneyManager.DOLLAR);

    if (expanseB[position]) {
        amount.setTextColor(Color.parseColor("#FFFF4444"));
    } else {
        amount.setTextColor(Color.parseColor("#0000FF"));
    }
    return row;
}

任何建议都会很棒:)

这里是所有的代码:

public class MoneyManager extends FragmentActivity implements FragmentChangeMoneyDialog.Communicator, OnCheckedChangeListener {

    // ...some def
    FragmentMoneyTotal frgTotalListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // ...some def

            radioGroup1.setOnCheckedChangeListener(this);
            radioGroup2.setOnCheckedChangeListener(this);

            // Create a ViewPager
            android.support.v4.app.FragmentManager fragManag = getSupportFragmentManager();
            myViewpager.setAdapter(new ViewPagerAdapter(fragManag, false));
            myViewpager.setCurrentItem(200);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // montly or total
        if (group == radioGroup1) {
            switch (checkedId) {
            case R.id.radioButton1:
                rG1 = false;
                rgCheck();
                break;
            case R.id.radioButton2:
                rG1 = true;
                rgCheck();
                break;
            }
        }
        // show all or show by cat
        if (group == radioGroup2) {
            // false : showAll True: show by category
            switch (checkedId) {
            // show all
            case R.id.rg2radioButton1:
                rG2 = false;
                rgCheck();
                break;
            // show by cat
            case R.id.rg2radioButton2:
                rG2 = true;
                rgCheck();
                break;
            }
        }
    }

    // TODO checking for radio group
    public void rgCheck() {
        android.support.v4.app.FragmentManager fragManag = getSupportFragmentManager();

            if (!rG2) {
                myViewpager.setAdapter(new ViewPagerAdapter(fragManag, false));
                myViewpager.setCurrentItem(200);
            } else {

                myViewpager.setAdapter(new ViewPagerAdapter(fragManag, true));
                myViewpager.setCurrentItem(200);
            }

    }

    class ViewPagerAdapter extends FragmentStatePagerAdapter {
        boolean radioGroup2Track;

        public ViewPagerAdapter(android.support.v4.app.FragmentManager fm, boolean rG) {
            super(fm);
            this.radioGroup2Track = rG;
        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            android.support.v4.app.Fragment frag = null;
            frag = FragmentMoneyMontly.newInstance(position - 200, radioGroup2Track);
            return frag;
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            Calendar cal = Calendar.getInstance();
            for (int i = 0; i < 199; i++) {
                if (position == i) {
                    cal.add(Calendar.MONTH, i - 200);
                    return (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.YEAR);
                }
            }

            if (position == 199) {
                return "Prev Month";
            }
            // show today month
            if (position == 200) {
                return "This Month";
            }

            if (position == 201) {
                return "Next Month";
            }
            // Show next month
            for (int i = 202; i <= 400; i++) {
                if (position == i) {
                    cal.add(Calendar.MONTH, i - 200);
                    return (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.YEAR);
                }
            }
            return null;
        }
    }
}

下面是 View 组内 fragment 的代码:

public class FragmentMoneyMontly extends Fragment {
    private static final String TEXT_AT_END = "Total : ";
    ListView transactionListV;
    TextView totalMontlyTV;
    int dateposition = 0;

    public static FragmentMoneyMontly newInstance(int index, boolean radioGTrack) {
        FragmentMoneyMontly f = new FragmentMoneyMontly();
        // Supply index, radioTrack input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        args.putBoolean("radioGtrack", radioGTrack);
        f.setArguments(args);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_fragment_money_manager, container, false);

        transactionListV = (ListView) view.findViewById(R.id.transactionData1);
        totalMontlyTV = (TextView) view.findViewById(R.id.totalMontly);
        HulkDataBaseAdapter db = new HulkDataBaseAdapter(getActivity());

        // getting from new instance method
        dateposition = getArguments().getInt("index", -1000);
        boolean rgTrack = getArguments().getBoolean("radioGtrack", false);

        // error checking
        if (dateposition == -1000) {
            Toast.makeText(getActivity(), "Something Went Wrong", Toast.LENGTH_SHORT).show();
        } else {
            setDateListView(db, rgTrack);
        }
        return view;
    }

    public void setTextView() {

    }

    public void setDateListView(HulkDataBaseAdapter db, boolean rgTrack) {
        Calendar cal = Calendar.getInstance();
        for (int i = -200; i < 0; i++) {
            if (dateposition == i) {
                cal.add(Calendar.MONTH, i);

                String monthString = String.format("%02d", (cal.get(Calendar.MONTH) + 1));
                String yearString = String.valueOf(cal.get(Calendar.YEAR));
                showListView(monthString, yearString, db, rgTrack);
            }
        }
        // show today month
        if (dateposition == 0) {
            String currentMonth = String.format("%02d", cal.get(Calendar.MONTH) + 1);
            String currentYear = String.valueOf(cal.get(Calendar.YEAR));
            showListView(currentMonth, currentYear, db, rgTrack);
        }
        // Show next month
        for (int i = 1; i <= 200; i++) {
            if (dateposition == i) {
                cal.add(Calendar.MONTH, i);
                String monthString = String.format("%02d", (cal.get(Calendar.MONTH) + 1));
                String yearString = String.valueOf(cal.get(Calendar.YEAR));
                showListView(monthString, yearString, db, rgTrack);
            }
        }
    }

    public void showListView(String currentMonth, String currentYear, HulkDataBaseAdapter db, boolean rgTrack) {
        // init
        String[] catArray = null;
        String[] amountArray = null;
        boolean[] expenseArray = null;
        int currCount = db.selectCatFromDate(currentMonth, currentYear).length;
        // if DB is not empty
        if (currCount != 0) {
            // ADD count to amount and disply it in TextView
            int countAmount = 0;
            // Show each individual (based on RadioGroup)
            if (rgTrack == false) {
                // initialization
                catArray = new String[currCount];
                amountArray = new String[currCount];
                expenseArray = new boolean[currCount];
                // set cat amount expanse to array
                for (int i = 0, c = currCount; i < currCount; i++) {
                    // Show it in reverse (last item first)
                    String catThis = db.selectCatFromDate(currentMonth, currentYear)[i];
                    int amountInt = db.selectAmountFromDate(currentMonth, currentYear)[i];
                    boolean expenseThis = db.selectExpenseFromDate(currentMonth, currentYear)[i];
                    String amountThis;
                    if (expenseThis) {
                        amountInt = amountInt * (-1);
                        countAmount -= amountInt;
                        amountThis = String.valueOf(amountInt);
                    } else {
                        countAmount += amountInt;
                        amountThis = "+"+String.valueOf(amountInt);
                    }

                    // saving in reverse format
                    c--;
                    catArray[c] = catThis;
                    amountArray[c] = amountThis;
                    expenseArray[c] = expenseThis;
                }

                // set the adapter and show it
                CustomAdapter adapter = new CustomAdapter(getActivity(), catArray, amountArray, expenseArray);
                transactionListV.setAdapter(adapter);
                // show count to textview text: Total : x $
                String textCountAll = TEXT_AT_END + countAmount + MoneyManager.DOLLAR;
                totalMontlyTV.setText(textCountAll);
            }

            // Show by Category (based on RadioGroup)
            else {
                String[] catAllArray = db.selectAllCategoryTable();
                int countCat = catAllArray.length;
                String[] amountAllArray = new String[countCat];
                boolean[] expenseAllArray = new boolean[countCat];
                for (int i = 0; i < countCat; i++) {
                    int ThisAmount = db.totalAmountOfCatFromDateCategoryTable(catAllArray[i], currentMonth, currentYear);
                    countAmount += ThisAmount;
                    if (ThisAmount < 0){
                        expenseAllArray[i] = true;
                        amountAllArray[i] = String.valueOf(ThisAmount);
                    }
                    else {
                        expenseAllArray[i] = false;
                        amountAllArray[i] = "+"+String.valueOf(ThisAmount);
                    }
                }

                CustomAdapter adapter = new CustomAdapter(getActivity(), catAllArray, amountAllArray, expenseAllArray);
                transactionListV.setAdapter(adapter);
            }

            String textCountAll = TEXT_AT_END + countAmount + MoneyManager.DOLLAR;
            totalMontlyTV.setText(textCountAll);
        }
        // if Transaction DB is empty
        else {
            String[] noString = { MoneyManager.NOTHING };
            ArrayAdapter<String> adapterNo = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, noString);
            transactionListV.setAdapter(adapterNo);
        }
    }
}

// Custom adapter for List View
class CustomAdapter extends ArrayAdapter<String> {
    Context context;
    String[] categoryArray;
    String[] amountArray;
    boolean[] expanseB;

    public CustomAdapter(Context c, String[] categoty, String[] amount, boolean[] expanse) {
        super(c, R.layout.list_view_in_money_manager, R.id.textView1x, categoty);
        this.context = c;
        this.amountArray = amount;
        this.categoryArray = categoty;
        this.expanseB = expanse;
    }

    int count = 0;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        if (row == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.list_view_in_money_manager, parent, false);
        }

        TextView category = (TextView) row.findViewById(R.id.textView1x);
        TextView amount = (TextView) row.findViewById(R.id.textView2x);

        category.setText(categoryArray[position]);
        amount.setText(amountArray[position] + MoneyManager.DOLLAR);

        if (expanseB[position]) {
            amount.setTextColor(Color.parseColor("#FFFF4444"));
        } else {
            amount.setTextColor(Color.parseColor("#0000FF"));
        }
        return row;
    }
}

最佳答案

如何在 androidmanifest.xml 内的 activity 标签 中添加 android:configChanges="orientation|keyboardHidden|screenSize|keyboard" 它永远不会重新创建您的 View ,甚至改变了您不想管理任何实例管理的方向。如果你想在方向改变期间做一些任务,你可以在你的 Activity 中覆盖 onConfigurationChanged()

关于android - 当我旋转屏幕时出现奇怪的错误,viewpager 内的 ListView 将消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27128107/

相关文章:

android - android中的用户不活动?

android - SwipeRefreshLayout 不允许我向上滚动

c# - 将项目添加到 Listview 控件

android - 工具栏菜单图标不显示

java - 无法在 Eclipse 的 keystore 中找到调试 key

java - android:显示从sqlite到AlertDialog的数据

android - Backstack android fragment 导航

android - 如何使 PreferenceFragment 与 MainActivity 一起工作

android - 难以理解如何支持多屏

excel - 如何使用 Excel 在 VBA 中禁用 ListView 控件中的箭头键