从基本活动中获取片段内容

时间:2014-04-03 18:49:10

标签: android android-fragments

我的应用程序总是使用相同的菜单,所以我定义了一个BaseActivity,每个活动现在都扩展了BaseActivity。

东西是菜单的一个元素用于同步系统。因此,根据我所处的活动,它应该刷新不同的元素:列表视图,地图等......

我可以在onStartMethod上使用SharedPreference了解哪个活动在最顶层。

但是从我的BaseActivity中,我无法检索其中的子活动和片段。

我有:

public class FragmentTabsPdv extends BaseActivity

在FragmentTabsPdv中,我有一个Sherlock Tab,有两个片段:

ListPdvTabFragment extends SherlockFragment  
MapPdvTabFragment extends SherlockFragment

在ListPdvTabFragment中,我想刷新ListView,但我不知道如何从BaseActivity到达它。

当然,我的菜单是在BaseActivity中定义的:

同步菜单启动从服务器获取新内容的AsyncTask,并更新sqlite db。 以及onPostExecute进程的结束,我需要更新我的元素:

 @Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    if (lTiendas == null){
        Toast.makeText(ctx, "Hubo un error al sincronizar los datos, intentalo más tarde", Toast.LENGTH_LONG).show();
    }

    if (BaseActivity.refreshItem != null) {
        String frontActivity = prefs.getString("FrontActivity", "");
        if (!frontActivity.isEmpty()){
            if (frontActivity.equals("ListPdvTabFragment")){
                // get List to Refresh 
            }
        }


        BaseActivity.completeRefresh();
    } else {

        Intent i = new Intent(ctx, DashBoard.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ctx.startActivity(i);

        if ((SplashScreen) ctx != null)
            ((SplashScreen) ctx).finish();
    }

}

标签活动:

public class FragmentTabsPdv extends BaseActivity {
private ArrayList<Pdv> listaPdv;
private Usuario mUser;
private SharedPreferences prefs;
private Context ctx;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ctx = this;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);

    DatabaseHandlerTienda db = new DatabaseHandlerTienda(this);
    // listaPdv = (ArrayList<Pdv>) db.getAllTiendas();
    String jsonUser = prefs.getString("usuario", "");
    Gson gson = new Gson();
    mUser = gson.fromJson(jsonUser, Usuario.class);
    listaPdv = db.getAllTiendas();

    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    ActionBar.Tab tab1 = actionBar.newTab();
    tab1.setText("Lista");
    tab1.setIcon(R.drawable.ic_action_view_as_list);

    ActionBar.Tab tab2 = getSupportActionBar().newTab();
    tab2.setText("Mapa");
    tab2.setIcon(R.drawable.ic_action_location_map);

    // create the two fragments we want to use for display content

    tab1.setTabListener(new TabListener<ListPdvTabFragment>(this, "lista", ListPdvTabFragment.class));
    tab2.setTabListener(new TabListener<MapPdvTabFragment>(this, "mapa", MapPdvTabFragment.class));

    actionBar.addTab(tab1);
    actionBar.addTab(tab2);
}

public ArrayList<Pdv> getListaPdv() {
    return listaPdv;
}

public void setListaPdv(ArrayList<Pdv> listaPdv) {
    this.listaPdv = listaPdv;
}

public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
    private Fragment mFragment;
    private final Activity mActivity;
    private final String mTag;
    private final Class<T> mClass;

    /**
     * Constructor used each time a new tab is created.
     * 
     * @param activity
     *            The host Activity, used to instantiate the fragment
     * @param tag
     *            The identifier tag for the fragment
     * @param clz
     *            The fragment's Class, used to instantiate the fragment
     */
    public TabListener(Activity activity, String tag, Class<T> clz) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
    }

    /* The following are each of the ActionBar.TabListener callbacks */

    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        // Check if the fragment is already initialized
        if (mFragment == null) {
            // If not, instantiate and add it to the activity
            mFragment = Fragment.instantiate(mActivity, mClass.getName());
            ft.add(android.R.id.content, mFragment, mTag);
        } else {
            // If it exists, simply attach it in order to show it
            // ft.attach(mFragment);
            ft.show(mFragment);
        }
    }

    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
        if (mFragment != null) {
            // Detach the fragment, because another one is being attached
            // ft.detach(mFragment);
            ft.hide(mFragment); // Optimize map display
        }
    }

    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
        // User selected the already selected tab. Usually do nothing.
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    case R.id.menu_sync:
        DatabaseHandlerTienda db = new DatabaseHandlerTienda(this);
        ArrayList<Pdv> lTiendas = db.getAllTiendas();

        // adbTienda.notifyDataSetChanged();
        // Toast.makeText(getActivity(), "test", Toast.LENGTH_LONG).show();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

@Override
protected void refresh() {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    ImageView iv = (ImageView) inflater.inflate(R.layout.refresh_action_view, null);

    Animation rotation = AnimationUtils.loadAnimation(this, R.anim.refresh);
    rotation.setRepeatCount(Animation.INFINITE);
    iv.startAnimation(rotation);

    refreshItem.setActionView(iv);
    // Sincronize:

    SyncData sd = new SyncData(ctx);
    sd.execute();
    // GET LISTVIEW FRAGMENT AND UPDATE VIEW
}

}

1 个答案:

答案 0 :(得分:2)

您的菜单项最终应该调用抽象方法,with的签名位于BaseActivity中,其实现在每个子Activity中定义为BaseActivity(例如{{ 1}})。例如:

FragmentTabsPdv

您的孩子public abstract class BaseActivity { protected abstract void refresh(); }

Activity

您似乎想要在public class FragmentTabsPdv extends BaseActivity { protected void refresh(){ // This should update your Fragment } } 的{​​{1}}中调用refresh()方法。由于您在子活动中引用了片段,因此您应该可以从那里进行适当的刷新。

如果您需要获得对显示的onPostExecute()的引用,您应该可以使用AsyncTask&#39; Fragment来执行此操作。您的布局xml应该像Activity一样保存FragmentManager,对吗?可能是身份FrameLayout?使用Fragments android.R.id.content(您可以使用FragmentTabsPdvFragmentManager获取)以获取该内容容器中的getFragmentManager()。然后你可以调用适当的方法。