Fragment碎片整理

本文介绍了一个使用Fragment进行界面布局划分的实例,展示了如何通过XML定义左右两个Fragment,并在Java代码中实现ListView点击事件来更新右侧Fragment的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Fragment碎片整理


不多说  直接上代码 效果图





先定义几个碎片


fragment_left.xml文件 

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/lv_fragment_left_contacts"
    ></ListView>
    
    


fragment——right.xml

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



activity_main .xml

    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:id="@+id/f_main_left"
        android:name="com.example.android_06_15.LeftFragment"
         >
    </fragment>

        <fragment
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:id="@+id/f_main_right"
            android:name="com.example.android_06_15.RightFragment"
></fragment>

然后给JAVA代码设置关联

RightFragment.java

public class RightFragment extends Fragment{

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View v=inflater.inflate(R.layout.fragment_right,null);

        return v;
    }
}

LeftFragment.java

public class LeftFragment extends Fragment{


    private ListView lv_fragment_left_contacts;
    String [] list={"一号","二号","三号","四号"};

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View v=inflater.inflate(R.layout.fragment_left,null);
        lv_fragment_left_contacts = (ListView) v.findViewById(R.id.lv_fragment_left_contacts);

        ArrayAdapter adapter=new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,list);
        lv_fragment_left_contacts.setAdapter(adapter);

        //给左边的ListView 设置事件
        lv_fragment_left_contacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //情况:右边是同样的布局
                TextView tv_fragment_right_phone= (TextView) getActivity().findViewById(R.id.tv_fragment_right_phone);
                tv_fragment_right_phone.setText(list[position]);
});

}
}


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值