活动不会从片段

时间:2015-12-05 07:10:34

标签: android android-fragments android-intent android-activity

我正在阅读https://www.udacity.com/course/viewer#!/c-ud853/l-1474559101/e-1480808718/m-1480808721上的教程,目前我正在第3章第11课。我已经完成了教程中提到的所有内容,但我的活动无法启动。是我在清单中放置的内容

    <activity
        android:name=".DetailActivity"
        android:label="@string/title_activity_detail"
        android:parentActivityName=".MainActivity" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.android.sunshine.app.MainActivity" />
    </activity>

这是我的代码,它在onItemClick listener上调用此活动

    listViewForecast.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent detailActivity = new Intent(getActivity(), DetailActivity.class);
            detailActivity.putExtra(Intent.EXTRA_TEXT, mForecastAdapter.getItem(position));
            getActivity().startService(detailActivity);
        }
    });


    return rootView;

正在调用此代码,我正在使用Toast消息来查看它是否正常工作。但是,当我把活动放在那里时,它没有出现新的活动。

这是我的DetailActivity(发布带有ommited菜单的类等)

public class DetailActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
}

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_detail, container, false);

        Intent intent = getActivity().getIntent();
        if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
            String forecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
            ((TextView) rootView.findViewById(R.id.detail_text))
                    .setText(forecastStr);
        }
        return rootView;
    }
}
}

1 个答案:

答案 0 :(得分:2)

做错了

 getActivity().startService(detailActivity);

而不是做

 getActivity().startActivity(detailActivity);

名为startActivity(...)