单击列表项时未显示Android片段

时间:2018-09-18 21:48:10

标签: android listview android-fragments

此刻,我正在Android中尝试使用Fragments,而这一步让我发疯。我在一个包含项目(书)列表的片段中有一个ListView。当我单击列表中的一个项目时,片段应该换成另一个包含该项目详细信息的片段。但是,尽管setOnItemClickListener()方法确实有效,但Fragment并未出现(我已经收到了logcat消息,确认已单击ListView中的项目。我还将另一个logcat消息放入第二个Fragment的onCreateView()方法中,因此片段似乎已创建但并未被夸大...

这里是FFBooksFragment,它是包含项ListView的Fragment:

package com.example.android.gamebookcollector;

public class FFBooksFragment extends Fragment {

    private static final String TAG = "FFBooksFragment";

    private Button ffButton;
    private CustomListAdapter adapter;
    private ListView booksList;

    private static final int STANDARD_APPBAR = 0;
    private static final int SEARCH_APPBAR = 1;

    private int mAppbarState;

    private AppBarLayout viewBooksToolbar, searchBar;



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_ffbooks, container, false);


        viewBooksToolbar = (AppBarLayout) view.findViewById(R.id.viewBooksToolbar);
        searchBar = (AppBarLayout) view.findViewById(R.id.searchBooksToolbar);

        booksList = (ListView) view.findViewById(R.id.booksList);

        setUpGamebooksList();

        ImageView searchIcon = (ImageView) view.findViewById(R.id.ivSearchIcon);
        searchIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "Clicked search icon in standard bar");
                toggleToolbarState();
            }
        });

        ImageView ivBackArrow = (ImageView) view.findViewById(R.id.ivBackArrow);
        ivBackArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "Clicked back arrow in search bar");
                toggleToolbarState();
            }
        });

        return view;
    }

    private void toggleToolbarState() {

        if (mAppbarState==STANDARD_APPBAR) {
            setAppbarState(SEARCH_APPBAR);
        }else {
            setAppbarState(STANDARD_APPBAR);
        }
    }

    private void setAppbarState(int state) {
        Log.d(TAG, "Changing app bar state to " + state);

        mAppbarState = state;

        if(mAppbarState==STANDARD_APPBAR){
            searchBar.setVisibility(View.GONE);
            viewBooksToolbar.setVisibility(View.VISIBLE);


            View view = getView();
            InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

            try{
                inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }catch(NullPointerException e){
                Log.d(TAG, "setAppbar state: Null pointer exception. " + e.getMessage());

            }
        }

        else if (mAppbarState==SEARCH_APPBAR){
            viewBooksToolbar.setVisibility(View.GONE);
            searchBar.setVisibility(View.VISIBLE);

            InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

        }
    }

    private void setUpGamebooksList(){
        final ArrayList<Gamebook> gameBooks = new ArrayList<>();

        gameBooks.add(new Gamebook("1. Book title", "Book authors", "Publisher", "Year", R.drawable.image1));
        gameBooks.add(new Gamebook("2. Book title", "Book authors", "Publisher", "Year", R.drawable.image2));
        gameBooks.add(new Gamebook("3. Book title", "Book authors", "Publisher", "Year", R.drawable.image3));
        gameBooks.add(new Gamebook("4. Book title", "Book authors", "Publisher", "Year", R.drawable.image4));




        adapter = new CustomListAdapter(getActivity(), R.layout.layout_book_list_item, gameBooks, "drawable://");

        /*  Now we call the setAdapter() method on our booksList list and pass it our adapter. */
        booksList.setAdapter(adapter);

        // Set up an onItemClickListener for checking to see if any book in the list is clicked on.
        // If so, go to the book fragment (which is blank for now).
        booksList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "Navigating to book fragment...");
                BookFragment bookFragment = new BookFragment();

                FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragmentContainer, bookFragment);

                // adding a string identifier string to the fragment, not really necessary right now but might as well do it
                fragmentTransaction.addToBackStack(getString(R.string.book_fragment));
                fragmentTransaction.commit();
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        setAppbarState(STANDARD_APPBAR);
    }
}

这是BooksFragment,当单击上述Fragment的ListView中的项目时,应该会显示该书:

package com.example.android.gamebookcollector;

public class BookFragment extends Fragment {

    private static final String TAG = "BookFragment";


    private android.support.v7.widget.Toolbar toolbar;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_book, container, false);
        toolbar = (Toolbar) view.findViewById(R.id.booksToolbar);

        Log.d(TAG, "Book fragment started...");

        // Set up the toolbar
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        setHasOptionsMenu(true);

        ImageView ivBackArrow = (ImageView) view.findViewById(R.id.ivBackArrow);
        ivBackArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "Back arrow clicked");
                // pop the previous fragment off the back stack (i.e. navigate back)
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });

        /*  If the edit button is clicked, go to the edit book fragment */
        ImageView ivEdit = (ImageView) view.findViewById(R.id.iv_edit);
        ivEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "Clicked the edit button...");

                EditBookFragment editBookFragment = new EditBookFragment();
                FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragmentContainer, editBookFragment);

                // adding a string identifier string to the fragment, not really necessary right now but might as well do it.
                // We can retrieve fragments by using their string identifer.
                fragmentTransaction.addToBackStack(getString(R.string.edit_book_fragment));
                fragmentTransaction.commit();
            }
        });
        return view;
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.book_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.menuitem_delete:
                Log.d(TAG, "Delete book...");
                break;

            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:0)

问题是您正在片段返回视图之前执行FindViewById

执行此操作:

在OnActivityCreated中绑定所有视图

请检查片段导入语句

//请导入此

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

public class FFBooksFragment extends Fragment {

    private static final String TAG = "FFBooksFragment";

    private Button ffButton;
    private CustomListAdapter adapter;
    private ListView booksList;

    private static final int STANDARD_APPBAR = 0;
    private static final int SEARCH_APPBAR = 1;

    private int mAppbarState;

    private AppBarLayout viewBooksToolbar, searchBar;



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_ffbooks, container, false);
        return view;
    }
     @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        viewBooksToolbar = (AppBarLayout) getActivity().findViewById(R.id.viewBooksToolbar);
    searchBar = (AppBarLayout) getActivity().findViewById(R.id.searchBooksToolbar);

    booksList = (ListView) getActivity().findViewById(R.id.booksList);

    setUpGamebooksList();

    ImageView searchIcon = (ImageView) getActivity().findViewById(R.id.ivSearchIcon);
        searchIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "Clicked search icon in standard bar");
            toggleToolbarState();
        }
    });

    ImageView ivBackArrow = (ImageView) getActivity().findViewById(R.id.ivBackArrow);
        ivBackArrow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "Clicked back arrow in search bar");
            toggleToolbarState();
        }
    });
    }

    private void toggleToolbarState() {

        if (mAppbarState==STANDARD_APPBAR) {
            setAppbarState(SEARCH_APPBAR);
        }else {
            setAppbarState(STANDARD_APPBAR);
        }
    }

    private void setAppbarState(int state) {
        Log.d(TAG, "Changing app bar state to " + state);

        mAppbarState = state;

        if(mAppbarState==STANDARD_APPBAR){
            searchBar.setVisibility(View.GONE);
            viewBooksToolbar.setVisibility(View.VISIBLE);


            View view = getView();
            InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

            try{
                inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }catch(NullPointerException e){
                Log.d(TAG, "setAppbar state: Null pointer exception. " + e.getMessage());

            }
        }

        else if (mAppbarState==SEARCH_APPBAR){
            viewBooksToolbar.setVisibility(View.GONE);
            searchBar.setVisibility(View.VISIBLE);

            InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

        }
    }

    private void setUpGamebooksList(){
        final ArrayList<Gamebook> gameBooks = new ArrayList<>();

        gameBooks.add(new Gamebook("1. Book title", "Book authors", "Publisher", "Year", R.drawable.image1));
        gameBooks.add(new Gamebook("2. Book title", "Book authors", "Publisher", "Year", R.drawable.image2));
        gameBooks.add(new Gamebook("3. Book title", "Book authors", "Publisher", "Year", R.drawable.image3));
        gameBooks.add(new Gamebook("4. Book title", "Book authors", "Publisher", "Year", R.drawable.image4));




        adapter = new CustomListAdapter(getActivity(), R.layout.layout_book_list_item, gameBooks, "drawable://");

        /*  Now we call the setAdapter() method on our booksList list and pass it our adapter. */
        booksList.setAdapter(adapter);

        // Set up an onItemClickListener for checking to see if any book in the list is clicked on.
        // If so, go to the book fragment (which is blank for now).
        booksList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "Navigating to book fragment...");
                BookFragment bookFragment = new BookFragment();

                FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.fragmentContainer, bookFragment);

                // adding a string identifier string to the fragment, not really necessary right now but might as well do it
                fragmentTransaction.addToBackStack(getString(R.string.book_fragment));
                fragmentTransaction.commit();
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        setAppbarState(STANDARD_APPBAR);
    }
}