在错误的片段中调用了带有ViewPagers oncreateView的Android片段

时间:2018-10-16 07:52:57

标签: java android android-fragments android-viewpager fragment-oncreateview

我有一个主要活动,该活动在带有标签的View Pagers中显示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个片段仍然大部分为空,只有烤面包的代码,现在才记录)

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函数似乎在/的错误片段中被调用。

当我启动应用程序时,发生了什么事:

  1. 项目位置0,1和2被称为
  2. 创建视图上的第一个片段被调用,创建视图上的第二个片段被立即调用

接下来会发生什么,取决于我的工作:

当我从第一个片段=>第二个片段更改时,创建视图上的第三个片段被称为

当我从第一个片段=>第三个片段更改时,创建视图上的第三个片段称为

当我从第二个片段=>第一个片段切换时,创建视图上没有片段称为

当我从第二个片段=>第三个片段切换时,在创建视图上没有片段称为

当我从第3个片段=>第2个片段切换时,在创建视图上没有调用任何片段(或者有时在创建视图上调用了第一个片段)

当我从第三个片段=>更改为第一个片段时,创建视图上的第一个片段称为

这是假设的事情吗(关于onCreateView函数在错误的片段上被调用)?

如果没有,我在哪里写错了代码?

非常感谢您

* EDIT:此行为是正常现象,我真的是android新手。非常抱歉给您带来不便

2 个答案:

答案 0 :(得分:0)

“错误”片段是什么意思? View分页器在导航到它之前先创建下一个片段,以使过渡平滑而快速。并且当创建片段时,将相应地调用其生命周期方法,此行为没有任何问题。如果要在用户在视图分页器中滑动到特定片段时执行某些操作,则可以使用OnPageChangeListener。

答案 1 :(得分:0)

除了显示的片段以外,FragmentPagerAdapter还将其他片段保持在恢复状态。

如果要初始化片段中的内容,应在以下情况下进行 OnCreate被调用。

与UI相关的任何事情都应正确加载 onViewCreated

此外,如果您想获得有关如何在ViewPager中处理片段的更多信息

@Shreyas Shettythis线程上很好回答