【问题标题】:How to refresh a fragment tab after a menubar selection?选择菜单栏后如何刷新片段选项卡?
【发布时间】:2015-02-27 17:30:45
【问题描述】:

在我的应用程序中的片段选项卡之间浏览时,我要返回的选项卡会自动从过时的视图刷新到当前视图。在菜单栏中进行选择后,我还想让我的应用程序刷新当前选项卡。

最好的方法是什么? TIA

【问题讨论】:

  • 您在实现该逻辑时遇到了哪些问题?
  • @Luksprog 我已经更新了代码。谢谢。
  • 在您的代码中,您再次添加一个已添加到布局中的片段。为什么不简单地获取对该片段的引用,然后对其调用刷新方法来更新它?
  • ...我认为这就是我想要做的。随意提出一个答案。谢谢。
  • 如果这就是你想要做的全部,我认为正确的方法是使用PreferenceonPreferenceChangeListener

标签: android android-activity android-fragments android-actionbar android-menu


【解决方案1】:

在你的片段中创建一个更新方法。

public class MyFragment extends Fragment {
    public void update(){
        //TODO: Do Update
    }
}

在你的 MainActivity 中创建一个这样的方法。当你需要刷新片段时调用它。

public void refreshData(){
    try {
        MyFragment fragment = (MyFragment) getFragmentManager().findFragmentById(R.id.container);
        fragment.update();
    } catch (ClassCastException e) {
        //MyFragment not active, do nothing
    }
}

【讨论】:

  • 有趣。更新方法不需要是静态的才能从 Activity 调用吗?您是否还建议 .beginTransaction/.replace/.commit 进入片段类中的 update() 方法?谢谢。
  • 不,不。您正在从FragmentManager 获取片段对象。当你显示它时它应该已经被实例化了。由于片段可以访问自己的视图,因此它不需要通过FragmentManager 来更新自身。这是@Luksprog 建议的解决方案。
  • 好的,那么片段类中的update()调用了什么?感谢您的耐心等待。
  • 只有你自己知道。出于所有意图和目的,您没有共享任何代码。我或其他任何人都无法知道您的更新内容。
  • 谢谢,我在我的问题中分享了更多代码。另外,我在上面添加了您建议的答案的实现。再次感谢您的耐心等待。
【解决方案2】:

通过使用 FragmentManager 将过时的片段替换为新片段来获得它。 现在可以选择触发事件的 ActiveView 菜单项,并将活动片段替换为当前片段,显示下面的每个屏幕截图。

将这些放在一起的问题主要与识别要在 FragmentManager 语法中使用的正确 R.id.layout 引用有关。我已经发布了相关的 XML 和 java 代码,希望其他人会发现它有用。

MainActivity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
  **android:id="@+id/fragment_placeholder"**
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
</LinearLayout>   

dataCapture.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:tag="data_capture"
android:id="@+id/data_capture"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">  
tools:context=".dataCapture" >
...
 <TextView
    style="@style/colorSizeStylexml"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dip"
    android:text="Tracklog: " />

     <TextView
         android:id="@+id/textViewOff"
         android:layout_width="40dp"
         android:layout_height="40dp"
         android:gravity="center"
         android:textAppearance="?android:attr/textAppearanceMedium"
         android:layout_marginRight="10dip"
         android:text="OFF"
         android:background="#ff000000"
         android:textStyle="bold"
         android:focusableInTouchMode="true"
         android:textColor="#ffffffff" />
     <TextView
         android:id="@+id/textViewOn"
         android:layout_width="40dp"
         android:layout_height="40dp"
         android:gravity="center"
         android:textAppearance="?android:attr/textAppearanceMedium"
         android:layout_marginRight="10dip"
         android:text="ON"
         android:background="#ff58ff2d"
         android:textStyle="bold" />
 </LinearLayout>
 ...
 </LinearLayout> 

Activity.java

public class MainActivity extends Activity{
static int iTrackLogFlag = 0; //if value = (0) Tracklog is off, if (1)  Tracklog is on
public dataCapture dataCapture;
...
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ...
    //put Actionbar in tab mode
    ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    //set titles for tabs
    ActionBar.Tab dataCaptureTab = actionBar.newTab().setText("DataCapture");
    ActionBar.Tab dataEditTab = actionBar.newTab().setText("DataEdit");
    ...

     /*******************************************************************************************
     *  Create instances of each of the fragments. dataCapture is refreshed several times from
     *  fragmentManager (ActiveBar menutab for tracklog ON-OFF, and at closure of lookup table
     *  edit PopupWindows) hence the different format.
     *******************************************************************************************/
    //Fragment dataCaptureFragment = new dataCapture();
    android.app.FragmentManager fragmentManager = getFragmentManager();
    android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    dataCapture dataCapture = new dataCapture();
    fragmentTransaction.add(dataCapture,"data_capture");
    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();

    Fragment dataEditFragment = new dataEdit();
    ...
    //attach those fragment instances to their respective tabs
    dataCaptureTab.setTabListener(new MyTabsListener(dataCapture));
    dataEditTab.setTabListener(new MyTabsListener(dataEditFragment));
    ...
    //add each tab to the ActionBar
    actionBar.addTab(dataCaptureTab);
    actionBar.addTab(dataEditTab);
    ...
    if (savedInstanceState == null){//...do nothing
    }else if (savedInstanceState != null){
        actionBar.setSelectedNavigationItem(savedInstanceState.getInt(TAB_KEY_INDEX,0));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.corax, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.menuitem_tracklogOnOff:
            openTracklogDialog();//opens a dialog box...trying to minimize clutter in the toolbar.
            //
            return true;
    }
    return false;
}
private void openTracklogDialog(){

    AlertDialog.Builder TracklogDialog = new AlertDialog.Builder(this);
    TracklogDialog.setTitle("Tracklog control");
    TracklogDialog.setMessage("Press a button below to start or stop the tracklog.");
    TracklogDialog.setPositiveButton("STOP",new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            iTrackLogFlag = 0;//"0" means OFF, sets button on frontend to black w/white letters OFF
        }
    });
    TracklogDialog.setNegativeButton("START",new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //Toast.makeText(getApplicationContext(), "Tracklog started.", Toast.LENGTH_LONG).show();
            iTrackLogFlag = 1;//"1" means ON, sets button to green w/black letters

            Fragment currentFragment = (dataCapture)getFragmentManager().findFragmentByTag("data_capture");
            if(currentFragment == null) {
                Toast.makeText(appContext, "This == NULL.", Toast.LENGTH_SHORT).show();
                currentFragment = new dataCapture();
            }else if(currentFragment != null){
                getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                getFragmentManager().beginTransaction().replace(R.id.fragment_placeholder, new dataCapture(),"data_capture").addToBackStack(null).commit();
                Toast.makeText(appContext, "This != NULL. currentFragment = "+currentFragment+", dataCapture = "+dataCapture+".", Toast.LENGTH_LONG).show();
            }
            dialog.dismiss();
        }
    });
    AlertDialog alert = TracklogDialog.create();
    alert.show();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多