Android之使用Activity与Fragment通信

本文详细介绍了在Android开发中如何实现Activity与Fragment之间的通信,包括Fragment的布局设置、Java代码操作,Activity的处理方式,以及两者如何关联和进行数据交换。
摘要由CSDN通过智能技术生成

一、Fragment—布局

<FrameLayout 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:background="@android:color/holo_orange_light"
    tools:context=".chapter17.FragmentSetterGetter">

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Hello" />

</FrameLayout>

二、Fragment—Java代码

public class FragmentSetterGetter extends Fragment {

    private TextView tvContent;

    public FragmentSetterGetter() {
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fragment_setter_getter, container, false);
        tvContent = view.findViewById(R.id.tv_content);
        return view;
    }

    public void setContemt(String content) {
        tvContent.setText(content);
    }

    public String getContent() {
        return tvContent.getText().toString();
    }
}

三、Activity—Java代码

public class IndexActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
     }
}

四、关联

        fragment = new FragmentSetArgument();
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_container, fragment);
        transaction.commit();

五、通信

        private String[] categorys = new String[]{"国际品牌", "奢饰品", "唯品会", "男装", "女装"};
        categoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                 fragment.setContemt(categorys[position]);
            }
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值