請幫幫我。我想顯示片段類List到MainActivity中。我嘗試主要活動new();但它顯示空白頁面,但是當我將所有數據放入mainActivity並運行時,它會顯示數據列表。實際上,我想學習如何從其他課程中獲取這種方法,使其成爲主要活動。如何在MainActivity類中調用單獨Fragement類的onCreateView?
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new ForecastFragment();
}
//----------------- A Separate ForecastFragment Class ------
public class ForecastFragment extends Fragment {
public ForecastFragment() {
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String[] data={
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
ArrayAdapter<String> adapter;
View rootView=inflater.inflate(R.layout.list_item_forecast,container,false);
ListView listView =(ListView)rootView.findViewById(R.id.listview);
List<String> listData=new ArrayList<String>(Arrays.asList(data));
adapter=new ArrayAdapter<String>(
getActivity(),R.layout.list_item_forecast,R.id.textView,listData);
listView.setAdapter(adapter);
return rootView;
}
}
謝謝Shadab Ansari先生,之後將ForecastFragment.getClass更改爲ForecastFragment.class並添加.cummit();比它的工作。現在它可以工作。 :) – Santosh
哦,是的,我錯過了添加提交()。感謝您的注意。爲未來編輯我的答案。 –