如何在菜单栏选择后刷新片段选项卡?

How to refresh a fragment tab after a menubar selection?

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

最好的方法是什么? TIA

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

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

通过使用 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();
  }
}