2015-11-21 58 views
0

這將會像3個小時,我嘗試將數據從活動更新到片段。我檢查所有頁面,但它沒有工作...Android更新數據片段

我必須做一個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,我添加了這本書,我想在這裏刷新或eventuelly當我回到摘要片段。我嘗試了一個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); 
    } 

} 

回答

0

你可以通過調用FragmentPagerAdapter的方法的getItem得到片段實例。

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

然後在Fragment實例中調用一個方法來刷新顯示,確保在調用Fragment的方法之前檢查null。

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

我可以得到我的碎片,很好^^。但是如何使用片段中的新數據進行刷新。我改變了我的私人attribut info []的價值,現在我想重新使用新數據的oncreateview。 我需要這樣做嗎? public void refreshBook(SimpleBookManager book) String [] info2 = new String [5]; info2 [0] = String.valueOf(book.count()); info2 [1] = String.valueOf(book.getTotalCost()); info2 [2] = String.valueOf(book.getMaxPrice()); info2 [3] = String.valueOf(book.getMinPrice()); this.info = info2; } –

+0

無需再次重新創建片段視圖,只需使用findViewById並更改內容即可找到這些視圖:例如,TextView tv =(TextView)findViewById(R.id.textview); tv.setText(...) –

+0

但是我們需要充氣器來根除它們嗎? –