片段到活动 Backstack 返回空白视图

2024-02-05

我创建了一个家庭活动,其中包括Tablayout and Navigation Draweronclick 与片段。我已经包括了fragmentTransaction.addToBackStack(null).commit();使用片段事务代码返回到上一个 Activity。

我想要的要求是来自Activity with tablayout-->NavigationDrawer-->Fragment1--> On BackButtonPress-->MainActivity with tablayout.

但是,现在我可以移动到 Fragment1,当返​​回到 MainActivity 时,视图变为filled with white(if i use mainLayout.removeAllViews();如果不会使用mainLayout.removeAllViews(); ,then the fragment is overlapping with the MainActivity)

1.我的主要活动

2.片段

3.当我返回主要活动时

现在我在 MainActivity 中看不到 tablayout。

谁能帮帮我吗。

mainactivity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".HomeActivity"
    android:id="@+id/mainlayout"
    tools:showIn="@layout/app_bar_home">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rel">
        <RelativeLayout
            android:id="@+id/main_layout1"
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity">

            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary"
                android:elevation="6dp"
                android:minHeight="?attr/actionBarSize"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

            <android.support.v4.view.ViewPager
                android:id="@+id/pager1"
                android:layout_width="match_parent"
                android:layout_height="fill_parent"
                android:layout_below="@id/tab_layout1"/>

        </RelativeLayout>
    </RelativeLayout>



</RelativeLayout>

MainActivity.java

    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.design.widget.NavigationView;
    import android.support.design.widget.TabLayout;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v4.view.GravityCompat;
    import android.support.v4.view.ViewPager;
    import android.support.v4.widget.DrawerLayout;
    import android.support.v7.app.ActionBarDrawerToggle;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.RelativeLayout;

    import java.io.File;
    import java.util.ArrayList;


    public class HomeActivity extends AppCompatActivity
            implements NavigationView.OnNavigationItemSelectedListener {


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);
            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();

            NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
            navigationView.setNavigationItemSelectedListener(this);

            TabLayout tabLayout1 = (TabLayout) findViewById(R.id.tab_layout1);
            tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_home));
            tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_map));
            tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_login));

            tabLayout1.setTabGravity(TabLayout.GRAVITY_FILL);

            final ViewPager viewPager1 = (ViewPager) findViewById(R.id.pager1);
            final PagerAdapter1 adapter = new PagerAdapter1
                    (getSupportFragmentManager(), tabLayout1.getTabCount());
            viewPager1.setAdapter(adapter);
            viewPager1.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout1));
            tabLayout1.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    viewPager1.setCurrentItem(tab.getPosition());
                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {

                }

                @Override
                public void onTabReselected(TabLayout.Tab tab) {

                }
            });
        }

        @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.home, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            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) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            // Handle navigation view item clicks here.
            int id = item.getItemId();
            RelativeLayout mainLayout=(RelativeLayout)findViewById(R.id.main_content);
            if (id == R.id.nav_login) {
                LoginFragment fragment = new LoginFragment();
    //            mainLayout.removeAllViews();
                fragmentTransaction.replace(R.id.mainlayout, fragment);
                fragmentTransaction.addToBackStack(null).commit();
            } 

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

片段.java

  import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class ContactFragment extends Fragment implements OnMapReadyCallback {

    private GoogleMap mMap;
    Button call;

    public ContactFragment() {
        // Required empty public constructor
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_contact,container,false);

        call = (Button) v.findViewById(R.id.button5);
        call.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NewApi")
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_DIAL);
                i.setData(Uri.parse("tel:7034409615"));
                startActivity(i);
            }
        });
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        return v;


    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(9.2700, 76.7800);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Pathanamthitta"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

正如我在评论中建议的那样,为了找出片段显示的问题,您可以尝试查看哪种片段被添加到后台堆栈中,如下所示
Log.d("FragmentList",getSupportFragmentManager().getFragments().toString(); 你可以把它放进去onBackPressed() ,onNavigationItemSelected()

根据您的反馈,这对您有帮助,您已经解决了问题。

另外还有一些布局设计问题: 您当前的方法是将片段添加到相对布局中。我相信这会导致一些观点问题。推荐的方法是将片段添加到 FrameLayout 中,如中所述docs http://developer.android.com/training/basics/fragments/fragment-ui.html此外,您可能希望将用于片段的所有内容移到视图之外 我已经按照文档中推荐的指南重写了您的布局。 P.S 我还没有测试它的显示方式。您可能需要调整一些布局参数。

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    xmlns:tools="http://schemas.android.com/tools"
                  android:orientation="vertical"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">
        <!--
        Layout for fragments
        -->
        <FrameLayout
                   android:id="@+id/mainlayout"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:paddingBottom="@dimen/activity_vertical_margin"
                        app:layout_behavior="@string/appbar_scrolling_view_behavior"
                        tools:showIn="@layout/app_bar_home">

        </RelativeLayout>
        <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/rel">
            <RelativeLayout
                    android:id="@+id/main_layout1"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                <android.support.design.widget.TabLayout
                        android:id="@+id/tab_layout1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="?attr/colorPrimary"
                        android:elevation="6dp"
                        android:minHeight="?attr/actionBarSize"
                        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" android:orientation="horizontal"/>

                <android.support.v4.view.ViewPager
                        android:id="@+id/pager1"
                        android:layout_width="match_parent"
                        android:layout_height="fill_parent"
                        android:layout_below="@id/tab_layout1"/>

            </RelativeLayout>
        </RelativeLayout>
    </LinearLayout>

您还在布局中定义了多个活动,例如tools:context=".MainActivity" and tools:context=".HomeActivity"我想这只是未经编辑的复制粘贴,但也可能会导致一些问题。

希望你觉得它有用 :)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

片段到活动 Backstack 返回空白视图 的相关文章

随机推荐