如何以编程方式切换到另一个片段?

时间:2016-05-26 06:26:02

标签: android android-fragments android-activity fragment

我'有两个片段(layout_first.xml和layout_second.xml) 我想这样做:单击第一个片段中的一个按钮(显示第二个)以显示第二个片段,并在第一个片段中获取EditText值,以在第二个Fragment programmaticaly中设置EditText值。

这是我的代码:

activity_main.xml中

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="@dimen/custom_tab_layout_height"
            app:tabMode="fixed"
            app:tabGravity="fill"/>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />
</android.support.design.widget.CoordinatorLayout>

layout_first.xml

<LinearLayout 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"
    android:orientation="horizontal"
    android:focusable="true"
    android:background="#bc8383">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Second"
        android:id="@+id/btnShowSecond"
        android:layout_weight="0.18" />

    <EditText
        android:id="@+id/et1"
        android:text="et1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#000000"
        android:elegantTextHeight="false"
        android:maxLength="20"
        android:singleLine="true"
        android:textAlignment="center"
        android:textColor="#85b27e"
        android:textSize="40dp"
        android:paddingLeft="3dp"
        android:paddingRight="3dp"
        android:layout_marginTop="10dp"
        android:layout_weight="1" />
</LinearLayout>

layout_second.xml

<LinearLayout 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"
    android:orientation="vertical"
    android:focusable="true"
    android:background="#bc8383">

    <EditText
        android:id="@+id/et2"
        android:text="et2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#000000"
        android:elegantTextHeight="false"
        android:maxLength="20"
        android:singleLine="true"
        android:textAlignment="center"
        android:textColor="#85b27e"
        android:textSize="40dp"
        android:paddingLeft="3dp"
        android:paddingRight="3dp"
        android:layout_marginTop="10dp"
        android:layout_gravity="center_horizontal" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="btn2"
        android:id="@+id/btn2"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

custom_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tab"
    android:textColor="@color/colorAccent"
    android:textSize="14dp"
    android:gravity="center"
    android:fontFamily="@string/font_fontFamily_medium"/>

MainActivity.java

package xmaxsoft.delfragment;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();
    }

    private void setupTabIcons() {
        TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabOne.setText("One");
        tabLayout.getTabAt(0).setCustomView(tabOne);

        TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabTwo.setText("Two");
        tabLayout.getTabAt(1).setCustomView(tabTwo);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new First(), "One");
        adapter.addFrag(new Second(), "Two");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

First.java

package xmaxsoft.delfragment;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class First extends Fragment {
    public First() {
    }

    Button btnShowSecond;
    EditText et1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.layout_first, container, false);
        btnShowSecond = (Button) view.findViewById(R.id.btnShowSecond);
        et1 = (EditText) view.findViewById(R.id.et1);
        btnShowSecond.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            //what kind of code must be here ???
            //what kind of code must be here ???
            //what kind of code must be here ???
            }
        });
        return view;
    }
}

Second.java

package xmaxsoft.delfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class Second extends Fragment {
    public Second() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.layout_second, container, false);
        //
        return view;
    }
}

4 个答案:

答案 0 :(得分:0)

使用代码: -

 Fragment fragment = new XXXFragment();
       if (fragment != null) {

 FragmentManager fragmentManager   =getActivity().getSupportFragmentManager();
                                fragmentManager.beginTransaction().replace(R.id.frame_container, fragment, "TAG").commit();

}

答案 1 :(得分:0)

由于这两个片段使用相同的活动,

从First片段设置值:

            public void onClick(View v) {
            //what kind of code must be here ???
            //what kind of code must be here ???
            //what kind of code must be here ???
   getActivity().getIntent().putExtra("key", "value");
            }

从第二个片段中获取值:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.activity_second, container, false);
        //
 EditText et2 = (EditText) view.findViewById(R.id.et2);
String valueofet1 = getActivity().getIntent().getExtras().getString("key");
et2.setText(valueofet1 );
        return view;
    }

答案 2 :(得分:0)

最好从活动中替换片段。

在btnShowSecond上的第一个片段中,点击内部点击监听器检查活动是否为空,如果它是主要活动的实例,并且调用mainActivity内部的方法将切换片段。

if(getActivity()!=null && getActivity instanceof MainActivity){
       ((MainActivity)getActivity()).showSecondFragment();
 }

您的MainActivity中的showSecondFragment()方法如下所示。

public void showSecondFragment(){
     getSupportFragmentManager().beginTransaction().replace(R.id.<the layout where you want to show second fragment>,new Second()).commit();

如果您有任何疑问,请告诉我。希望这会有所帮助。

更好的方法是使用接口来调用片段中活动的方法。

请查看下面的链接,了解片段通信的活动,反之亦然。

https://laaptu.wordpress.com/tag/android-communication-between-fragment-and-activity/

答案 3 :(得分:0)

试试这个:

FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
btnShowSecond.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mFragmentManager = getFragmentManager();
                mFragmentTransaction = mFragmentManager.beginTransaction();
                FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.containerView, new second()).addToBackStack("second").commit();
            }
        });

在XML上添加FrameLayout&amp;我提到id- containerView 希望它可以帮助