她是我的代码
public static class DetailFragment extends Fragment {
private String forecastData;
private static final String LOG_TAG = DetailFragment.class.getSimpleName();
private static final String FORECAST_SHARE_HASHTAG ="#SunshineApp";
public DetailFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
//receive forecast data from the ForeCast Fragment
Intent intent=getActivity().getIntent();
forecastData=intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v(LOG_TAG,"data is "+forecastData);
TextView textView=(TextView)rootView.findViewById(R.id.detail_text);
textView.setText(forecastData);
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_detailfragment,menu);
MenuItem menuItem=menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
ShareActionProvider mShareActionProvider =
(ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// Attach an intent to this ShareActionProvider. You can update this at any time,
// like when the user selects a new piece of data they might like to share.
if (mShareActionProvider!= null ) {
mShareActionProvider.setShareIntent(createShareIntent());
}
else
{
Log.v(LOG_TAG,"Share Action Provider is null");
}
}
public Intent createShareIntent()
{
Log.v(LOG_TAG,"data is "+forecastData);
Intent intent=new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,forecastData+DetailFragment.FORECAST_SHARE_HASHTAG);
Log.v(LOG_TAG,"data is "+forecastData);
return intent;
}
我绝对相信这个意图是正确的,因为我可以与其他应用分享它并且有效,如果你看到下面的日志,那就很清楚
01-04 18:36:02.370 6121-6121/com.example.droid.sunshine V/DetailFragment﹕ in optionMenu method data is null
01-04 18:36:02.380 6121-6121/com.example.droid.sunshine V/DetailFragment﹕ in create intent data is null
01-04 18:36:02.380 6121-6121/com.example.droid.sunshine V/DetailFragment﹕ in create intent data is null
01-04 18:36:02.650 6121-6121/com.example.droid.sunshine V/DetailFragment﹕ in view method data is Wed, Jan 7 - Clear - 27/24
为什么这样,我认为在OnCreateOptionsMenu()之前调用了OnCreate()视图方法 ?我该怎么做才能纠正这个问题?
答案 0 :(得分:3)
这是一个想法:
根据您的日志,输出首先显示在onCreateOptionsMenu()
方法中,而最后一个输出来自onCreateView()
。这意味着在onCreateOptionsMenu()
之前调用onCreateView
,这可以解释为什么一切都为空。
尝试在其他地方移动setHasOptionsMenu(true)
,也许在构造函数中移动{应用}确保onCreateOptionsMenu()
和onCreate
之后调用onCreateView
。试试吧。
答案 1 :(得分:0)
onCreateView旨在返回视图。
onActivityCreated表示关联的活动已完成其onCreate()方法并已设置。