【问题标题】:fragment to activity Backstack returns blank view片段到活动 Backstack 返回空白视图
【发布时间】:2015-11-03 07:29:49
【问题描述】:

我创建了一个 Home 活动,其中包括带有片段的 Tablayout and Navigation Drawer onclick。我已将fragmentTransaction.addToBackStack(null).commit(); 包含在片段事务代码中以返回上一个活动。

我想要的要求来自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.当我回到mainactivty时

现在我在 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));
    }
}

【问题讨论】:

  • onNavigationItemSelected 中使用fragmentTransaction.commit(); 而不是fragmentTransaction.addToBackStack(null).commit(); 会发生什么??
  • 向我们展示 backstack 中有哪些片段。你可以使用这个方法查看它们Log.d("FragmentList",getSupportFragmentManager().getFragments().toString());你可以放在里面onBackPressed(),onNavigationItemSelected()
  • 尝试使用将片段添加到 Framewlayout 中。您当前的方法是将片段添加到相对布局中。我相信这会导致视图出现一些问题。推荐的方法是按照文档developer.android.com/training/basics/fragments/… 中的描述将片段添加到 FrameLayout 中。此外,您可能希望将所有用于片段的视图移出 PS 请在回复时将我称为@ProblemSlover,否则我将不会收到有关您的回复的通知跨度>
  • 我已经重写了你的布局。请查看pastebin.com/Jbm44RG8 您在布局中定义了多个活动,例如tools:context=".MainActivity"tools:context=".HomeActivity" 我想这只是未经编辑的复制粘贴,但也可能导致一些问题..
  • 你能不能试着替换 fragmentTransaction.replace(R.id.mainlayout, fragment);这个语句带有 fragmentTransaction.add(R.id.mainlayout, fragment);。谢谢。

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


【解决方案1】:

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

根据您的反馈,这对您很有帮助,并且您发现了问题。

还有一些布局设计问题: 您当前的方法是将片段添加到相对布局中。我相信这会导致视图出现一些问题。推荐的方法是将片段添加到 FrameLayout 中,如docs 中所述 此外,您可能希望将所有用于片段的视图移出 我已经按照文档中推荐的指南重写了您的布局。 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"tools:context=".HomeActivity" 我猜这只是未经编辑的复制粘贴,但也可能导致一些问题。

希望你觉得它有用:)

【讨论】:

    【解决方案2】:

    在您的MainActivity.java 中添加:

    protected OnBackPressedListener onBackPressedListener;
    
    public interface OnBackPressedListener {
        void doBack();
    }
    
    public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
        this.onBackPressedListener = onBackPressedListener;
    }
    
    @Override
    public void onBackPressed() {
        if (onBackPressedListener != null)
            onBackPressedListener.doBack();
        else
            super.onBackPressed();
    }
    

    Fragment.java 实现的类是这样的:

    implements MainActivity.OnBackPressedListener
    

    并实现方法:

    @Override
    public void doBack() {
        Intent yourMainActivity = new Intent(getActivity(), MainActivity.class);
        startActivity(yourMainActivity);
    }
    

    【讨论】:

      【解决方案3】:

      鲁宾·内利昆纳图。我遇到过同样的问题。替换FrameLayout 中的NavigationView 片段,而不是RelativeLayout。所以你总是会加载TabLayoutViewPager。 把它放在mainactivity_layout.xmlapp_bar_home.xml 中(我没有看到你的完整代码,所以你试试这些组合)。

      mainactivity_layout.xml

      <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>
      
          // Replace NavigationView fragments in this FrameLayout
          <FrameLayout
              android:id="@+id/flForReplace"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              tools:context=".FrameLayout" />
      
      </RelativeLayout>
      

      你的代码应该是

      fragmentTransaction.replace(R.id.flForReplace, fragment);
      

      按照 ρяσѕρєя K 的建议,也将 fragmentTransaction.addToBackStack(null).commit(); 替换为 fragmentTransaction.commit();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多