2013-03-07 62 views
39

我有一个片段,膨胀一个XML布局。我的要求是当我的活动恢复时更新我片段内所有视图的文本大小。我试过刷新或强制重绘片段

fragment.getView().invalidate(); 

哪个似乎没有做的工作。我也试过

fragment.getView().requestLayout(); 

哪些也没有工作。

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

listfragment.getListView().invalidate(); 

的伎俩,刷新我的列表视图,并重新绘制它里面的所有物品。

我不明白为什么一个作品,但不是其他。

我也看到有人建议启动片段交易,并更换一个新的当前片段,它使我想知道

  1. 我为什么要创造一个全新的片段取代我当我需要的是刷新我的片段包含的视图上的文本。

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

有没有简单的方法呢?

+0

更新的已知属性'喜欢的文字大小TextView'不是那种的事你应该需要调用'invalidate()';该框架会在属性更改时为您执行此操作。也许显示你正在更新文本属性的代码;问题更可能出现在那里。您唯一需要手动使视图无效()的方法是创建Android不知道的自定义属性。 – Devunwired 2013-03-07 04:39:55

+0

该片段负责加载其包含的所有视图中的数据,并在填充该数据时检查用户从“首选项”设置的文本大小,并在此时设置该大小。我相信如果尺寸发生显着变化,视图必须调整自己来包装内容,因此需要重新绘制。即使它是一个自定义属性而不是文本大小,我们如何强制片段视图重绘自己? – ps2010 2013-03-07 13:48:39

+0

同样,当你设置文本值时,视图/布局系统知道它需要重新测量和重新绘制。只需看看TextView源代码中的setRawTextSize()行(2406行)......更新属性后会调用什么? https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/widget/TextView.java另外,'invalidate()'不会强制视图调整自己,'requestLayout()'做到这一点。 – Devunwired 2013-03-07 15:34:31

回答

24

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

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

然而,如果这还不够,你可以不喜欢与同一个替换片段迫使它来调用onCreateView()

​​

注意

要刷新你需要调用notifyDataSetChanged()上的ListView ListView的适配器。

+0

对于我的用例,再次添加视图做了诀窍。 – 2014-09-22 21:10:12

+0

任何帮助在这里:http://stackoverflow.com/questions/40095826/how-to-update-a-fragment-that-has-a-gridview-populated-from-sqlite/40096402?noredirect=1#comment67569523_40096402 – Si8 2016-10-20 10:00:01

19

在我的情况下,detachattach适合我。

getSupportFragmentManager() 
       .beginTransaction() 
       .detach(contentFragment) 
       .attach(contentFragment) 
       .commit(); 
+0

@ swooby为什么呢? – 2015-04-18 23:32:34

+0

原始文本已更新w /我的评论,使我的评论不再相关,所以我删除它。 – swooby 2015-04-21 00:08:48

+9

这个解决方案损害了我的背部堆栈 – ElizaS 2015-05-10 14:02:18

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(); 
+0

标签在哪里?我如何找到它?我正在给Sqlite Db添加一些东西。一旦完成,我想从Acvitiy中刷新片段。 – Si8 2016-10-20 09:59:14

3

detach().detach()支持库更新25.1.0后不工作(可能更早)。

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

getSupportFragmentManager() 
    .beginTransaction() 
    .attach(oldFragment) 
    .commitAllowingStateLoss(); 
+0

在更新到更新的支持库版本之前,所有工作都正常,但此解决方案救了我!快速提示 - 我必须使用'runOnUiThread()'来使用'commitNowAllowingStateLoss',但如果没有它,它就无法工作。 – 2017-02-04 01:21:37

-1

我使用捞出像

final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
fragmentTransaction.remove(resetFragment).commit(); 
fragmentTransaction.replace(R.id.frame_container,resetFragment).commit(); 
+0

你的建议会导致应用程序崩溃。 – 2017-02-16 16:08:31

1

这从片段中为我工作同时替换为片段的提神内容:

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

该解决方案更新后工作正常让我们看看下面的源代码。这里的片段名称是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(); 
      } 

     } 
    } 

    } 
0

使用清爽的片段下面的代码再次:​​

FragmentTransaction ftr = getFragmentManager().beginTransaction();       
ftr.detach(EnterYourFragmentName.this).attach(EnterYourFragmentName.this).commit();