2016-09-06 53 views
0

實際上,我創建了一個導航抽屜,其中有三個項目,並且在點擊每個項目時它會轉到其顯示特定類型產品的片段,因此我有一個包含三個片段的Activity他們的每種類型。只加載一個片段並僅替換它的內容

如果我想添加另一種產品類型,我將不得不創建它的片段。 所以,我的問題是,是否有任何方法只能製作一個片段,每次只有一個片段中的數據被更改/替換,而不是用另一個片段替換整個片段?

編輯我的主要活動:

public class MainActivity extends AppCompatActivity { 


Toolbar toolbar; 

DrawerLayout drawerLayout; 

RecyclerView recyclerView; 

String navTitles[]; 
private NavigationView navigationView; 
TypedArray navIcons; 

RecyclerViewAdapter recyclerViewAdapter; 

ActionBarDrawerToggle drawerToggle; 
Fragment[] fFragments = new Fragment[3]; 

@Override 

protected void onCreate(Bundle savedInstanceState) { 


    super.onCreate(savedInstanceState); 

    setContentView(R.layout.activity_main); 

    //Let's first set up toolbar 

    setupToolbar(); 

    //Initialize Views 

    recyclerView = (RecyclerView) findViewById(R.id.recyclerView); 

    drawerLayout = (DrawerLayout) findViewById(R.id.drawerMainActivity); 


    //Setup Titles and Icons of Navigation Drawer 

    navTitles = getResources().getStringArray(R.array.navDrawerItems); 

    navIcons = getResources().obtainTypedArray(R.array.navDrawerIcons); 

    recyclerViewAdapter = new RecyclerViewAdapter(navTitles, navIcons, this); 

    recyclerView.setAdapter(recyclerViewAdapter); 


    recyclerViewAdapter.setClickedListener(new RecyclerViewAdapter.ClickListerner() { 

     @Override 

     public void onItemlistener(int index) { 

      updateUIWithIndex(index); 

     } 

    }); 


    recyclerView.setLayoutManager(new LinearLayoutManager(this)); 
    //Finally setup ActionBarDrawerToggle 

    setupDrawerToggle(); 


    //Add the Very First Fragment to the Container 

    updateUIWithIndex(1); 


} 



// on click update fragment 
private void updateUIWithIndex(int index) { 


    drawerLayout.closeDrawers(); 


    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 

    Fragment fFragment = null; 


    if (fFragments[index - 1] == null) { 

     switch (index) { 

      case 1: 

       fFragment = new FirstFragment(); 

       break; 

      case 2: 

       fFragment = new SecondFragment(); 

       break; 

      case 3: 

       fFragment = new ThirdFragment(); 

       break; 

     } 

     fFragments[index - 1] = fFragment; 

    } else { 

     fFragment = fFragments[index - 1]; 

    } 

    fragmentTransaction.replace(R.id.containerView, fFragment); 

    fragmentTransaction.commit(); 


} 


void setupToolbar() { 

    toolbar = (Toolbar) findViewById(R.id.toolBar); 

    setSupportActionBar(toolbar); 

    getSupportActionBar().setDisplayShowHomeEnabled(true); 

} 


void setupDrawerToggle() { 

    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name); 

    //This is necessary to change the icon of the Drawer Toggle upon state change. 

    drawerToggle.syncState(); 

} 


} 

我的片段:

public class FirstFragment extends Fragment implements ClickListner { 

private final String LOG_TAG = FirstFragment.class.getSimpleName(); 
private DisplayAdapter recyclerViewAdapter; 
private RecyclerView recyclView; 
private ArrayList<Products> pProduct = null; 

private List<Products> prods = null; 
ProductDbHelper pDB; 
ProgressDialog mJsonDialog; 


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    View myView = inflater.inflate(R.layout.all_products, container, false); 
    pDB = new ProductDbHelper(getActivity()); 
    mJsonDialog = new ProgressDialog(getActivity()); 
    mJsonDialog.setIndeterminate(true); 


    if (pDB.isDataAvailable() == 0) { 
     mJsonDialog.setMessage("Parsing JSON feed..."); 
     mJsonDialog.show(); 
     getFeed(); 

    } else { 

     new FetchDatabaseTask().execute(); 
    } 


    return myView; 
} 


@Override 
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 
    super.onViewCreated(view, savedInstanceState); 

    recyclView = (RecyclerView) view.findViewById(R.id.RecycleList); 


    StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); 

    recyclView.setLayoutManager(layoutManager); 

    recyclerViewAdapter = new DisplayAdapter(getActivity(), new ArrayList<Products>()); 
    recyclView.setAdapter(recyclerViewAdapter); 
    recyclerViewAdapter.setClickListener(this); 


} 

@Override 
public void itemClicked(View view, Parcelable product) { 

    Intent intent = new Intent(getActivity(), DetailActivity.class); 
    intent.putExtra("P", product); 
    startActivity(intent); 

} 

public void getFeed() { 

    RestInterface interfaces = Client.getClient().create(RestInterface.class); 

    Call<List<Products>> call = interfaces.getProductsReport(); 
    call.enqueue(new Callback<List<Products>>() { 

     @Override 
     public void onResponse(Call<List<Products>> call, Response<List<Products>> response) { 

      prods = response.body(); 


      for (int i = 0; i < prods.size(); i++) { 
       pDB.addShop(prods.get(i)); 
      } 

      new FetchDatabaseTask().execute(); 

      if (mJsonDialog.isShowing()) 
       mJsonDialog.dismiss(); 

     } 

     @Override 
     public void onFailure(Call<List<Products>> call, Throwable t) { 

      Log.e(LOG_TAG, "FFFF" + t.toString()); 
     } 
    }); 

} 


public class FetchDatabaseTask extends AsyncTask<Void, Void, List<Products>> { 


    protected void onPreExecute() { 
     mJsonDialog.setMessage("Reading from internal storage..."); 
     mJsonDialog.show(); 

    } 

    @Override 
    protected List<Products> doInBackground(Void... voids) { 

     // get all the shop's products 
     List<Products> lProduct = pDB.getAllShops(); 

     // in the second fragment , sort the products' price in ascending order 
     List<Products> lProduct = pDB.sortShopsAscend(); 


     // in the third fragment sort the products descendingly 
      List<Products> lProduct = pDB.sortShopsDescend(); 

     return lProduct; 
    } 


    protected void onPostExecute(List<Products> shops) { 
     super.onPostExecute(shops); 
     if (shops != null) { 
      if (recyclerViewAdapter != null) { 
       recyclerViewAdapter.setData(shops); 
      } else { 
       pProduct = new ArrayList<>(); 
       pProduct.addAll(shops); 
      } 
     } 


     if (mJsonDialog.isShowing()) 
      mJsonDialog.dismiss(); 
    } 
} 


} 
+0

每個片段的佈局是否完全相同,並且只顯示不同的內容? –

+0

是的,佈局是一樣的 – Suzy

+0

不一定是重複的,但一些好主意。基本上和下面的答案一樣。 http://stackoverflow.com/questions/9245408/best-practice-for-instantiating-a-new-android-fragment –

回答

1

請在MainActivity類的變化:

public class MainActivity extends AppCompatActivity { 

Toolbar toolbar;  
DrawerLayout drawerLayout;  
RecyclerView recyclerView;  
String navTitles[]; 
private NavigationView navigationView; 
TypedArray navIcons;  
RecyclerViewAdapter recyclerViewAdapter;  
ActionBarDrawerToggle drawerToggle;< 

//If you want to use the first fragment only 
FirstFragment fragment = null; 
. 
. 
. 
recyclerViewAdapter.setClickedListener(new RecyclerViewAdapter.ClickListerner() { 

    @Override 

    public void onItemlistener(int index) { 
     //Call this method to close the drawer layout or you can simply call the close method here 
     updateUIWithIndex(index); 

     //Do something depending on the index 
     if(index == 0){ 
      //Call getFeed() for example 
      fragment.getFeed(); 
     } 
     else if(index == 1){ 
      //call another method 
     } 
    } 
}); 
. 
. 
. 

// on click update fragment 
//I don't know if you still need the index in this method 
private void updateUIWithIndex(int index) {  
    //Close the drawer Layout anyway 
    drawerLayout.closeDrawers();  

    if (fragment == null) { 
     FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
     //Create an instance of the FirstFragment 
     fragment = new FirstFragment(); 
     fragmentTransaction.replace(R.id.containerView, fragment);  
     fragmentTransaction.commit();  
    } 


} 
+0

setArguments只能在片段附加到活動之前調用,但是,所以這種方法不相當回答如何在稍後更改顯示的數據 –

+0

Suzy詢問多個導航抽屜項目是否可以導致相同的佈局但使用不同的加載數據,所以我的解決方案是通過'FragmentManager之前的參數發送標籤或其他內容'被調用。然後,使用'onCreateView()'方法,可以檢索參數,數據將根據傳遞的參數而變化。我不知道我的理解是否清楚:) –

+0

沒錯,只會在每次點擊列表項目時更換片段並設置新參數。由於片段另外附加到活動,因此再次調用setArguments將不會執行任何操作。 –

0

你可以簡單地傳遞變量Fragment方法。

完全更新後

你的情況:

組片段場在MainActivity

private FirstFragment firstFragment; 

運行此片段在OnCreate方法MainActivity

FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
firstFragment = null; 
firstFragment = new FirstFragment(); 
fragmentTransaction.replace(R.id.containerView, firstFragment); 
fragmentTransaction.commit(); 

然後更換updateUIWithIndex方法片段的方法,讓你擁有:

recyclerViewAdapter.setClickedListener(new RecyclerViewAdapter.ClickListerner() { 
    @Override 
    public void onItemlistener(int index) { 
     firstFragment.getFeed(index) 
    } 
}); 

證指數getFeed:

public void getFeed(int index) { 

final int currentIndex = index; 

    RestInterface interfaces = Client.getClient().create(RestInterface.class); 

Call<List<Products>> call = interfaces.getProductsReport(); 
call.enqueue(new Callback<List<Products>>() { 

    @Override 
    public void onResponse(Call<List<Products>> call, Response<List<Products>> response) { 
     prods = response.body(); 
     for (int i = 0; i < prods.size(); i++) { 
      pDB.addShop(prods.get(i)); 
     } 
     new FetchDatabaseTask(currentIndex).execute(); 
     if (mJsonDialog.isShowing()) 
      mJsonDialog.dismiss(); 
    } 

    @Override 
    public void onFailure(Call<List<Products>> call, Throwable t) { 
     Log.e(LOG_TAG, "FFFF" + t.toString()); 
    } 
}); 

添加構造函數FetchDatabaseTask

public class FetchDatabaseTask extends AsyncTask<Void, Void, List<Products>> { 

    private int currentIndex = 0; 

    FetchDatabaseTask(int index) { 
     currentIndex = index; 
    } 

    //ur others methods here 
} 

然後你就可以做你需要在onPreExecute,doInBackgroundonPostExecute這樣的方法:

protected void onPostExecute(List<Products> shops) { 
    super.onPostExecute(shops); 

    switch (currentIndex) { 
     case 0: 
      if (shops != null) { 
       if (recyclerViewAdapter != null) { 
        recyclerViewAdapter.setData(shops); 
       } else { 
        pProduct = new ArrayList<>(); 
        pProduct.addAll(shops); 
       } 
      } 
      if (mJsonDialog.isShowing()) 
       mJsonDialog.dismiss(); 
      break; 
     case 1: 
      //ur SecondFragment code 
      break; 
     case 2: 
      //ur ThirdFragment code 
      break; 
    } 
} 

因此,您只能爲每種產品或任何您想要的產品使用一個片段。

+0

如果我的片段例如有這些方法我應該如何通知它來處理doChanges? 公共類MyFragment擴展片段(){// 我的代碼 公共查看onCreateView() 公共無效getDataFromDatabase() 公共無效doChanges(字符串的東西){ myTextView.setText(東西); } } – Suzy

+0

問題是有關導航抽屜點擊後更新的問題,對吧?點擊抽屜項目後你想看什麼? – DEADMC

+0

檢查更新的答案 – DEADMC

相關問題