一个片段类的两个实例不正确

时间:2018-12-14 00:01:19

标签: java android android-fragments

我创建了选项卡式活动,该活动具有带有一个片段类的两个实例的viewpager。这个片段包含列表框,我写了一些函数来 与listview项进行交互,并且活动中的一项功能可以完成相同的操作。关键是当我尝试调用片段方法时,它总是尝试更新首先创建的片段的列表视图,但是当我从活动中调用函数时,它的工作原理是绝对正确的。有什么问题吗?

这是活动代码:

public class CategoriesActivity extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    SparseArray<Fragment> registeredFragments = new SparseArray<>();

    Toolbar toolbar;

    FloatingActionButton btnAddCategories;

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

        assignElements();
        prepareToolbar();
        prepareEelements();

    }

    public void assignElements() {
        toolbar = findViewById(R.id.action_bar);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        btnAddCategories = findViewById(R.id.btnAddCategory);
        // Set up the ViewPager with the sections adapter.
        mViewPager = findViewById(R.id.container);
    }
    public void prepareToolbar() {
        toolbar.setTitle("Категории");
        toolbar.setTitleTextColor(getResources().getColor(R.color.colorTextLight));
        toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    public void prepareEelements() {
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = findViewById(R.id.tabs);

        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));

        btnAddCategories.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TabCategoriesFragment tabCategoriesFragment = (TabCategoriesFragment) getRegisteredFragment(mViewPager.getCurrentItem());
                tabCategoriesFragment.addNewCategory();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch(id) {
            case R.id.home:
                finish();
                break;
            case R.id.homeAsUp:
                finish();
                break;
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public Fragment getRegisteredFragment(int position) {
        return registeredFragments.get(position);
    }
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            Fragment fragment = (Fragment) super.instantiateItem(container, position);
            registeredFragments.put(position, fragment);
            return fragment;
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = null;
            switch (position) {
                case 0:
                    fragment = TabCategoriesFragment.newInstance(false);
                    break;
                case 1:
                    fragment = TabCategoriesFragment.newInstance(true);
                    break;
            }
            return fragment;
        }

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

和片段:

public class TabCategoriesFragment extends Fragment {
    private static final String ARG_INCOMING = "Incoming";


    private OnFragmentInteractionListener mListener;

    public int Incoming = -1;

    ListView listView;
    ArrayList<Categories> categories;
    CategoriesListViewAdapter categoriesListViewAdapter;
    DBHelper dbHelper;
    SQLiteDatabase sqLiteDatabase;

    public TabCategoriesFragment() {
    }
    public int selectedPostion;

    public static TabCategoriesFragment newInstance(boolean Incoming) {
        TabCategoriesFragment fragment = new TabCategoriesFragment();
        Bundle args = new Bundle();
        args.putBoolean(ARG_INCOMING, Incoming);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            if (getArguments().getBoolean(ARG_INCOMING)) {
                Incoming = 1;
            } else {
                Incoming = 0;
            }
        }
    }

    public void assignElements(View view) {
        dbHelper = new DBHelper(getContext());
        sqLiteDatabase = dbHelper.getWritableDatabase();
        categories = new ArrayList<>();
        categoriesListViewAdapter = new CategoriesListViewAdapter(getContext(), categories);
    }

    @SuppressLint("ClickableViewAccessibility")
    public void prepareElements() {
        filldata();
        listView.setAdapter(categoriesListViewAdapter);
        categoriesListViewAdapter.notifyDataSetChanged();
        registerForContextMenu(listView);
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                selectedPostion = position;
                getActivity().openContextMenu(listView);
                return true;
            }
        });
    }

    public void deleteCategory(boolean deletecosts, String name) {
        try {
            //delete from db
        } catch (Exception e) {
            Toast.makeText(getContext(), "Произошла ошибка" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    public String getTableName() {
        if (Incoming == 1) {
            return "incomingcategories";
        } else {
            return "outcomingcategories";
        }
    }

    public String getSign() {
        if (Incoming == 1) {
            return ">";
        } else {
            return "<";
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        Objects.requireNonNull(getActivity()).getMenuInflater().inflate(R.menu.edit_category_menu, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        //final int selectedPostion = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position;
        int id = item.getItemId();
        final CheckBox checkBox = new CheckBox(getContext());
        switch (id) {
            case R.id.categoryDelete:
                        deleteCategory(categories.get(selectedPosition);
                        filldata();
                        categoriesListViewAdapter.notifyDataSetChanged();
            case R.id.categorySetbydefault:
                        break;

           case R.id.categoriesSetBydefault:
          setCategoryBydefault(categories.get(selectedPostion).description);
                filldata();
                categoriesListViewAdapter.notifyDataSetChanged();
                break;
        }
        return true;
    }

        public void setCategoryBydefault(String name) {


   //set
        }

    @Override
    public void onStart() {
        super.onStart();
        prepareElements();
        CategoriesActivity categoriesActivity = (CategoriesActivity) getActivity();
    }

    public void filldata() {
        categories.clear();
        //do some stuff
    }

    public void addNewCategory() {
       //do some stuff
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab_categories, container, false);
        listView = view.findViewById(R.id.CategoriesListView);
        assignElements(view);
        return view;
    }

    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }
}

0 个答案:

没有答案