仅加载一个片段并仅替换其内容

时间:2016-09-06 13:52:50

标签: android android-fragments navigation-drawer

实际上,我创建了一个导航抽屉,它有三个项目,点击每个项目到它的片段,显示某种类型的产品,所以我有一个活动,每种类型的三个片段。

如果我想添加其他产品类型,我将不得不创建其片段。 所以,我的问题是,是否有任何方法只能创建一个片段,每次单击一个项目时,只需要更改/替换片段内的数据,而不是用另一个片段替换整个片段本身?

编辑我的主要活动:

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


}

2 个答案:

答案 0 :(得分: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();     
    }


}

答案 1 :(得分: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
}

然后,您可以按照onPreExecutedoInBackgroundonPostExecute这样的方法执行此操作:

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

因此,您只能为每种类型的产品或任何您想要的产品使用一个片段。