无法从ViewPager Android Activity中添加或删除页面

时间:2017-05-12 23:50:52

标签: android android-viewpager adapter

我已经阅读了有关此主题的所有stackOverflow答案,其中任何一个都适合我,或者我无法自己制作。

正如您在下面的代码中看到的,我从Android Studio添加了默认的ViewPager活动,现在我需要添加新页面或从相应的按钮中删除现有页面。

因此,活动正确加载并获得正确的页数,我也可以成功更改每个页面中的信息。正如您所看到的,应用程序已连接到Firebase,我从那里获得了我的活动应该具有的总页数(狗),这很有效。

现在,如何添加新页面,移至该页面以及更新适配器和总页数?

删除相同,如何删除当前页面,然后移动到另一个页面并更新适配器没有问题?

我对此感到非常疯狂,花了一整天的时间在stackoverflow中找到了不同的解决方案,但却无法实现。我现在很困惑何时使用" notifyDataSetChanged()",如果这是一个好主意,则覆盖" getItemPosition"或不,等等。

如果有人能够帮我调整我的项目的答案,我会很感激,它是默认的ViewPager,只是修改了小部件以尝试解决它,但不知道我还能做些什么。

提前谢谢你,对不起我的英语。

注意:某些功能如" updateIntValueFromCurrentUser()"在MainActivity中声明但是有效,它们与firebase查询等有关,所以我不关注它。

public class DummyViewPagerActivity extends MainActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private static ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

//Creating menu bar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_dummy_view_pager, menu);
    return true;
}
//Creating the two buttons to save and delete the images
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.

    switch (item.getItemId()) {
        case R.id.add:

            updateIntValueFromCurrentUser("dogs_number", person.getDogs_number()+1);
            return true;
        case R.id.edit:

            return true;
        case R.id.delete:

            updateIntValueFromCurrentUser("dogs_number", person.getDogs_number()-1);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = null;
        try {
            rootView = inflater.inflate(R.layout.fragment_dummy_view_pager, container, false);
            TextView dogName = (TextView) rootView.findViewById(R.id.dog_name);
            dogName.setText(allDogs.get((getArguments().getInt(ARG_SECTION_NUMBER)) - 1).getName());
        } catch (Exception e) {
            Log.e("RaisedException()", e.getMessage());
        }
        return rootView;
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getItemPosition(Object object) {
    // POSITION_NONE makes it possible to reload the PagerAdapter
        return POSITION_NONE;
    }

    @Override
    public int getCount() {
        // Show x total pages.
            return person.getDogs_number();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}

}

1 个答案:

答案 0 :(得分:1)

从FragmentViewPager添加/删除项目有点棘手:

尝试使用此适配器,让我知道它是否适合您。

enter code here


public class Emp4 {

    private JFrame frame;
 private JTextField jtxtName;
 private JTextField jtxtAge;
 private JTextField jtxtSal;
  private JTextField jtxtHour_Pay;
    private JTextField jtxtHour_Worked;


     public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Emp4 window = new Emp4();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
                }
        }
        });
    }

    public Emp4() {
    initialize();
    }


    private void initialize() {
    frame = new JFrame();
    frame.setBounds(0, 0, 1000, 800);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JPanel panel = new JPanel();
    panel.setBorder(new LineBorder(new Color(0, 0, 0), 3));
    panel.setBounds(30, 11, 414, 36);
    frame.getContentPane().add(panel);
    panel.setLayout(null);

    JLabel lblEmployeeDatabase = new JLabel("Employee Database");
    lblEmployeeDatabase.setFont(new Font("Tahoma", Font.PLAIN, 15));
    lblEmployeeDatabase.setBounds(157, 7, 193, 25);
    panel.add(lblEmployeeDatabase);

    JPanel panel_1 = new JPanel();
    panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 3));
    panel_1.setBounds(10, 61, 464, 230);
    frame.getContentPane().add(panel_1);
    panel_1.setLayout(null);

    JLabel jlblEmpName = new JLabel("Employee Name");
    jlblEmpName.setBounds(10, 11, 110, 14);
    panel_1.add(jlblEmpName);

    jtxtName = new JTextField();
    jtxtName.setBounds(114, 8, 120, 20);
    panel_1.add(jtxtName);
    jtxtName.setColumns(10);

    JLabel jlblEmpAge = new JLabel("Employee Age");
    jlblEmpAge.setBounds(10, 52, 110, 14);
    panel_1.add(jlblEmpAge);

    jtxtAge = new JTextField();
    jtxtAge.setColumns(10);
    jtxtAge.setBounds(114, 49, 120, 20);
    panel_1.add(jtxtAge);

    JLabel jlblEmpType = new JLabel("Employee Type");
    jlblEmpType.setBounds(10, 95, 110, 14);
    panel_1.add(jlblEmpType);

    JRadioButton jrdbuttonFullTime = new JRadioButton("Full Time");
    JRadioButton jrdbtnContract = new JRadioButton("Contract ");
    JLabel jlblEmpHour = new JLabel("Hourly Rate");
    jlblEmpHour.setBounds(5, 121, 66, 14);
    ButtonGroup group =new ButtonGroup();
    JLabel jlblEmpSal = new JLabel("Salary");
    jlblEmpSal.setBounds(114, 121, 66, 14);
    JLabel jlblEmpWork = new JLabel("Hours Worked");
    jlblEmpWork.setBounds(150, 120, 86, 24);

    jtxtSal = new JTextField();
    jtxtSal.setColumns(10);
    jtxtSal.setBounds(164, 121, 109, 23);

    jtxtHour_Pay = new JTextField();
    jtxtHour_Pay.setColumns(10);
    jtxtHour_Pay.setBounds(75, 121, 59, 23);

    jtxtHour_Worked = new JTextField();
    jtxtHour_Worked.setColumns(10);
    jtxtHour_Worked.setBounds(243, 121, 109, 23);

    group.add(jrdbuttonFullTime);
    group.add(jrdbtnContract);

    jrdbuttonFullTime.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(jrdbuttonFullTime.isSelected()){
                //jrdbtnContract.setSelected(false);

                panel_1.add(jlblEmpSal);
                panel_1.add(jtxtSal);
                jlblEmpHour.setVisible(false);
                jtxtHour_Pay.setVisible(false);
                jtxtHour_Worked.setVisible(false);
                jlblEmpWork.setVisible(false);
            }

        }
    });


    jrdbuttonFullTime.setBounds(113, 91, 109, 23);
    panel_1.add(jrdbuttonFullTime);



    jrdbtnContract.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if(jrdbtnContract.isSelected()){
                //jrdbuttonFullTime.setSelected(false);

                panel_1.add(jlblEmpHour);
                panel_1.add(jtxtHour_Pay);
                panel_1.add(jlblEmpWork);
                panel_1.add(jtxtHour_Worked);
                jlblEmpSal.setVisible(false);
                jtxtSal.setVisible(false);
            }


        }
    });
    jrdbtnContract.setBounds(218, 91, 109, 23);
    panel_1.add(jrdbtnContract);






      }
    }