Android 在错误的片段中调用了带有 ViewPager oncreateView 的片段
Android Fragment with ViewPagers oncreateView Called in Wrong Fragment
我有一个主要 activity,它在带有选项卡的查看寻呼机中显示了 3 个片段。
mainActivity.java
public class mainActivity extends AppCompatActivity {
globalVariableActivity variable = new globalVariableActivity();
private APIService mAPIService;
private TextView mResponseTv;
private RecyclerView recyclerView;
private Token token = new Token("","","");
private Gson gson = new Gson();
private Context context=mainActivity.this;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//check if token is still active
String current_token=token.getToken(context);
MyFirebaseInstanceIDService Fcm= new MyFirebaseInstanceIDService();
Fcm.onTokenRefresh(context,current_token);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new BeritaFragment(), "Berita");
adapter.addFragment(new DiskusiFragment(), "Diskusi");
adapter.addFragment(new PesanFragment(), "Pesan");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
//Toast.makeText(context,"Item " + position + " shown.", Toast.LENGTH_SHORT).show();
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
Toast.makeText(context,"Position : " + position + " Title : "+ mFragmentTitleList.get(position) + " shown.", Toast.LENGTH_SHORT).show();
return mFragmentTitleList.get(position);
}
}
interface LyfecycleListener {
void onCreatedView();
}
这是第一个片段代码
beritaFragment.java
public class BeritaFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private APIService mAPIService = APIUtils.getAPIService();;
private Gson gson = new Gson();
private TextView createdAtText;
private TextView judulText;
private ImageView imageView;
private RecyclerView mRecyclerView;
private ListAdapter mListadapter;
private ArrayList<DataBerita> list_berita= new ArrayList<>();
private OnFragmentInteractionListener mListener;
public BeritaFragment() {
}
// TODO: Rename and change types and number of parameters
public static BeritaFragment newInstance(String param1, String param2) {
BeritaFragment fragment = new BeritaFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getBeritaTask getBerita= new getBeritaTask();
try {
Log.d("berita :", "On create 1");
getBerita.execute().get(10000, TimeUnit.MILLISECONDS);
Log.d("berita :", "On create 2");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_berita, container, false);
Log.d("Berita","On create view");
Toast.makeText(getActivity() ,"Berita Fragment onCreateView", Toast.LENGTH_SHORT).show();
ArrayList<DataBerita> data_berita;
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
judulText = (TextView)view.findViewById(R.id.summary_judul);
createdAtText = (TextView)view.findViewById(R.id.created_at);
//imageView = (ImageView)view.findViewById(R.id.gambar);
final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
//data_berita=getBeritaList();
Log.d("Berita","1");
Log.d("Berita List : ", list_berita.toString());
Log.d("Berita","3");
mListadapter = new ListAdapter(list_berita);
mRecyclerView.setAdapter(mListadapter);
//Log.d("Berita view :", view.toString());
return view;
}
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder>
{
private ArrayList<DataBerita> dataList;
public ListAdapter(ArrayList<DataBerita> data)
{
this.dataList = data;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView judulText;
TextView waktuText;
ImageView gambarView;
public ViewHolder(View itemView)
{
super(itemView);
this.judulText = (TextView) itemView.findViewById(R.id.summary_judul);
this.waktuText = (TextView) itemView.findViewById(R.id.created_at);
//this.gambarView = (ImageView) itemView.findViewById(R.id.gambar);
}
}
@Override
public ListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.berita_list_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(ListAdapter.ViewHolder holder, final int position)
{
Uri ImageURI=Uri.parse(dataList.get(position).getGambar_utama());
holder.judulText.setText(dataList.get(position).getSummary_judul());
holder.waktuText.setText(dataList.get(position).getCreated_at());
//holder.gambarView.setImageURI(ImageURI);
holder.itemView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getActivity(), "Item " + position + " is clicked.", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount()
{
return dataList.size();
}
}
private class getBeritaTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
Log.d("Berita","2.1");
}
protected Void doInBackground(Void... voids) {
mAPIService.getBeritaList().enqueue(new Callback<Berita>() {
@Override
public void onResponse(Call<Berita> call, Response<Berita> response) {
list_berita = new ArrayList<>();
DataBerita data_berita = new DataBerita("","","","");
String id_berita;
String judul;
String gambar_utama;
String created_at;
Log.d("Berita","2.2");
if(response.isSuccessful()) {
Berita body = gson.fromJson(response.body().toString(),Berita.class);
for (int i = 0; i < body.getList_berita().getData().size(); i ++) {
id_berita=body.getList_berita().getData().get(i).getId_berita();
judul=body.getList_berita().getData().get(i).getSummary_judul();
gambar_utama=body.getList_berita().getData().get(i).getGambar_utama();
created_at=body.getList_berita().getData().get(i).getCreated_at();
data_berita = new DataBerita(id_berita,judul,gambar_utama,created_at);
list_berita.add(data_berita);
}
Log.d("Berita List",list_berita.toString());
}else{
Log.d("Berita", "Fail");
}
}
@Override
public void onFailure(Call<Berita> call, Throwable t) {
Log.d("Berita Fail", t.getMessage());
}
});
return null;
}
}
这是第 2 和第 3 个片段(这 2 个片段大部分仍然是空的,目前只有 toast 和 log 的代码)
DiskusiFragment.java
public class DiskusiFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public DiskusiFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static DiskusiFragment newInstance(String param1, String param2) {
DiskusiFragment fragment = new DiskusiFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Toast.makeText(getActivity() ,"Diskusi Fragment onCreateView", Toast.LENGTH_SHORT).show();
return inflater.inflate(R.layout.fragment_diskusi, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
问题来了,
片段的 onCreateView 函数似乎在错误的片段中被调用。
当我启动应用程序时,发生了以下情况:
- 项目位置 0、1 和 2 被调用
- 调用创建视图的第一个片段,并立即调用创建视图的第二个片段
接下来会发生什么,取决于我做什么:
当我从第一个片段更改为第二个片段时,创建视图上的第三个片段被调用
当我从第一个片段更改为 => 第三个片段时,创建视图上的第三个片段被调用
当我从第二个片段切换到第一个片段时,创建视图上没有片段调用
当我从第二个片段切换到第三个片段时,创建视图上没有片段调用
当我从第 3 个片段切换到第 2 个片段时,创建视图上没有片段被调用(或者有时第一个片段被调用)
当我从第 3 个片段更改 => 第 1 个片段时,创建视图上的第 1 个片段称为
这是否会发生(关于在错误的片段上调用 onCreateView 函数)?
如果不是,我哪里代码错了?
非常感谢
*编辑:这种行为很正常,我是 android 的新手。非常抱歉给大家带来的不便
"wrong"片段是什么意思? View pager 在导航到下一个片段之前创建下一个片段,以使过渡平稳快速。当片段被创建时,它的生命周期方法被相应地调用,这种行为没有任何问题。如果您想在用户滑动到您的视图寻呼机中的特定片段时执行某些操作,您可以使用 OnPageChangeListener。
FragmentPagerAdapter 在恢复状态中保留了除显示的片段之外的其他片段。
如果你想初始化片段中的东西你应该在什么时候做
OnCreate
被调用。
任何与 UI 相关的正确加载都应该发生在
onViewCreated
此外,如果您想接收有关如何在 ViewPager 中处理片段的更多信息
@Shreyas Shetty answered it really well on this 线程
我有一个主要 activity,它在带有选项卡的查看寻呼机中显示了 3 个片段。
mainActivity.java
public class mainActivity extends AppCompatActivity {
globalVariableActivity variable = new globalVariableActivity();
private APIService mAPIService;
private TextView mResponseTv;
private RecyclerView recyclerView;
private Token token = new Token("","","");
private Gson gson = new Gson();
private Context context=mainActivity.this;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//check if token is still active
String current_token=token.getToken(context);
MyFirebaseInstanceIDService Fcm= new MyFirebaseInstanceIDService();
Fcm.onTokenRefresh(context,current_token);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new BeritaFragment(), "Berita");
adapter.addFragment(new DiskusiFragment(), "Diskusi");
adapter.addFragment(new PesanFragment(), "Pesan");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
//Toast.makeText(context,"Item " + position + " shown.", Toast.LENGTH_SHORT).show();
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
Toast.makeText(context,"Position : " + position + " Title : "+ mFragmentTitleList.get(position) + " shown.", Toast.LENGTH_SHORT).show();
return mFragmentTitleList.get(position);
}
}
interface LyfecycleListener {
void onCreatedView();
}
这是第一个片段代码
beritaFragment.java
public class BeritaFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private APIService mAPIService = APIUtils.getAPIService();;
private Gson gson = new Gson();
private TextView createdAtText;
private TextView judulText;
private ImageView imageView;
private RecyclerView mRecyclerView;
private ListAdapter mListadapter;
private ArrayList<DataBerita> list_berita= new ArrayList<>();
private OnFragmentInteractionListener mListener;
public BeritaFragment() {
}
// TODO: Rename and change types and number of parameters
public static BeritaFragment newInstance(String param1, String param2) {
BeritaFragment fragment = new BeritaFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getBeritaTask getBerita= new getBeritaTask();
try {
Log.d("berita :", "On create 1");
getBerita.execute().get(10000, TimeUnit.MILLISECONDS);
Log.d("berita :", "On create 2");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_berita, container, false);
Log.d("Berita","On create view");
Toast.makeText(getActivity() ,"Berita Fragment onCreateView", Toast.LENGTH_SHORT).show();
ArrayList<DataBerita> data_berita;
mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
judulText = (TextView)view.findViewById(R.id.summary_judul);
createdAtText = (TextView)view.findViewById(R.id.created_at);
//imageView = (ImageView)view.findViewById(R.id.gambar);
final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(layoutManager);
//data_berita=getBeritaList();
Log.d("Berita","1");
Log.d("Berita List : ", list_berita.toString());
Log.d("Berita","3");
mListadapter = new ListAdapter(list_berita);
mRecyclerView.setAdapter(mListadapter);
//Log.d("Berita view :", view.toString());
return view;
}
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder>
{
private ArrayList<DataBerita> dataList;
public ListAdapter(ArrayList<DataBerita> data)
{
this.dataList = data;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView judulText;
TextView waktuText;
ImageView gambarView;
public ViewHolder(View itemView)
{
super(itemView);
this.judulText = (TextView) itemView.findViewById(R.id.summary_judul);
this.waktuText = (TextView) itemView.findViewById(R.id.created_at);
//this.gambarView = (ImageView) itemView.findViewById(R.id.gambar);
}
}
@Override
public ListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.berita_list_layout, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(ListAdapter.ViewHolder holder, final int position)
{
Uri ImageURI=Uri.parse(dataList.get(position).getGambar_utama());
holder.judulText.setText(dataList.get(position).getSummary_judul());
holder.waktuText.setText(dataList.get(position).getCreated_at());
//holder.gambarView.setImageURI(ImageURI);
holder.itemView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getActivity(), "Item " + position + " is clicked.", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount()
{
return dataList.size();
}
}
private class getBeritaTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
Log.d("Berita","2.1");
}
protected Void doInBackground(Void... voids) {
mAPIService.getBeritaList().enqueue(new Callback<Berita>() {
@Override
public void onResponse(Call<Berita> call, Response<Berita> response) {
list_berita = new ArrayList<>();
DataBerita data_berita = new DataBerita("","","","");
String id_berita;
String judul;
String gambar_utama;
String created_at;
Log.d("Berita","2.2");
if(response.isSuccessful()) {
Berita body = gson.fromJson(response.body().toString(),Berita.class);
for (int i = 0; i < body.getList_berita().getData().size(); i ++) {
id_berita=body.getList_berita().getData().get(i).getId_berita();
judul=body.getList_berita().getData().get(i).getSummary_judul();
gambar_utama=body.getList_berita().getData().get(i).getGambar_utama();
created_at=body.getList_berita().getData().get(i).getCreated_at();
data_berita = new DataBerita(id_berita,judul,gambar_utama,created_at);
list_berita.add(data_berita);
}
Log.d("Berita List",list_berita.toString());
}else{
Log.d("Berita", "Fail");
}
}
@Override
public void onFailure(Call<Berita> call, Throwable t) {
Log.d("Berita Fail", t.getMessage());
}
});
return null;
}
}
这是第 2 和第 3 个片段(这 2 个片段大部分仍然是空的,目前只有 toast 和 log 的代码)
DiskusiFragment.java
public class DiskusiFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public DiskusiFragment() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static DiskusiFragment newInstance(String param1, String param2) {
DiskusiFragment fragment = new DiskusiFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Toast.makeText(getActivity() ,"Diskusi Fragment onCreateView", Toast.LENGTH_SHORT).show();
return inflater.inflate(R.layout.fragment_diskusi, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
问题来了,
片段的 onCreateView 函数似乎在错误的片段中被调用。
当我启动应用程序时,发生了以下情况:
- 项目位置 0、1 和 2 被调用
- 调用创建视图的第一个片段,并立即调用创建视图的第二个片段
接下来会发生什么,取决于我做什么:
当我从第一个片段更改为第二个片段时,创建视图上的第三个片段被调用
当我从第一个片段更改为 => 第三个片段时,创建视图上的第三个片段被调用
当我从第二个片段切换到第一个片段时,创建视图上没有片段调用
当我从第二个片段切换到第三个片段时,创建视图上没有片段调用
当我从第 3 个片段切换到第 2 个片段时,创建视图上没有片段被调用(或者有时第一个片段被调用)
当我从第 3 个片段更改 => 第 1 个片段时,创建视图上的第 1 个片段称为
这是否会发生(关于在错误的片段上调用 onCreateView 函数)?
如果不是,我哪里代码错了?
非常感谢
*编辑:这种行为很正常,我是 android 的新手。非常抱歉给大家带来的不便
"wrong"片段是什么意思? View pager 在导航到下一个片段之前创建下一个片段,以使过渡平稳快速。当片段被创建时,它的生命周期方法被相应地调用,这种行为没有任何问题。如果您想在用户滑动到您的视图寻呼机中的特定片段时执行某些操作,您可以使用 OnPageChangeListener。
FragmentPagerAdapter 在恢复状态中保留了除显示的片段之外的其他片段。
如果你想初始化片段中的东西你应该在什么时候做
OnCreate
被调用。
任何与 UI 相关的正确加载都应该发生在
onViewCreated
此外,如果您想接收有关如何在 ViewPager 中处理片段的更多信息
@Shreyas Shetty answered it really well on this 线程