根据Intent-given标识符向活动添加不同的片段

时间:2013-01-16 20:02:43

标签: android android-layout android-fragments

我正在开发一个应用程序,其中布局layout-small-portrait我想启动包含在一个名为SingleActivity的单个“容器活动”中的不同片段。我将在布局layout-landlayout-large等方面处理不同的问题,但这与我的问题无关。

我有一个活动MainActivity,正如名称所示,它是我的应用程序的主要活动(启动器)。这最初将包含一个ListFragment,其中包含不同的项目供用户按下。

根据用户按下SingleActivity将启动的项目,其内容将对应于与此项目相关的特定Fragment。我的问题从这里开始。当用户按下某个项目时,我会引用我希望在SingleFragment中显示的相应片段。如下图所示:

  String tag = myFragmentReference.getTag();
  Intent i = new Intent(this, SingleActivity.class);
  i.putExtra(SingleActivity.CONST_TAG, tag);
  startActivity(i);

活动成功启动。在SingleActivity我有以下onCreate()方法:

...

// Retrieve the fragment tag from the intent
String tag = getIntent().getStringExtra(CONST_TAG);
Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);

if(fragment == null) {
    // always end up here, this is my problem.
}

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragmentContainer, fragment);
ft.commit();

...

我怀疑fragment始终是null的事实是因为片段尚未膨胀。如果我是对的,我需要做的是在片段标记膨胀之前定义它,以便findFragmentByTag()找到它。这可能吗?

如果有任何不清楚的地方,请告诉我。

我期待听到一些好主意!如果有更好或更聪明的方法来实现这一点,我很想听听你的想法!谢谢:))

2 个答案:

答案 0 :(得分:3)

由于您正在跳转到另一个活动,它将拥有自己的Fragment BackStack,并且该片段将不存在。

您将不得不在新活动中对片段进行充气:

String tag = intent.getStringExtra(CONST_TAG);

    if (getSupportFragmentManager().findFragmentByTag(tag) == null) {
        Fragment fragment = Fragment.instantiate(this, tag, extras);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fragmentContainer, fragment, tag);
        ft.commit();
    }

标记字符串需要包含片段的包位置,例如" com.android.myprojectname.myfragment"

答案 1 :(得分:1)

首先使用SlidingMenu库:https://github.com/jfeinstein10/SlidingMenu 这将对您有所帮助,您的应用程序将更加酷,这是我可以帮助您制作所需内容的唯一方式,这里是代码:

以下是您的MainActivity:

我会尝试解释这个示例代码并根据您的需要使用。

这是BehindContent(SlidingMenu)的ListFragment:

public class ColorMenuFragment extends ListFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.list, null);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        String[] colors = getResources().getStringArray(R.array.color_names);
        ArrayAdapter<String> colorAdapter = new ArrayAdapter<String>(getActivity(), 
                android.R.layout.simple_list_item_1, android.R.id.text1, colors);
        setListAdapter(colorAdapter);
//This array is only to fill SlidingMenu with a Simple String Color.
//I used MergeAdapter from Commonsware to create a very nice SlidingMenu.
    }

    @Override
    public void onListItemClick(ListView lv, View v, int position, long id) {
//This switch case is a listener to select wish item user have been selected,  so it Call
//ColorFragment, you can change to Task1Fragment, Task2Fragment, Task3Fragment.
        Fragment newContent = null;
        switch (position) {
        case 0:
            newContent = new ColorFragment(R.color.red);
            break;
        case 1:
            newContent = new ColorFragment(R.color.green);
            break;
        case 2:
            newContent = new ColorFragment(R.color.blue);
            break;
        case 3:
            newContent = new ColorFragment(android.R.color.white);
            break;
        case 4:
            newContent = new ColorFragment(android.R.color.black);
            break;
        }
        if (newContent != null)
            switchFragment(newContent);
    }

    // the meat of switching the above fragment
    private void switchFragment(Fragment fragment) {
        if (getActivity() == null)
            return;

        if (getActivity() instanceof FragmentChangeActivity) {
            FragmentChangeActivity fca = (FragmentChangeActivity) getActivity();
            fca.switchContent(fragment);
        } else if (getActivity() instanceof ResponsiveUIActivity) {
            ResponsiveUIActivity ra = (ResponsiveUIActivity) getActivity();
            ra.switchContent(fragment);
        }
    }


}

以下是您的BaseActivity类:

它没有滑动,据我所知,你不需要这个。

public class FragmentChangeActivity extends BaseActivity {

    private Fragment mContent;

    public FragmentChangeActivity() {
        super(R.string.changing_fragments);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set the Above View
        if (savedInstanceState != null)
            mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
        if (mContent == null)
            mContent = new ColorFragment(R.color.red);  

        // set the Above View
            //This will be the first AboveView
        setContentView(R.layout.content_frame);
        getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.content_frame, mContent)
        .commit();

        // set the Behind View
            //This is the SlidingMenu
        setBehindContentView(R.layout.menu_frame);
        getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.menu_frame, new ColorMenuFragment())
        .commit();

        // customize the SlidingMenu
            //This is opcional
        getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        getSupportFragmentManager().putFragment(outState, "mContent", mContent);
    }

    public void switchContent(Fragment fragment) {
            // the meat of switching fragment
        mContent = fragment;
        getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.content_frame, fragment)
        .commit();
        getSlidingMenu().showContent();
    }

}

好的,那么如果你想将ColorFragment更改为其他任何东西,请执行以下操作:

首先,选择您要使用的项目:

case 0:
                newContent = new ColorFragment(R.color.red);
                break;

case 0:
            newContent = new ArrayListFragment();
            break;

我只做了一个arraylist,这只是一个简单的例子,你可以做很多事情,然后你可以阅读Fragment来学习如何做不同的事情。

public class ArrayListFragment extends ListFragment {

@Override                               
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            setListAdapter(new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_list_item_1, Listnames.TITLES));

// Listnames是一个带有String [] TITLES;

的类

}

        @Override
        public void onListItemClick(ListView l, View v, int position, long id) {
            Log.i("FragmentList2", "Item clicked: " + id);

            String item = (String) getListAdapter().getItem(position);
        Toast.makeText(getActivity(), item, Toast.LENGTH_LONG).show();

        }

    }

如您所见,它可以根据用户按下的ListFragment(MainActivity)中的哪个项目显示不同的片段。

好吧,如果你误解了什么,请告诉我。