Fragment解析创建和传参,动态添加fragment

一下是个人的一些总结。

为fragment创建XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <ListView
            android:id="@+id/yulelist"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
</LinearLayout>
public class Yule extends ListFragment {
         @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.yule,container,false);
    }
//主要就是加载我们刚刚写好的fragment.xml布局文件并返回


 

然后打开或新建activity_main.xml作为主Activity的布局文件,在里面加入两个Fragment的引用,使用android:name前缀来引用具体的Fragment:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:baselineAligned="false" > 
 
    <fragment 
        android:id="@+id/fragment1" 
        android:name="com.example.fragmentdemo.Fragment1" 
        android:layout_width="0dip" 
        android:layout_height="match_parent" 
        android:layout_weight="1" /> 
 
    <fragment 
        android:id="@+id/fragment2" 
        android:name="com.example.fragmentdemo.Fragment2" 
        android:layout_width="0dip" 
        android:layout_height="match_parent" 
        android:layout_weight="1" /> 
 
</LinearLayout>  


 

动态添加fragment将activity_main.xml中的两个fragmnet控件删除,只留下linearlayout布局。为这个布局设置一个id
//将MainActivity中的代码修改如下
public class MainActivity extends Activity { 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main);  
        //获取屏幕尺寸
        Display display = getWindowManager().getDefaultDisplay();  
        if (display.getWidth() > display.getHeight()) { 
            Fragment1 fragment1 = new Fragment1(); 
            getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit(); 
        } else { 
            Fragment2 fragment2 = new Fragment2(); 
            getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit(); 
        } 
    }  
}

首先,我们要获取屏幕的宽度和高度,然后进行判断,如果屏幕宽度大于高度就添加fragment1,如果高度大于宽度就添加fragment2。动态添加Fragment主要分为4步:

1.获取到FragmentManager,在Activity中可以直接通过getFragmentManager得到。

2.开启一个事务,通过调用beginTransaction方法开启。

3.向容器内加入Fragment,一般使用replace方法实现,需要传入容器的id和Fragment的实例。

4.提交事务,调用commit方法提交。
 
//fragment的生命周期,与activity不同的
onAttach方法:Fragment和Activity建立关联的时候调用。
onCreateView方法:为Fragment加载布局时调用。
onActivityCreated方法:当Activity中的onCreate方法执行完后调用。
onDestroyView方法:Fragment中的布局被移除时调用。
onDetach方法:Fragment和Activity解除关联的时候调用。


 

Fragment之间通信:使用了接口传参和getActivity两种方式
fragment1.xml布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <ListView
            android:id="@+id/onelist"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    </ListView>
</LinearLayout>

fragment2.xml布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@android:color/holo_green_dark">
    <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="555555555555555"
            android:layout_weight="3"
            android:id="@+id/one"/>
</LinearLayout>

fragment1:
public class Fragment1 extends Fragment implements AdapterView.OnItemClickListener{
    private ListView listView;
    private String str[]={"sssss","ddddd","ffffff","gggggg","hhhhhh","jj","mmmm"};
//传参接口
    private OnHeadlineSelectedListener mOnHeadlineSelectedListener;

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        mybaseAdapter = (MybaseAdapter) adapterView.getAdapter();
        String item=mybaseAdapter.getItem(i).toString();
     //使用接口传参
       // mOnHeadlineSelectedListener.onSelectItemClick(item);
     //使用getActivity()获取fragment2的TextView进行传参
        TextView textView=(TextView)getActivity().findViewById(R.id.one);
        Log.e("getActivity()",getActivity()+"");
        textView.setText(item);
    }
//定义传参的接口
    public interface OnHeadlineSelectedListener{
        public void onSelectItemClick(String message);
    }
//和activity建立关系
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mOnHeadlineSelectedListener=(OnHeadlineSelectedListener)activity;
    }
//为这个fragment加载布局
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       View view= inflater.inflate(R.layout.fragment1,container,false);
       listView=(ListView)view.findViewById(R.id.onelist);
        return view;
    }
//当Activity加载完成后将数据用adapter存入
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
       ArrayAdapter arrayAdapter=new ArrayAdapter(getActivity(),android.R.layout.simple_list_item_1,str);
    }

fragment2:
public class Fragment2 extends android.support.v4.app.Fragment{
    private TextView mtext;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment2,container,false);

        mtext= (TextView) view.findViewById(R.id.one);
        mtext.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_bright));
       // mtext.setText("内容");
        return  view;
    }
//写个方法为text放入参数
    public void setMtext(String message){
        mtext.setText(message);
    }
}

MainActivity:
public class MyActivity extends FragmentActivity implements Fragment1.OnHeadlineSelectedListener{
   Fragment2 fragment2;
    Fragment1 fragment1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        fragment1=new Fragment1();
        fragment2=new Fragment2();
        android.support.v4.app.FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.onefragment,fragment1);
        fragmentTransaction.add(R.id.twofragment,fragment2);
        fragmentTransaction.commit();
    }
    @Override
    public void onSelectItemClick(String message) {
        //(( Fragment2)fragment2).setMtext(message);
        fragment2.setMtext(message);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
动态 Fragment创建 ListView 时,你需要在 Fragment 的 onCreateView() 方法中创建 ListView,并设置它的 Adapter。下面是一个简单的示例代码: ```java public class MyFragment extends Fragment { private ListView listView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.my_fragment_layout, container, false); listView = view.findViewById(R.id.list_view); listView.setAdapter(new MyAdapter(getActivity())); return view; } } ``` 其中,my_fragment_layout.xml 是该 Fragment 的布局文件,包含一个 id 为 list_view 的 ListView。 接下来,你需要创建一个 Adapter,用于为 ListView 提供数据。下面是一个简单的 MyAdapter 示例代码: ```java public class MyAdapter extends BaseAdapter { private Context context; private List<String> data; public MyAdapter(Context context) { this.context = context; this.data = new ArrayList<>(); this.data.add("item 1"); this.data.add("item 2"); this.data.add("item 3"); } @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { return data.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.list_item_layout, parent, false); } TextView textView = convertView.findViewById(R.id.text_view); textView.setText(data.get(position)); return convertView; } } ``` 其中,list_item_layout.xml 是 ListView 的每个 item 的布局文件,包含一个 id 为 text_view 的 TextView,用于展示数据。 这样,你就可以在动态 Fragment创建一个 ListView 并展示数据了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值