public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setContentView(R.layout.fragment_main); TypedValue typedValue = new TypedValue(); context.getTheme().resolveAttribute(R.attr.lvBackground, typedValue, true); Log.d(TAG, "onCreate: " + typedValue.data + " " + typedValue.resourceId); Log.d(TAG, "onCreate: " + getActivity().getTheme().toString()); btn = (FloatingActionButton) findViewById(R.id.fab); lv = findViewById(R.id.lv); myToolbar = findViewById(R.id.myToolbar); adapter = new NoteAdapter(getApplicationContext(), noteList); refreshListView(); lv.setAdapter(adapter); setSupportActionBar(myToolbar); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); //设置toolbar取代actionBar initPopUpView(); myToolbar.setNavigationIcon(R.drawable.ic_menu_black_24dp); myToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "onClick: shit"); showPopUpView(); } });怎么修改
时间: 2024-04-26 15:21:48 浏览: 193
Android应用源码之Bundle_Bundle.zip
将上述代码转换为Fragment的实现可以按照以下步骤进行:
1. 将继承关系由Activity改为Fragment,即将类声明改为`public class MainFragment extends Fragment {`
2. 修改onActivityCreated()方法,重写onCreateView()方法,用LayoutInflater.inflate()方法加载布局文件,并返回加载后的View对象,代码如下:
```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
TypedValue typedValue = new TypedValue();
getActivity().getTheme().resolveAttribute(R.attr.lvBackground, typedValue, true);
Log.d(TAG, "onCreate: " + typedValue.data + " " + typedValue.resourceId);
Log.d(TAG, "onCreate: " + getActivity().getTheme().toString());
btn = view.findViewById(R.id.fab);
lv = view.findViewById(R.id.lv);
myToolbar = view.findViewById(R.id.myToolbar);
adapter = new NoteAdapter(getActivity().getApplicationContext(), noteList);
refreshListView();
lv.setAdapter(adapter);
((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); //设置toolbar取代actionBar
initPopUpView();
myToolbar.setNavigationIcon(R.drawable.ic_menu_black_24dp);
myToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: shit");
showPopUpView();
}
});
return view;
}
```
3. 将findViewById()方法改为view.findViewById()方法,因为现在视图层次结构是在onCreateView()方法中创建的。
4. 如果需要在Fragment中使用上下文,请使用getActivity()方法获取Activity的上下文。
需要注意的是,在Fragment中获取Activity的上下文时,需要使用getActivity()方法,并且调用getActivity()方法时要确保Activity已经被创建。另外,如果在Fragment中调用Activity中的控件或方法,可以通过定义一个接口并让Activity实现该接口来完成。
阅读全文