android - fragment 到 Activity Backstack 返回空白 View

标签 android android-layout android-fragments android-activity

我创建了一个 Home Activity ,其中包括带有 fragment 的 Tablayout 和 Navigation Drawer onclick。我已将 fragmentTransaction.addToBackStack(null).commit(); 包含在 fragment 事务代码中以返回到之前的 Activity。

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

但是,现在我可以移动到 Fragment1,当返​​回到 MainActivity 时, View 变为 填充白色(如果我使用 mainLayout.removeAllViews();如果不使用 mainLayout.removeAllViews(); ,然后 fragment 与MainActivity重叠)

1.我的主要 Activity

My Mainactivty

2. fragment

when goes to a fragment

3.当我回到mainactivty时

when i returned to mainactivity

现在我在 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>

主 Activity .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;
        }
    }

fragment .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));
    }
}

最佳答案

正如我在评论中所建议的,为了弄清楚 fragment 显示的问题,您可以尝试查看哪些 fragment 被添加到后退堆栈中,如下所示
Log.d("FragmentList",getSupportFragmentManager().getFragments().toString(); 你可以把它放在 onBackPressed() ,onNavigationItemSelected()

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

还有一些布局设计问题: 您当前的方法是将 fragment 添加到相对布局中。我相信这会导致一些 View 问题。推荐的方法是将 fragment 添加到 FrameLayout 中,如 docs 中所述。 此外,您可能希望将用于 fragment 的所有内容移到 View 之外 我已经按照文档中推荐的指南重写了您的布局。 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>

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

希望你觉得它有用:)

关于android - fragment 到 Activity Backstack 返回空白 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33493612/

相关文章:

Android:资源String自动生成

java - 设备旋转时丢失 'MediaPlayer'(及其他变量)

android - 尝试在 fragment 中使用 Mediaplayer

java - 在选项卡式 Activity 中启用和禁用搜索操作

android - 谷歌地图引擎 Lite API 脚本失败

android - 在阴天,GPS 设备在 Android 中返回错误输出

android - fragment - 获取 View 在调用 onCreateView 时已经有父错误

android - ListView setOnItemClickListener 不起作用

android - AppCompat - 设置操作栏样式时出错

java - 想要将 Activity 更改为 Fragment