我的Android导航抽屉活动发生了什么变化?

时间:2016-08-08 11:59:13

标签: java android android-fragments navigation-drawer

我正在构建一个OpenGL动态壁纸。我决定在我的主要活动中安装导航抽屉,因为用户可以访问许多功能。

问题/问题 如果我按下"硬件"后退按钮通常关闭应用程序显示的初始片段只刷新,应用程序永远不会关闭。如果我点击主页按钮并返回应用程序,一切都是黑屏。我在谷歌的所有搜索中都认为,我可能没有正确地破坏MainActivity或者终止片段。我尝试在主要活动的onDestroy方法中调用finish()。我尝试在网上找到每个帖子的片段管理器中使用片段管理器中的remove方法。没有任何效果。我很难过。我在onDestroy方法和片段onDetach方法的主要活动中设置了调试点,没有产生错误或给出任何信息。在这一点上,我无能为力。这是我的MainActivity课程。

    public class MainActivity extends AppCompatActivity implements OnNavigationItemSelectedListener, OnPostSelectedListener{

    FragmentManager mFragmentManager;
    FragmentTransaction mFragmentTransaction;
    TextView usrTag, tagrEmail;
    CircleImageView tagrPic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).addToBackStack("PreviewFragment").commit();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View header = navigationView.getHeaderView(0);
        usrTag = (TextView)header.findViewById(R.id.usrName);
        tagrEmail = (TextView)header.findViewById(R.id.usrEmail);
        tagrPic = (CircleImageView)header.findViewById(R.id.usrImg);

        Log.i("MainActivity: ", "User Photo: " + getProfilePic(this));

        usrTag.setText(getUserName(getBaseContext()));
        tagrEmail.setText(getUserEmail(getBaseContext()));
        GlideUtils.loadProfileIcon(getProfilePic(getBaseContext()), tagrPic);

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();


        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        Fragment fragment = null;
        Class fragmentClass = null;
        int id = item.getItemId();

        if (id == R.id.nav_home) {
            fragmentClass = PreviewFragment.class;
        } else if (id == R.id.nav_custom) {
            startCustomLabelCreator();
        } else if (id == R.id.nav_mylabels) {

        } else if (id == R.id.nav_commLabels) {
            fragmentClass = PostsFragment.class;
        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void startCustomLabelCreator(){
        Intent cLC = new Intent(getBaseContext(), CreateLabel.class);
        startActivity(cLC);
    }

    @Override
    public void onPostComment(String postKey) {

    }

    @Override
    public void onPostLike(String postKey) {

    }

    @Override
    public void onPhotoSelected(String photoUrl) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();
    }
}

我的碎片

    public class PostsFragment extends Fragment implements ConfirmSelectedPhotoListener{

    public static final String TAG = "PostsFragment";
    private static final String KEY_LAYOUT_POSITION = "layoutPosition";
    private int mRecyclerViewPosition = 0;
    private OnPostSelectedListener mListener;


    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter<PostViewHolder> mAdapter;

    public PostsFragment() {
        // Required empty public constructor
    }

    public static PostsFragment newInstance() {
        PostsFragment fragment = new PostsFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_posts, container, false);
        rootView.setTag(TAG);

        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setReverseLayout(true);
        linearLayoutManager.setStackFromEnd(true);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        Log.d(TAG, "Restoring recycler view position (all): " + mRecyclerViewPosition);
        Query allPostsQuery = FirebaseUtil.getPostsRef();
        mAdapter = getFirebaseRecyclerAdapter(allPostsQuery);
        mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                super.onItemRangeInserted(positionStart, itemCount);
                // TODO: Refresh feed view.
            }
        });


        mRecyclerView.setAdapter(mAdapter);
    }

    private FirebaseRecyclerAdapter<Post, PostViewHolder> getFirebaseRecyclerAdapter(Query query) {
        return new FirebaseRecyclerAdapter<Post, PostViewHolder>(
                Post.class, R.layout.post_item, PostViewHolder.class, query) {
            @Override
            public void populateViewHolder(final PostViewHolder postViewHolder,
                                           final Post post, final int position) {
                setupPost(postViewHolder, post, position, null);
            }

            @Override
            public void onViewRecycled(PostViewHolder holder) {
                super.onViewRecycled(holder);
//                FirebaseUtil.getLikesRef().child(holder.mPostKey).removeEventListener(holder.mLikeListener);
            }
        };
    }

    private void setupPost(final PostViewHolder postViewHolder, final Post post, final int position, final String inPostKey) {
        postViewHolder.setPhoto(post.getThumb_url());
        Log.d(TAG, post.getThumb_url());
        postViewHolder.setText(post.getText());
        postViewHolder.setTimestamp(DateUtils.getRelativeTimeSpanString(
                (long) post.getTimestamp()).toString());
        final String postKey;
        if (mAdapter instanceof FirebaseRecyclerAdapter) {
            postKey = ((FirebaseRecyclerAdapter) mAdapter).getRef(position).getKey();
        } else {
            postKey = inPostKey;
        }

        Author author = post.getAuthor();
        postViewHolder.setAuthor(author.getFull_name(), author.getUid());
        postViewHolder.setIcon(author.getProfile_picture(), author.getUid());

        ValueEventListener likeListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                postViewHolder.setNumLikes(dataSnapshot.getChildrenCount());
                if (dataSnapshot.hasChild(FirebaseUtil.getCurrentUserId())) {
                    postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.LIKED, getActivity());
                } else {
                    postViewHolder.setLikeStatus(PostViewHolder.LikeStatus.NOT_LIKED, getActivity());
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
        FirebaseUtil.getLikesRef().child(postKey).addValueEventListener(likeListener);
        postViewHolder.mLikeListener = likeListener;

        postViewHolder.setPostClickListener(new PostViewHolder.PostClickListener() {
            @Override
            public void showComments() {
                Log.d(TAG, "Comment position: " + position);
                mListener.onPostComment(postKey);
            }

            @Override
            public void toggleLike() {
                Log.d(TAG, "Like position: " + position);
                mListener.onPostLike(postKey);
            }

            @Override
            public void savePhotoUrl() {
                //mListener.onPhotoSelected(post.getFull_url());
                showLabelConfirm(post.getFull_url());
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mAdapter != null && mAdapter instanceof FirebaseRecyclerAdapter) {
            ((FirebaseRecyclerAdapter) mAdapter).cleanup();
        }
    }


    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save currently selected layout manager.
        int recyclerViewScrollPosition = getRecyclerViewScrollPosition();
        Log.d(TAG, "Recycler view scroll position: " + recyclerViewScrollPosition);
        savedInstanceState.putSerializable(KEY_LAYOUT_POSITION, recyclerViewScrollPosition);
        super.onSaveInstanceState(savedInstanceState);
    }

    private int getRecyclerViewScrollPosition() {
        int scrollPosition = 0;
        // TODO: Is null check necessary?
        if (mRecyclerView != null && mRecyclerView.getLayoutManager() != null) {
            scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
                    .findFirstCompletelyVisibleItemPosition();
        }
        return scrollPosition;
    }

    @Override
    public void onSelectedPhoto(String selectPhoto) {
        mListener.onPhotoSelected(selectPhoto);
    }

    public interface OnPostSelectedListener {
        void onPostComment(String postKey);
        void onPostLike(String postKey);
        void onPhotoSelected(String photoUrl);
    }

    private void showLabelConfirm(String uriBmp) {
        FragmentManager fm = getFragmentManager();
        PhotoDialogFragment editNameDialogFragment = PhotoDialogFragment.newInstance(uriBmp);
        // SETS the target fragment for use later when sending results
        editNameDialogFragment.setTargetFragment(PostsFragment.this, 300);
        editNameDialogFragment.show(fm, "fragment_edit_name");
    }

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

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

第二片段:

    public class PreviewFragment extends RajBaseFragment {


    @Override
    public ISurfaceRenderer createRenderer() {
        return new PreviewRenderer(getContext());
    }


}

其中包括:

    public abstract class RajBaseFragment extends Fragment implements IDisplay, View.OnClickListener {


    protected FrameLayout mLayout;
    protected ISurface mRajawaliSurface;
    protected ISurfaceRenderer mRenderer;

    public RajBaseFragment(){

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        // Inflate the view
        mLayout = (FrameLayout) inflater.inflate(getLayoutID(), container, false);

        mLayout.findViewById(R.id.relative_layout_loader_container).bringToFront();

        // Find the TextureView
        mRajawaliSurface = (ISurface) mLayout.findViewById(R.id.rajwali_surface);

        // Create the loader


        mRenderer = createRenderer();
        onBeforeApplyRenderer();
        applyRenderer();
        return mLayout;
    }

    protected void onBeforeApplyRenderer() {

    }

    protected void applyRenderer() {
        mRajawaliSurface.setSurfaceRenderer(mRenderer);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        if (mLayout != null)
            mLayout.removeView((View) mRajawaliSurface);
    }

    @Override
    public int getLayoutID() {
        return R.layout.rajawali_textureview_fragment;
    }




}

到目前为止,我已经尝试了下面的所有建议,当按下后退按钮而不是app退出/关闭时,MainActivity onCreate方法中设置的主要片段仍然会被刷新/重新加载。

7 个答案:

答案 0 :(得分:3)

onNavigationItemSelected方法中,即使在fragment为null且具有未定义效果的情况下,也会使用fragment替换当前片段。你不应该这样做。

一个解决方法是替换此代码块:

try {
  fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
  e.printStackTrace();
}

这一个:

if (fragmentClass != null) {
  fragment = fragmentClass.newInstance();
  FragmentManager fragmentManager = getSupportFragmentManager();
  fragmentManager.beginTransaction().replace(R.id.cLMain, fragment).addToBackStack().commit();
}

(然后在此点之下省略片段事务)。

此外,在finish方法中调用了onDestroy,这可能不会导致问题,但应该删除,因为它没有任何意义。

答案 1 :(得分:2)

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
          switch (item.getItemId()) {
          case android.R.id.home:
                 onBackPressed();
                 break;
            }
          return true;
  }

用我的替换你的onOptionsItemSelected()。

答案 2 :(得分:2)

不要将第一个片段包含在Backstack中。

尝试在没有addToBackStack的情况下更改片段交易行代码 如下:

mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
  

在使用addToBackStack添加片段时,这允许返回   添加片段的导航。因为背板中的片段,   空(黑色)活动布局将会显示。

更改onBackPressed()如下所示,如果在FragmentManager中找不到任何片段,则自动关闭应用程序:

    @Override
public void onBackPressed() {
    if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
        this.finish();
    } else {
        getSupportFragmentManager().popBackStack();
    }
}

此外,您可以在以下链接中看到一些类似的问答,这有助于您更好地解决问题:

Fragment pressing back button

In Fragment on back button pressed Activity is blank

Transaction of fragments in android results in blank screen

它解决了我的黑屏问题。希望它可以帮助你。

答案 3 :(得分:2)

尝试使用此代码,希望这可以帮助您,采取您需要的必要内容。此外,尝试在Android studio中运行此项目,它可以工作。

https://github.com/asifali22/Navigation_Health/blob/master/app/src/main/java/com/thenewboston/mynavigation/MainActivity.java

答案 4 :(得分:1)

当用户按下后退按钮时,它将检查片段管理器的后台堆栈,如果后台堆栈实体计数大于0(这意味着后台堆栈中有一个片段),它将popBackStack,否则它将完成活动。

如果您将初始片段添加到Backstack,当用户按下后退按钮时,他们将看到一个空白屏幕。

此外,当您初始化活动时,如果需要放置片段,最佳做法是检查保存的实例状态是否为空。在这里,我修改了部分代码。

if(savedInstanceState == null){
        mFragmentManager = getSupportFragmentManager();
        mFragmentTransaction = mFragmentManager.beginTransaction();
        mFragmentTransaction.add(R.id.cLMain, new PreviewFragment()).commit();
}

我希望这对你有帮助。如果您仍有问题,请告诉我。

祝你好运。

答案 5 :(得分:1)

ISurface创建子类并覆盖此{/ p>的onKeyDown方法

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    Log.e("Custom View", "onKeyDown");
    //return super.onKeyDown(keyCode, event);
    return false;
}

答案 6 :(得分:0)

可能与生命周期有关... 尝试使用GLSurfaceView。我相信你想要的更容易,对于OpenGL渲染是特别的,并且有很多关于它的信息。 Examples中的lifecycleothers。如果有帮助,请告诉我。如果没有,请提供更多信息。