如何从 Main Activity 到 Fragment,并从同一个 Fragment 返回到 Main Activity?

Posted

技术标签:

【中文标题】如何从 Main Activity 到 Fragment,并从同一个 Fragment 返回到 Main Activity?【英文标题】:How to go from Main Activity to fragment, and from the same fragment back to Main Activity? 【发布时间】:2021-03-27 11:40:35 【问题描述】:

您好,我正在尝试制作一个应用程序,该应用程序将从主要活动(登录屏幕)转到带有列表视图(显示登录名)的片段,然后使列表视图选项之一返回到主活动(重新输入姓名、电子邮件和地址)。我一直在努力让它工作,但我不知道出了什么问题,我想因为我是编程新手。

这些是 XML 和类:

MainActivity.java

package com.example.project;

import android.app.Fragment;
import android.os.Bundle;
import android.provider.Telephony;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import org.w3c.dom.Text;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity 

    public Button login;
    public EditText name;
    public EditText email;
    public EditText address;

    String Name;
    String Email;
    String Address;

    @Override
    protected void onCreate(Bundle savedInstanceState) 

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try 
            Thread.sleep(5000);
         catch (InterruptedException e) 
            e.printStackTrace();
        
        Button login = (Button) findViewById(R.id.button);
        EditText name = (EditText) findViewById(R.id.name);
        EditText email = (EditText) findViewById(R.id.email);
        EditText address = (EditText) findViewById(R.id.address);

        String Name = name.getText().toString();
        String Email = email.getText().toString();
        String Address = address.getText().toString();


        Fragment fragment = new ListViewFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.mainFrag, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
    
    private void showFragment()
        Bundle info = new Bundle();
        info.putString("name", Name);
        info.putString("email", Email);
        info.putString("address", Address);

        Fragment fragment = new Fragment();
        fragment.setArguments(info);
        android.app.FragmentTransaction transaction = getFragmentManager().beginTransaction();
       // transaction.setCustomAnimations(R.animator.fade_in, R.animator.fade_out);
        transaction.addToBackStack(null);
        transaction.replace(R.id.account, fragment);
        transaction.commit();
    

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/mainFrag"
    android:layout_
    android:layout_
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_
        android:layout_
        android:layout_marginTop="16dp"
        android:text="Smart-Home Sensors System"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <fragment
        android:id="@+id/fragment"
        android:name="com.example.project.ListViewFragment"
        android:layout_
        android:layout_
        android:layout_weight="1"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/button"
        android:layout_
        android:layout_
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.931" />

    <EditText
        android:id="@+id/name"
        android:layout_
        android:layout_
        android:layout_marginTop="100dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <EditText
        android:id="@+id/email"
        android:layout_
        android:layout_
        android:layout_marginTop="40dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Email"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/name" />

    <EditText
        android:id="@+id/address"
        android:layout_
        android:layout_
        android:layout_marginTop="40dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Address"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/email" />
</androidx.constraintlayout.widget.ConstraintLayout>

ListViewFragment.java

package com.example.project;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import java.lang.reflect.Array;
import java.util.ArrayList;

import static android.provider.AlarmClock.EXTRA_MESSAGE;

public class ListViewFragment extends Fragment 
    String myValue = this.getArguments().getString("message");
    public static ListViewFragment newInstance(String name, String email, String password) 
        ListViewFragment f = new ListViewFragment();



        /*
        Bundle args = new Bundle();
        args.putString("Name", name);
        args.putString("Email", email);
        args.putString("Password", password);
        f.setArguments(args);*/
        return f;
    
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        View v = inflater.inflate(R.layout.mainmenu, container, false);
        final ListView list = getView().findViewById(R.id.list);
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("View sensor 1");
        arrayList.add("View sensor 2");
        arrayList.add("View login details");
        arrayList.add("Logout");
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getView().getContext(), android.R.layout.simple_list_item_1, arrayList);
        list.setAdapter(arrayAdapter);
        TextView textView = new TextView(getView().getContext());
        textView.setText("Please select an option:");
        list.addHeaderView(textView);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() 

            private void showFragment() 


                Fragment fragment = new Fragment();
                FragmentTransaction transaction =
                        getFragmentManager().beginTransaction();
                transaction.addToBackStack(null);
                // transaction.setCustomAnimations(R.animator.fade_in, R.animator.fade_out);
                transaction.replace(R.id.account, fragment, "fragment");
                transaction.commit();
            

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
                String clickedItem = (String) list.getItemAtPosition(position);
                Toast.makeText(getView().getContext(), clickedItem, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getView().getContext(), LoginFragment.class);
                intent.putExtra(EXTRA_MESSAGE, clickedItem);
                startActivity(intent);
            
        );
        return v;
    
    private void showSigninFragment(Fragment showinfo)

        Fragment fragment = showinfo;
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        //transaction.setCustomAnimations(R.animator.fade_in, R.animator.fade_out);
        transaction.addToBackStack(null);

        transaction.replace(R.id.account, fragment);
        transaction.commit();


    

mainmenu.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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_
    android:layout_>

    <TextView
        android:id="@+id/nameDisp"
        android:layout_
        android:layout_
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_weight="1"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/list"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.552" />

    <TextView
        android:id="@+id/emailDisp"
        android:layout_
        android:layout_
        android:layout_weight="1"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/list"
        app:layout_constraintEnd_toStartOf="@+id/nameDisp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/addressDisp"
        android:layout_
        android:layout_
        android:layout_marginEnd="48dp"
        android:layout_marginRight="48dp"
        android:layout_weight="1"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/list"
        app:layout_constraintEnd_toStartOf="@+id/emailDisp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.552" />

    <ListView
        android:id="@+id/list"
        android:layout_
        android:layout_
        android:layout_marginTop="72dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/selectOption"
        android:layout_
        android:layout_
        android:layout_weight="1"
        android:hint="@string/testStringForToast"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/list" />

</androidx.constraintlayout.widget.ConstraintLayout>

【问题讨论】:

更新了你的标签。 android-studio 标签只能用于有关 Android Studio 产品的问题/错误。您的问题与 Android Studio 无关,因此我删除了标记并添加了通用的 android 标记。 【参考方案1】:

代替

import android.app.Fragment;

你应该导入

import androidx.fragment.app.Fragment;

Main Activity.java

中的 showFragment()
// create new ListViewFragment ("ListViewFragment.java" ...)
ListViewFragment lvFragment = new ListViewFragment();
// create new FragmentManager
FragmentManager fm = getSupportFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction transaction = fm.beginTransaction();
// your animation...
transaction.setCustomAnimations(R.animator.fade_in, R.animator.fade_out);
// replace your activity_main layout with your Fragment layout
transaction.add(R.id.mainFrag, lvFragment);
transaction.addToBackStack("");
transaction.commit(); // save changes

您可以从activity_main.xml 中删除&lt;fragment...

【讨论】:

以上是关于如何从 Main Activity 到 Fragment,并从同一个 Fragment 返回到 Main Activity?的主要内容,如果未能解决你的问题,请参考以下文章

Android 如何从 Main Activity 中的另一个类调用 Activity 数据类型?

如何从Fragment到DataBinding访问Activity视图?

如何将数据从Activity返回到Fragment

Fragment

android开发 如何从一个activity中的两个按钮分别跳转到另外两个activity?

android 兼容性包 - 片段...未附加到 Activity