Android Studio —— fragment

效果

源码

优快云源码下载

代码

     MainActivity.java

package com.example.application;

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

import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    String name[] = new String[]{"人工智能","大数据","区块链","物联网","云计算","VR"};
    String cont[] = new String[]{"人工智能人工智能人工智能人工智能人工智能人工智能人工智能人工智能人工智能人工智能.",
                                 "大数据大数据大数据大数据大数据大数据大数据大数据大数据大数据.",
                                 "区块链区块链区块链区块链区块链区块链区块链区块链区块链区块链.",
                                 "物联网物联网物联网物联网物联网物联网物联网物联网物联网物联网.",
                                 "云计算云计算云计算云计算云计算云计算云计算云计算云计算云计算.",
                                 "VRVRVRVRVRVRVRVRVRVR"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getSupportFragmentManager();
        MyFragment myFragment = (MyFragment) fragmentManager.findFragmentById(R.id.myfragment);
        TextView TV = myFragment.getView().findViewById(R.id.TV);
        TV.setText(cont[0]);

        ArrayAdapter<String> nameAdapter = new ArrayAdapter<String>(MainActivity.this,R.layout.item,name);
        ListView listview = findViewById(R.id.listview);
        listview.setAdapter(nameAdapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TV.setText(cont[i]);
            }
        });
    }
}


     activity_main.xml

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="TextView" />

        <ListView
            android:id="@+id/listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="20dp"
            android:layout_weight="1" />
    </LinearLayout>

    <fragment
        android:id="@+id/myfragment"
        android:name="com.example.application.MyFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3" />

</LinearLayout>


     MyFragment.java

package com.example.application;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class MyFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.myfragment,container,false);
        Button buttonSEND = view.findViewById(R.id.buttonSEND);
        buttonSEND.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TextView textView = getActivity().findViewById(R.id.textView);
                textView.setText("来自Fragment:" + System.currentTimeMillis());
            }
        });
        return view;
    }
}


     myfragment.xml

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

    <TextView
        android:id="@+id/TV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="..." />

    <Button
        android:id="@+id/buttonSEND"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_weight="0"
        android:text="发送" />
</LinearLayout>


     item.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="40dp"
    android:gravity="center"
    android:text="123"
    android:textSize="16sp">
</TextView>

关注

笔者 - jxd

微信公众号搜索 “码农总动员” 或 微信扫描下方二维码,了解更多你不知道的XX,O(∩_∩)O

在这里插入图片描述

<think>好的,我现在需要帮助用户解决在Android Studio中实现界面切换并传递参数的问题。用户还提到了Activity和Fragment之间的切换,以及参数传递的教程。首先,我应该回忆一下Android开发中处理界面切换和参数传递的基本方法。 首先,Activity之间的跳转通常使用Intent来实现,而Fragment之间的切换则需要FragmentManager或者Navigation组件。传递参数的话,Activity之间可以通过Intent的putExtra方法,而Fragment之间则建议使用Bundle,并通过setArguments来传递参数。另外,现在Google推荐使用Safe Args来处理参数传递,特别是在使用Navigation组件时,这样可以确保类型安全,减少出错的可能。 接下来,我需要考虑用户可能的背景。用户可能有一定的Android开发基础,但可能对具体的实现步骤不太清楚,尤其是参数传递部分。需要分步骤说明,并且给出代码示例,这样用户更容易理解。 然后,我需要确保回答结构清晰,按照用户的要求分步骤讲解。同时,用户要求使用中文回答,所以需要用准确的中文术语,比如“活动”、“碎片”、“意图”等。此外,用户提供的引用中提到Glide需要传入Activity和Fragment,这可能与上下文有关,但当前问题更关注界面切换和参数传递,所以引用可能只是示例,但需要注意是否需要结合引用内容。不过,根据用户的问题,引用中的内容可能并不直接相关,因此可能不需要过多涉及。 在回答中,需要覆盖两个主要部分:Activity之间的切换和参数传递,以及Fragment之间的切换和参数传递。可能还需要提到使用Navigation组件和Safe Args,因为这是现代Android开发推荐的做法,能够提高代码的安全性和可维护性。 对于代码示例,需要确保语法正确,并且使用合适的格式。例如,在Activity跳转时,使用Intent的putExtra方法添加参数,然后在目标Activity中使用getIntent().getExtras()获取参数。对于Fragment,使用Bundle和setArguments,然后在onCreateView中通过getArguments()获取参数。 此外,用户可能还想知道如何防止因屏幕旋转等配置变化导致的数据丢失,这时候可以考虑使用ViewModel来保存数据,但用户的问题主要集中在参数传递,可能暂时不需要深入讨论这方面,不过提一下可以作为优化点。 最后,生成相关问题时,需要围绕界面切换和参数传递的扩展,例如如何回传数据、使用安全参数、处理大型数据等。确保问题覆盖用户可能感兴趣的后续知识点。 现在需要组织这些思路,按照用户提供的格式,分步骤详细说明,并附上代码示例和相关问题。</think>在Android开发中,界面切换与参数传递可通过`Activity`和`Fragment`的API实现,以下是具体实现步骤: --- ### 一、Activity之间切换与参数传递 #### 1. 使用Intent传递参数 **步骤说明:** - 在源Activity中创建Intent对象 - 使用`putExtra()`方法添加参数 - 启动目标Activity **代码示例:** ```java // 源Activity Intent intent = new Intent(SourceActivity.this, TargetActivity.class); intent.putExtra("username", "John"); intent.putExtra("age", 25); startActivity(intent); // 目标Activity中获取参数 Bundle extras = getIntent().getExtras(); if (extras != null) { String username = extras.getString("username"); int age = extras.getInt("age", 0); // 0为默认值 } ``` #### 2. 使用Bundle传递复杂对象 若需传递自定义对象,需实现`Parcelable`或`Serializable`接口: ```java // 自定义类实现Parcelable public class User implements Parcelable { private String name; private int age; // 构造方法、Getter/Setter及Parcelable实现省略 } // 传递对象 User user = new User("Alice", 30); intent.putExtra("user", user); ``` --- ### 二、Fragment之间切换与参数传递 #### 1. 使用Bundle和setArguments **步骤说明:** - 创建Fragment实例时附加Bundle - 通过`getArguments()`获取参数 **代码示例:** ```java // 创建Fragment实例并传参 UserFragment fragment = new UserFragment(); Bundle args = new Bundle(); args.putString("email", "test@example.com"); fragment.setArguments(args); // Fragment中获取参数 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String email = getArguments().getString("email"); // ... } ``` #### 2. 使用Navigation组件与Safe Args(推荐) **步骤说明:** - 在`build.gradle`中添加Navigation依赖 - 定义导航图和安全参数 - 通过生成的Directions类传递参数 **代码示例:** ```gradle // build.gradle dependencies { def nav_version = "2.5.3" implementation "androidx.navigation:navigation-fragment-ktx:$nav_version" implementation "androidx.navigation:navigation-ui-ktx:$nav_version" implementation "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version" } ``` ```xml <!-- navigation_graph.xml --> <fragment android:id="@+id/userFragment" android:name="com.example.UserFragment"> <argument android:name="userId" app:argType="integer" /> </fragment> ``` ```kotlin // 源Fragment中使用Safe Args传递参数 val action = HomeFragmentDirections.actionHomeFragmentToUserFragment(userId = 123) findNavController().navigate(action) // 目标Fragment中获取参数 val userId = arguments?.getInt("userId") ``` --- ### 三、Activity与Fragment交互 #### 通过接口回调传递参数 ```java // 在Fragment中定义接口 public interface OnDataPass { void onDataPass(String data); } // Activity实现接口 public class MainActivity extends AppCompatActivity implements OnDataPass { @Override public void onDataPass(String data) { // 处理数据 } } // Fragment中调用 ((OnDataPass) requireActivity()).onDataPass("Hello from Fragment"); ``` --- ### 注意事项 1. **数据类型限制**:Intent传递的数据量需小于1MB,复杂数据建议使用数据库或ViewModel共享[^1] 2. **生命周期安全**:Fragment获取参数应在`onCreate()`或之后的生命周期方法中进行 3. **类型安全**:推荐使用Navigation组件的Safe Args避免类型错误[^2] ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

信必诺

嗨,支持下哥们呗。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值