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]);
});
}
}