Vier Sprungmethoden von Fragment

Dieser Artikel zeichnet hauptsächlich vier Sprungmethoden zu Fragmenten auf:  

1. Von einem Fragment derselben Aktivität zu einem anderen Fragment springen  
2. Von einem Fragment einer Aktivität zu einer anderen Aktivität springen  
3. Von einer Aktivität zu einem Fragment einer anderen Aktivität springen
4. Von einem Fragment einer Aktivität springen Gehe zu dem Fragment einer anderen Aktivität

Das Schreiben dieses Artikels ist nur eine einfache Aufzeichnung. Wenn ich die Artikel anderer Leute las, während ich hier lernte, fühlte ich mich immer im Nebel. Später hatte ich auch das Gefühl, dass es fast genug war, also schrieb ich diesen Blog, um meinen eigenen Lernprozess aufzuzeichnen . . .

Erstellen Sie zuerst ein neues Projekt und dann zwei neue Aktivitäten MainActivity und OtherActivity.
Schreiben Sie ein Unterlayout in die Layoutdatei von MainActivity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>


</LinearLayout>

Erstellen Sie ein neues my_fragment.xml-Layout und eine neue MyFragment-Klasse

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="MyFragment"
        android:textSize="40sp"
        android:gravity="center_horizontal"/>

    <Button
        android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="To YourFragment"/>

    <Button
        android:id="@+id/my_other"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="To OtherActivity"/>

</LinearLayout>

Die MyFragment-Klasse wird vorübergehend weggelassen, und alle Codes werden später veröffentlicht.
Fügen Sie zuerst ein Fragment in MainActivity für die anfängliche Anzeige hinzu (push add)

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container,new MyFragment())
                .addToBackStack(null)
                .commit();

    }
}

Springe von einem Fragment derselben Aktivität zu einem anderen Fragment

Dieser Sprung ähnelt der anfänglichen Anzeige von Fragment oben.
Erstellen Sie ein neues your_fragment.xml-Layout und eine neue YourFragment-Klasse.

public class YourFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView;
        contentView = inflater.inflate(R.layout.your_fragment, container, false);
        return contentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button myReturn = (Button) getActivity().findViewById(R.id.my_return);
        myReturn.setOnClickListener(new View.OnClickListener() {
            //返回到上一个Fragment(同一个Activity中)
            @Override
            public void onClick(View v) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });
    }
}

your_fragment.xml wird vorübergehend weggelassen, und der gesamte Code wird am Ende veröffentlicht.

Der Sprungteilcode lautet wie folgt, springen Sie, indem Sie auf die Schaltfläche klicken:

myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /** 一、从同一个Activity的一个Fragment跳到另外一个Fragment*/
                //压栈式跳转
                getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment_container, new YourFragment(), null)
                        .addToBackStack(null)
                        .commit();

            }
        });

Von einem Fragment einer Aktivität zu einer anderen Aktivität springen

Dieser Sprung ist dem Sprung zwischen Aktivitäten sehr ähnlich, ändern Sie ihn einfach in getActivity(), wenn Sie auf den Kontext verweisen.

Schlüsselcode springen:

myOther.setOnClickListener(new View.OnClickListener() {
            /**
             二、从一个Activity的Fragment跳转到另外一个Activity(等同于Activity之间的跳转(上下文是getActivity))
             */
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),OtherActivity.class);
                startActivity(intent);
            }
        });

Wechseln Sie von einer Aktivität zum Fragment einer anderen Aktivität

Wir wollen von OtherActivity zu YourFragment von MainActivity springen:
Zuerst übergeben wir MainActivity im Sprungereignis in OtherActivity einen Parameter mit dem Namen id:

Intent intent = new Intent(OtherActivity.this, MainActivity.class);
intent.putExtra("id",1);
startActivity(intent);

 Dann erhalten wir den id-Wert in MainActivity, beurteilen den Wert und führen die Sprungoperation aus, wenn er korrekt ist:

int id = getIntent().getIntExtra("id", 0);
if (id == 1) {      
     getSupportFragmentManager()
       .beginTransaction()
       .replace(R.id.fragment_container,new YourFragment())
       .addToBackStack(null)
       .commit(); 
}

Wechseln Sie vom Fragment einer Aktivität zum Fragment einer anderen Aktivität

Erstellen Sie ein neues other_fragment.xml-Layout als Fragment von OtherActivity.

 Diese Sprungart ist der dritten Sprungart sehr ähnlich, wir müssen nur das Obige ändern

Intent intent = new Intent(OtherActivity.this, MainActivity.class);

Schreiben Sie es in das entsprechende Fragment, ändern Sie OtherActivity.this in getActivity(), und der andere kann den Sprung ohne Änderung abschließen.

Der Schlüsselcode lautet wie folgt:

public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button ToButton = (Button) getActivity().findViewById(R.id.to_button);
        ToButton.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putExtra("id",1);
                startActivity(intent);
            }
        });
    }

alle Codedateien

Hängen Sie alle Codedateien am Ende an.  
Hauptaktivität:

package com.example.fragment_activity_skiptest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container,new MyFragment())
                .addToBackStack(null)
                .commit();
        int id = getIntent().getIntExtra("id", 0);
        if (id == 1) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container,new YourFragment())
                    .addToBackStack(null)
                    .commit();
        }

    }
}

MeinFragment:

package com.example.fragment_activity_skiptest;

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


public class MyFragment extends Fragment {

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView;
            contentView = inflater.inflate(R.layout.my_fragment, container, false);

        return contentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button myButton = (Button) getActivity().findViewById(R.id.my_button);

        Button myOther = (Button) getActivity().findViewById(R.id.my_other);
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /** 一、从同一个Activity的一个Fragment跳到另外一个Fragment*/
                //压栈式跳转
                getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment_container, new YourFragment(), null)
                        .addToBackStack(null)
                        .commit();

            }
        });
        myOther.setOnClickListener(new View.OnClickListener() {
            /**
             二、从一个Activity的Fragment跳转到另外一个Activity(等同于Activity之间的跳转(上下文是getActivity))
             */
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),OtherActivity.class);
                startActivity(intent);
            }
        });
    }
}

Sonstige Aktivität:

package com.example.fragment_activity_skiptest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class OtherActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);
        Button button = (Button)findViewById(R.id.to_MainActivity_YourFragment);
        Button button_back = (Button)findViewById(R.id.back);
        Button button_fm = (Button)findViewById(R.id.to_OtherFragment);
        button.setOnClickListener(new View.OnClickListener() {
            /*从一个Activity跳转到另外一个Activity的Fragment上
            例如我们要从OtherActivity跳转到MainActivity的YourFragment上去:
            首先,我们在OtherActivity中的跳转事件中给MainActivity传递一个名为id的参数:
            然后,我们在MainActivity里接收id值,对值进行判断,如果正确进行跳转操作:
            */
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(OtherActivity.this, MainActivity.class);
                intent.putExtra("id",1);
                startActivity(intent);

            }
        });
        button_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        button_fm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.frame_container, new OtherFragment(), null)
                        .addToBackStack(null)
                        .commit();
            }
        });
    }
}

SonstigesFragment:

package com.example.fragment_activity_skiptest;

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


public class OtherFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView;
        contentView = inflater.inflate(R.layout.other_fragment, container, false);
        return contentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button ToButton = (Button) getActivity().findViewById(R.id.to_button);
        ToButton.setOnClickListener(new View.OnClickListener() {
            /*4、从一个Activity的Fragment跳转到另外一个Activity的Fragment上
            这种跳转与第三种跳转极为类似,我们只需要将
            Intent intent = new Intent(OtherActivity.this, MainActivity.class);
            书写在对应的Fragment中,将OtherActivity.this更改为getActivity(),其他不用改变,几个完成跳转.
            */
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putExtra("id",1);
                startActivity(intent);
            }
        });
    }
}

DeinFragment:

package com.example.fragment_activity_skiptest;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


public class YourFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView;
        contentView = inflater.inflate(R.layout.your_fragment, container, false);
        return contentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button myReturn = (Button) getActivity().findViewById(R.id.my_return);
        myReturn.setOnClickListener(new View.OnClickListener() {
            //返回到上一个Fragment(同一个Activity中)
            @Override
            public void onClick(View v) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>


</LinearLayout>

activity_other.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:id="@+id/activity_other"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#d0ff05"
    >

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="OtherActivity"
                android:textSize="50sp"
                android:gravity="center_horizontal"/>

            <Button
                android:id="@+id/to_MainActivity_YourFragment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="To MainActivity YourFragment"
                android:textAllCaps="false"/>

            <Button
                android:id="@+id/to_OtherFragment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="To OtherFragment"
                android:textAllCaps="false"/>

            <Button
                android:id="@+id/back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="back"/>

        </LinearLayout>
    </FrameLayout>



</LinearLayout>

mein_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="MyFragment"
        android:textSize="40sp"
        android:gravity="center_horizontal"/>

    <Button
        android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="To YourFragment"/>

    <Button
        android:id="@+id/my_other"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="To OtherActivity"/>

</LinearLayout>

anderes_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff">



    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="OtherFragment"
        android:textSize="40sp"
        android:gravity="center_horizontal"/>

    <Button
        android:id="@+id/to_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="To MainActivity YourFragment"/>

</LinearLayout>

your_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0fa345">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textSize="40sp"
        android:text="YourFragment"/>

    <Button
        android:id="@+id/my_return"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RETURN"
        />

</LinearLayout>

Referenz: Vier Sprünge von Android Fragment

Supongo que te gusta

Origin blog.csdn.net/m0_61465701/article/details/126145181
Recomendado
Clasificación