我有MainActivity
(延伸Activity
)和一個FooFragment
(延伸Fragment
)。getArguments上的空引用
活動使用newFooInstance
方法實例FooFragment
並設置一些參數吧:
public static FooFragment newInstance(String label) {
FooFragment fooFragment = new FooFragment();
Bundle args = new Bundle();
args.putString("fooLabel", label);
fooFragment.setArguments(args);
return fooFragment;
}
現在,裏面FooFragment
小號onCreate
和onCreateView
我做的:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fooLabel = getArguments().getString("fooLabel"); // null error
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_balanse_period, container, false
);
TextView fooView = (TextView) rootView.findViewById(R.id.fooLabel);
fooView.setText(fooLabel);
return rootView;
}
它產生:
嘗試調用virt ual方法
java.lang.String android.os.Bundle.getString(java.lang.String, java.lang.String)
上的空對象參考*
任何想法我做錯了什麼?
編輯:
定義的主要活動爲:
public class MainActivity extends AppCompatActivity {
然後實例化fooFragment
爲:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragments = new ArrayList<>();
fragments.add(newInstance("bar"));
// Instantiate a ViewPager and PagerAdapter
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new FooPagerAdapter(getSupportFragmentManager(), fragments);
告訴你如何使用'newInstance'方法。我認爲你創建它不使用這種方法。 –
@ h3d0,首先如果您想在活動中使用Fragment,則必須擴展FragmentActivity或其他AppCompatActivity。 – TejaDroid
根據意見添加更多信息。 – Oleg