簡體   English   中英

Android更新數據片段

[英]Android update data fragment

就像3個小時,我嘗試將數據從活動更新為片段。 我檢查了所有頁面,但是沒有用...

我必須做一個BookManager。 我創建了一些課程來做。

我有一個主要活動,其中有兩個片段,第一個片段暫時是空的,第二個片段是我的書籍清單的摘要(書籍的最高價格,平均價格...)。 當我想添加一本書時,我使用了一個新的活動,並在添加這本書之后(工作)取回數據。 我想在添加書籍后刷新片段。

我主要活動的代碼:

public class MainActivity extends AppCompatActivity {

/**
 * 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 ViewPager mViewPager;

private SimpleBookManager bookManager;

public final static int ADD_BOOK_REQUEST = 1;

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

    bookManager = new SimpleBookManager();

    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);

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

}


@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_main, menu);
    return true;
}

@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.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.button_add_menu) {
        Intent intent = new Intent(MainActivity.this, AddBookActivity.class);
        startActivityForResult(intent, ADD_BOOK_REQUEST);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {


    if (requestCode == ADD_BOOK_REQUEST) {
        // On vérifie aussi que l'opération s'est bien déroulée
        if (resultCode == RESULT_OK) {
            // On affiche le bouton qui a été choisi
            String[] valueBook = data.getStringArrayExtra("VALUE");

            Book book = this.bookManager.createBook();

            book.setTitle(valueBook[0]);
            book.setAuthor(valueBook[1]);
            book.setCourse(valueBook[2]);
            book.setIsbm(valueBook[3]);
            book.setPrice((int) Integer.parseInt(valueBook[4]));

        }
    }
}


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

    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).

        switch (position) {
            case 0:
                return PlaceholderFragment.newInstance(position + 1);
            case 1:
                Fragment frag = SummaryFragment.newInstance(bookManager);

                return frag;

        }
        return PlaceholderFragment.newInstance(position + 1);
    }

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

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

在onActivityResult方法中,我添加了這本書,當我回到摘要片段時,我想在這里刷新或最終更新。 我嘗試了FragmentTransaction ,但是提交沒有用,因為我沒有標簽來獲取我的片段(我不知道如何獲取一個片段)...而且我們沒有實例片段的原因,因為我們使用靜態方法來創建它。

我的片段代碼:

public class SummaryFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String BOOKMANAGER = "book";


    // TODO: Rename and change types of parameters
    private String[] info;


    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *

     * @return A new instance of fragment SummaryFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SummaryFragment newInstance(SimpleBookManager bookManager) {

        String[] info = new String[5];

        info[0] = String.valueOf(bookManager.count());
        info[1] = String.valueOf(bookManager.getTotalCost());
        info[2] = String.valueOf(bookManager.getMaxPrice());
        info[3] = String.valueOf(bookManager.getMinPrice());
        info[4] = String.valueOf(bookManager.getMeanPrice());

        SummaryFragment fragment = new SummaryFragment();
        Bundle args = new Bundle();
        args.putStringArray(BOOKMANAGER, info);

        fragment.setArguments(args);

        return fragment;
    }

    public SummaryFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            this.info = getArguments().getStringArray(BOOKMANAGER);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View rootView;
        TextView textView;

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


        textView = (TextView) rootView.findViewById(R.id.nbbook_value);
        textView.setText(this.info[0]);

        textView = (TextView) rootView.findViewById(R.id.totalcost_value);
        textView.setText(this.info[1] + " SEK");

        textView = (TextView) rootView.findViewById(R.id.mostprice_value);
        textView.setText(this.info[2] + " SEK");

        textView = (TextView) rootView.findViewById(R.id.leastprice_value);
        textView.setText(this.info[3] + " SEK");

        textView = (TextView) rootView.findViewById(R.id.averageprice_value);
        textView.setText(this.info[4] + " SEK");

        return rootView;
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {


        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        Activity a;

        if (context instanceof Activity){
            a=(Activity) context;
        }

    }



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

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

}

您可以通過調用FragmentPagerAdapter的getItem方法獲取Fragment實例。

SummaryFragment frag = (SummaryFragment) mSectionsPagerAdapter.getItem(1);

然后在Fragment實例中調用方法以刷新顯示,請確保在調用Fragment上的方法之前檢查null。

if (frag != null) {
        frag.refreshBook(book);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM