54

我有一个扩展 xml 布局的片段。我的要求是在我的活动恢复时更新片段内所有视图的文本大小。我试过了

    fragment.getView().invalidate();

这似乎没有做这项工作。我也试过

    fragment.getView().requestLayout();

这也不起作用。

在另一个活动中,我有一个 ListFragment 需要做同样的事情。我试过了

    listfragment.getListView().invalidate();

成功了,刷新了我的列表视图并重绘了其中的所有项目。

我不明白为什么一个有效,而另一个无效。

我还看到有人建议启动一个片段事务并用一个新片段替换当前片段,这让我一直想知道

  1. 当我只需要刷新我的片段包含的视图上的文本时,我为什么要创建一个全新的片段并替换我当前的片段。

  2. 片段事务方法将阻止我在我的活动的布局 xml 中定义我的片段,我将不得不以编程方式将片段插入到正确的位置。

有什么简单的方法吗?

4

8 回答 8

28

我不认为有办法做到这一点。片段在 onCreateView() 上重建它的 UI ...但是在创建或重新创建片段时会发生这种情况。

您必须实现自己的 updateUI 方法,或者在哪里指定哪些元素以及它们应该如何更新。这是一个很好的做法,因为无论如何在创建片段时都需要这样做。

但是,如果这还不够,你可以做一些事情,比如用相同的片段替换片段,强制它调用onCreateView()

FragmentTransaction tr = getFragmentManager().beginTransaction();
tr.replace(R.id.your_fragment_container, yourFragmentInstance);
tr.commit()

笔记

要刷新 ListView,您需要调用notifyDataSetChanged()ListView 的适配器。

于 2014-04-18T08:45:09.103 回答
25

就我而言,detach并且attach工作:

 getSupportFragmentManager()
   .beginTransaction()
   .detach(contentFragment)
   .attach(contentFragment)
   .commit();
于 2015-02-01T03:42:28.783 回答
10

使用以下代码再次刷新片段:

FragmentTransaction ftr = getFragmentManager().beginTransaction();                          
ftr.detach(EnterYourFragmentName.this).attach(EnterYourFragmentName.this).commit();
于 2017-06-01T06:06:52.120 回答
8

detach().detach()支持库更新 25.1.0(可能更早)后无法正常工作。此解决方案在更新后工作正常:

getSupportFragmentManager()
    .beginTransaction()
    .detach(oldFragment)
    .commitNowAllowingStateLoss();

getSupportFragmentManager()
    .beginTransaction()
    .attach(oldFragment)
    .commitAllowingStateLoss();
于 2016-12-22T09:35:19.190 回答
1

为了解决这个问题,我使用这个:

Fragment frg = null;
frg = getFragmentManager().findFragmentByTag("Feedback");
final android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
于 2016-08-23T15:09:03.773 回答
1

这在 Fragment 中对我有用:

Fragment frg = null;
Class fragmentClass;
fragmentClass = MainFragment.class;

try {
    frg = (android.support.v4.app.Fragment)     
    fragmentClass.newInstance();
} catch(Exception ex) {
    ex.printStackTrace();
}

getFragmentManager()
    .beginTransaction()
    .replace(R.id.flContent, frg)
    .commit();
于 2017-02-04T13:18:23.977 回答
-1

我正在使用 remove 和 replace 来刷新 Fragment 的内容,例如

final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.remove(resetFragment).commit();
fragmentTransaction.replace(R.id.frame_container,resetFragment).commit();
于 2017-01-27T07:36:44.713 回答
-1

让我们看看下面的源代码。这里片段名称是 DirectoryOfEbooks。后台任务完成后,我正在用当前片段替换框架。所以片段被刷新并重新加载它的数据

    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.widget.DefaultItemAnimator;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.SearchView;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.github.mikephil.charting.data.LineRadarDataSet;

    import java.util.ArrayList;
    import java.util.List;


    /**
     * A simple {@link Fragment} subclass.
     */
    public class DirectoryOfEbooks extends Fragment {

        RecyclerView recyclerView;
        branchesAdapter adapter;
        LinearLayoutManager linearLayoutManager;
        Cursor c;
        FragmentTransaction fragmentTransaction;
        SQLiteDatabase db;
        List<branch_sync> directoryarraylist;

        public DirectoryOfEbooks() {
            // Required empty public constructor
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {


            View view = inflater.inflate(R.layout.fragment_directory_of_ebooks, container, false);
            directoryarraylist = new ArrayList<>();
            db = getActivity().openOrCreateDatabase("notify", android.content.Context.MODE_PRIVATE, null);
            c = db.rawQuery("select * FROM branch; ", null);

            if (c.getCount() != 0) {
                c.moveToFirst();
                while (true) {
                    //String ISBN = c.getString(c.getColumnIndex("ISBN"));
                    String branch = c.getString(c.getColumnIndex("branch"));

                    branch_sync branchSync = new branch_sync(branch);
                    directoryarraylist.add(branchSync);
                    if (c.isLast())
                        break;
                    else
                        c.moveToNext();
                }

                recyclerView = (RecyclerView) view.findViewById(R.id.directoryOfEbooks);
                adapter = new branchesAdapter(directoryarraylist, this.getContext());
                adapter.setHasStableIds(true);
                recyclerView.setItemAnimator(new DefaultItemAnimator());
                System.out.println("ebooks");
                recyclerView.setHasFixedSize(true);
                linearLayoutManager = new LinearLayoutManager(this.getContext());
                recyclerView.setLayoutManager(linearLayoutManager);
                recyclerView.setAdapter(adapter);
                System.out.println(adapter.getItemCount()+"adpater count");

            }
            // Inflate the layout for this fragment
            return view;
        }
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //setContentView(R.layout.fragment_books);
            setHasOptionsMenu(true);
        }
        public void onPrepareOptionsMenu(Menu menu) {
            MenuInflater inflater = getActivity().getMenuInflater();
            inflater.inflate(R.menu.refresh, menu);
            MenuItem menuItem = menu.findItem(R.id.refresh1);
            menuItem.setVisible(true);
        }
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId() == R.id.refresh1) {
                new AlertDialog.Builder(getContext()).setMessage("Refresh takes more than a Minute").setPositiveButton("Refresh Now", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {

                        new refreshebooks().execute();
                    }
                }).setNegativeButton("Refresh Later", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).setCancelable(false).show();

            }
            return super.onOptionsItemSelected(item);
        }

    public class refreshebooks extends AsyncTask<String,String,String>{
        ProgressDialog progressDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
          progressDialog=new ProgressDialog(getContext());
            progressDialog.setMessage("\tRefreshing Ebooks .....");
            progressDialog.setCancelable(false);
            progressDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            Ebooksync syncEbooks=new Ebooksync();
            String status=syncEbooks.syncdata(getContext());
            return status;

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s.equals("error")){
                progressDialog.dismiss();
                Toast.makeText(getContext(),"Refresh Failed",Toast.LENGTH_SHORT).show();
            }
            else{
                fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.mainframe, new DirectoryOfEbooks());
                fragmentTransaction.commit();
                progressDialog.dismiss();
                adapter.notifyDataSetChanged();
                Toast.makeText(getContext(),"Refresh Successfull",Toast.LENGTH_SHORT).show();
            }

        }
    }

    }
于 2017-03-26T06:24:43.943 回答