Viewpager仅显示所需的详细信息一次,而不是在从主屏幕返回时再次显示

问题描述 投票:0回答:2

我从ListView(片段A)调用ViewPager(片段C)。但这只能运作一次。如果我移回我的列表并选择另一个项目,它不会进入列表视图。它只显示片段c的空白布局。

以下是片段A的代码:

public class FragmentA extends Fragment implements AdapterView.OnItemClickListener{

ListView list;
Communicator communicator;
ArrayList<Book> book_a;
ArrayList<String>  book_titles;


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view= inflater.inflate(R.layout.fragment_a,container,false);
    savedInstanceState = getArguments();
    if (getArguments() != null) {
        // savedInstanceState = getArguments();
        book_a = (ArrayList<Book>) getArguments().getSerializable("bookarray");
        book_titles = getList(book_a);
        //Log.d("Frag_a:Title",book_a.get(5).getTitle());
        list= (ListView) view.findViewById(R.id.listview);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,book_titles);
        list.setAdapter(adapter);
        list.setOnItemClickListener(this);
    }
    return view;
}


public ArrayList<String> getList(ArrayList<Book> book2){

    ArrayList<String> list_titles = new ArrayList<String>();
    int size = book2.size();
    for(int i=0;i<size;i++){
        Book object;
        object = book2.get(i);
        list_titles.add(object.title);
    }


    return list_titles;
}

public void setCommunicator(Communicator communicator)
{
    this.communicator = communicator;
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    communicator.respond(position);

}

public interface Communicator{
    public void respond(int index);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if(context instanceof Communicator){
        communicator = (Communicator) context;
    } else {
        throw new RuntimeException(context.toString()+"must implement Communicator");
    }

}

@Override
public void onDetach() {
    super.onDetach();
    communicator = null;
}

}

以下是MainActivity的代码:

public class MainActivity extends AppCompatActivity implements FragmentA.Communicator{

FragmentB f2;
ArrayList<Book> b = new ArrayList<Book>();
FragmentManager manager;
static int flag = 0;
static String search="great";
SearchView sv ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sv = (SearchView) findViewById(R.id.searchView);
    sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            flag = 1;
            search = query;
            getBooks();
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            getBooks();
            return false;
        }
    });

    getBooks();
    /*
    manager = getSupportFragmentManager();
    f1 = (FragmentA) manager.findFragmentById(R.id.fragment);
    f1.setCommunicator(this);*/

}


@Override
public void respond(int index) {
    f2 = (FragmentB) manager.findFragmentById(R.id.fragment2);
    if(f2!=null && f2.isVisible())
    {
        f2.changeData(index);
    }
    else
    {
        Bundle bundle = new Bundle();
        bundle.putInt("index", index);
        bundle.putSerializable("bookarray",(ArrayList<Book>)b);
        Fragment newFragment = new FragmentC();
        newFragment.setArguments(bundle);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();


    }
}

public void afterGetBooks(ArrayList<Book> bks) {
    for (Book h : bks) {
        b.add(h);
    }
    manager = getSupportFragmentManager();
    Bundle args = new Bundle();
    args.putSerializable("bookarray",(ArrayList<Book>)bks);
    FragmentA f1 = new FragmentA();
    f1.setArguments(args);
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.fragment,f1);
    transaction.addToBackStack(null);
    transaction.commit();
    f1.setCommunicator(this);


}

private void getBooks(){

    String url;
    if(flag==0){
    url = "https://kamorris.com/lab/audlib/booksearch.php/";}
    else{
        url = "https://kamorris.com/lab/audlib/booksearch.php?search=" + search;
        flag=0;
    }
    //ArrayList<Book> boo;

    Retrofit retrofit =  new Retrofit.Builder().baseUrl("https://kamorris.com/lab/audlib/booksearch.php/").addConverterFactory(GsonConverterFactory.create()).build();

    Book.API api = retrofit.create(Book.API.class);

    Call<ArrayList<Book>> call = api.getBooks(url);
    call.enqueue(new Callback<ArrayList<Book>>() {
        @Override
        public void onResponse(Call<ArrayList<Book>> call, Response<ArrayList<Book>> response) {

            ArrayList<Book> Books = response.body();
            for(Book h: Books){
                Log.d("Retro-Title",h.getTitle());
                //b.add(h);
            }
            afterGetBooks(Books);
        }

        @Override
        public void onFailure(Call<ArrayList<Book>> call, Throwable t) {
            Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_SHORT).show();
        }
    });


}

下面是片段C的代码:

public class FragmentC extends Fragment {

ViewPager vp;
static int list_pos;
FragmentPagerAdapter adapterViewPager;
public static ArrayList<Book> book_c;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_c,container,false);
    if(getArguments()!= null){

    book_c  = (ArrayList<Book>) getArguments().getSerializable("bookarray");
    list_pos = getArguments().getInt("index");

    }
    vp = (ViewPager) view.findViewById(R.id.viewpager);
    adapterViewPager = new MyPagerAdapter(getFragmentManager());
    vp.setAdapter(adapterViewPager);

    return view;
}

public static class MyPagerAdapter extends FragmentPagerAdapter {
    private static int NUM_ITEMS = 11;

    public MyPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    // Returns total number of pages
    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    // Returns the fragment to display for that page
    @Override
    public Fragment getItem(int position) {
        switch (list_pos) {
            case 0: // Fragment # 0 - This will show FirstFragment
                list_pos = position;
                return FragmentB.newInstance(book_c,0);
            case 1: // Fragment # 0 - This will show FirstFragment different title
                list_pos = position;
                return FragmentB.newInstance(book_c,1);
            case 2: // Fragment # 1 - This will show SecondFragment
                list_pos = position;
                return FragmentB.newInstance(book_c,2);
            case 3: list_pos = position;
                return FragmentB.newInstance(book_c,3);
            case 4:list_pos = position;
                return FragmentB.newInstance(book_c,4);
            case 5:list_pos = position;
                return FragmentB.newInstance(book_c,5);
            case 6:list_pos = position;
                return FragmentB.newInstance(book_c,6);
            case 7:list_pos = position;
                return FragmentB.newInstance(book_c,7);
            case 8:list_pos = position;
                return FragmentB.newInstance(book_c,8);
            case 9:list_pos = position;
                return FragmentB.newInstance(book_c,9);
            default:
                return null;
        }
    }

    // Returns the page title for the top indicator
    @Override
    public CharSequence getPageTitle(int position) {
        return "Page " + position;
    }

}

}

还有一种方法,我可以从我选择的listitem的描述开始我的viewpager。

片段B也只是一个文本视图持有者。

我试着用调试器看到控制流程。但是,当我这样尝试它时片段C中的这些行不起作用..

    {
    book_c  = (ArrayList<Book>) getArguments().getSerializable("bookarray");
    list_pos = getArguments().getInt("index");
    }
    vp = (ViewPager) view.findViewById(R.id.viewpager);
    adapterViewPager = new MyPagerAdapter(getFragmentManager());
    vp.setAdapter(adapterViewPager);
java android android-fragments android-viewpager
2个回答
0
投票

您的片段尚未被销毁,因此当它被带回时,onCreateView没有被调用。而是覆盖setUserVisibleHint。

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // This is true when your fragment is visible, write code to populate view here
    } else {
        // This is true when your fragment is hidden.
    }
}

0
投票

我找到的解决方案是更改片段管理器

adapterViewPager = new MyPagerAdapter(getFragmentManager());

adapterViewPager = new MyPagerAdapter(getChildFragmentManager());
© www.soinside.com 2019 - 2024. All rights reserved.