Fragment

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/important0534/article/details/51731065
<pre name="code" class="java">FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fa = new FragmentA();
ft.add(R.id.fl, fa, "aaa");
ft.commit();



FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
fa = new FragmentA();
ft.replace(R.id.fl, fa, "aaa");
ft.commit();

add是添加Fragment 到 ViewGroup 中, 可以多次添加,会重叠;  与hide 结合使用,Fragment 方法不用从头走一遍;

(replace方法相当于remove, add结合使用;  remove从当前manager中移除,则前一个(没加入栈的前提下)不能通过 findFragmentByTag找到;

此时fragment对象依然有效,内部成员变量的值依然保存在内存中;  要注意:当重新走一遍生命周期 成员变量的值的问题) ;


add 和 hide ,当activity销毁重新创建出现重影问题: 由于 activity 的 onSaveInstanceSate 中调用了父类的方法, 说明fragment也要重新创建;

重新创建时 oncreate 通过 bundle 传递 了 Fragment对象;   因此  一般 saveInstance==null 才创建 fragment对象,避免内存中两个一样

的Fragment对象,造成重影; 另外, 成员变量的引用 可以通过findFragmentByTag获得内存中的fragment对象;   注意: fragment也

可通过 onSaveInstanceState保存状态,以便恢复用;

另外  加上 addToBackStack后,  findFragmentByTag 总能找到它;

///

addToBackState(String tag) ; 

tag用于标记一次事务;

一次事务能提交多个Fragment到回退栈; 

当出栈时,一次事务的 fragment都会出栈;


此外看看:

http://www.jianshu.com/p/d9143a92ad94


展开阅读全文

Fragment嵌套Fragment

06-21

[code=java]package com.example.android_firstcos.Fragment;rnrnimport java.util.ArrayList;rnrnimport android.os.Bundle;rnimport android.support.v4.app.Fragment;rnimport android.support.v4.view.ViewPager;rnimport android.util.DisplayMetrics;rnimport android.view.LayoutInflater;rnimport android.view.View;rnimport android.view.View.OnClickListener;rnimport android.view.ViewGroup;rnimport android.view.animation.Animation;rnimport android.view.animation.TranslateAnimation;rnimport android.widget.ImageView;rnimport android.widget.TextView;rnrnimport com.example.android_firstcos.R;rnimport com.example.android_firstcos.Fragment.mainFragment.ShouYeFragment;rnimport com.example.android_firstcos.FragmentAdapter.MyFragmentAdapter;rnrnpublic class MainFragment extends Fragment rn private TextView SHOUYE, BIAOQIAN;rn private ImageView XIAHUAXIAN;rn private ViewPager mViewPager;rn private ArrayList list;rn private int index;rn private int max;rn private int flag = 0;rnrn @Overridern public void onCreate(Bundle savedInstanceState) rn // TODO Auto-generated method stubrn super.onCreate(savedInstanceState);rnrn rnrn @Overridern public View onCreateView(LayoutInflater inflater, ViewGroup container,rn Bundle savedInstanceState) rn // TODO Auto-generated method stubrn View view = inflater.inflate(R.layout.mainfragment, container, false);rn mViewPager = (ViewPager)container.findViewById(R.id.vPage);rn SHOUYE = (TextView) container.findViewById(R.id.textView2);rn BIAOQIAN = (TextView) container.findViewById(R.id.textView3);rn XIAHUAXIAN = (ImageView) container.findViewById(R.id.imageView1);rn InitData();rn InitViewPager();rn SHOUYE.setOnClickListener(new MyMainFragmentOnClickListener());rn BIAOQIAN.setOnClickListener(new MyMainFragmentOnClickListener());rn return view;rn rnrn private void InitData() rn DisplayMetrics dm = new DisplayMetrics();rn getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);rn max = dm.widthPixels;rn index = (int) (max / 4.0);rn rnrn private void InitViewPager() rn list = new ArrayList();rn list.add(new ShouYeFragment());rn list.add(new ShouYeFragment());rn System.out.println(list.toString());rn mViewPager.setAdapter(new MyFragmentAdapter(getChildFragmentManager(),rn list));rn mViewPager.setCurrentItem(0);rn mViewPagerrn .setOnPageChangeListener(new MyMainFragmentOnPageChangeListener());rn rnrn private class MyMainFragmentOnClickListener implements OnClickListener rn @Overridern public void onClick(View arg0) rn // TODO Auto-generated method stubrn mViewPager.setCurrentItem(0);rn rn rnrn private class MyMainFragmentOnPageChangeListener implementsrn ViewPager.OnPageChangeListener rnrn @Overridern public void onPageScrollStateChanged(int arg0) rn // TODO Auto-generated method stubrn rnrn @Overridern public void onPageScrolled(int arg0, float arg1, int arg2) rn // TODO Auto-generated method stubrn rnrn @Overridern public void onPageSelected(int arg0) rn // TODO Auto-generated method stubrn Animation animation = null;rn switch (arg0) rn case 0:rn if (flag == 1) rn animation = new TranslateAnimation(index, 0, 0, 0);rn rn break;rnrn case 1:rn if (flag == 0) rn animation = new TranslateAnimation(0, index, 0, 0);rn rn break;rnrn default:rn break;rn rn flag = arg0;rn animation.setFillAfter(true);rn animation.setDuration(300);rn XIAHUAXIAN.startAnimation(animation);rn rnrn rnrn[/code]rn提示我空指针[img=https://img-bbs.csdn.net/upload/201406/21/1403343691_609971.jpg][/img] 求大神帮忙rnmViewPager.setAdapter(new MyFragmentAdapter(getChildFragmentManager(),rn list));这行报空指针 论坛

fragmentfragment传递数据问题

03-28

fragment向fragment传递数据问题,我想从MsgFragment这里 点击之后获取城市名传到下一个跳转的AttractionsFragment并获取String city,我试过用javabean的SET GET方法没用。IndexFragment这个方法是写fragment跳转代码的。rn有没有人帮下额。难住我很久了。rn项目地址链接:https://pan.baidu.com/s/1VbWzHWg26cJ8iKNcIFlSeQ rn提取码:vu86 rnrn```rnpublic class IndexFragment extends Fragment implements ChangeFragment rnrn private Fragment fragmentMsg;rn private Fragment fragmentColl;rn private Fragment fragmentAction;rnrn @Nullablern @Overridern public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) rn View view1 = LayoutInflater.from(getContext()).inflate(R.layout.fragment_index, container, false);rn return view1;rn rnrn @Overridern public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) rn super.onViewCreated(view, savedInstanceState);rnrn fragmentMsg = MsgFragment.newInstance(this);rn fragmentColl = AttractionsFragment.newInstance(this);rn fragmentAction=AttractionsContentFragment.newInstance(this);rnrn changeResult();rn rnrn @Overridern public void changeFragment() rn getChildFragmentManager()rn .beginTransaction()rn .addToBackStack(null)rn .replace(R.id.fl_content,fragmentColl).commit();rn rnrn @Overridern public void changeResult() rn getChildFragmentManager()rn .beginTransaction()rn .addToBackStack(null)rn .replace(R.id.fl_content,fragmentMsg).commit();rn rnrn @Overridern public void changeAttractionsContent() rn getChildFragmentManager()rn .beginTransaction()rn .addToBackStack(null)rn .replace(R.id.fl_content,fragmentAction).commit();rn rnrnrnrn```rnrn```rnpublic class MsgFragment extends Fragment rnrn View view;rnrn private int i;rn private String str;rnrnrn private String[] mVals = new String[] "南宁市","柳州市","桂林市" ,"梧州市" ,"北海市","防城港市","钦州市","贵港市","玉林市","百色市","贺州市","河池市","来宾市","崇左市";rn private LayoutInflater mInflater;rn private FlowLayout mFlowLayout;rn private CityEntity cityEntity ;rnrnrnrnrn private static ChangeFragment mChange;rnrn public static MsgFragment newInstance(ChangeFragment changeFragment) rn mChange = changeFragment;rn Bundle args = new Bundle();rn MsgFragment fragment = new MsgFragment();rn fragment.setArguments(args);rn return fragment;rn rnrn @Overridern public void onCreate(@Nullable Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rnrn mInflater = LayoutInflater.from(getContext());rnrnrn rnrn public MsgFragment() rn rnrnrn @Overridern public View onCreateView(LayoutInflater inflater, ViewGroup container,rn Bundle savedInstanceState) rnrn view = inflater.inflate(R.layout.fragment_msg, container, false);rnrn mFlowLayout = view.findViewById(R.id.id_flowlayout);rnrnrn initData();rnrnrn return view;rn rnrn public void initData() rn /**rn * 找到搜索标签的控件rn */rn for (i = 0; i < mVals.length; i++) rn final TextView tv = (TextView) mInflater.inflate(rn R.layout.search_label_tv, mFlowLayout, false);rn tv.setText(mVals[i]);rn str = tv.getText().toString();rn //点击事件rn tv.setOnClickListener(new View.OnClickListener() rn @Overridern public void onClick(View v) rn try rnrn switch (((TextView) v).getText().toString()) rn case "南宁市":rnrn String a="南宁市";rnrnrn rn changeToAnotherFragment();rnrnrnrn break;rn case "柳州市":rn cityEntity.setCity("柳州市");rn changeToAnotherFragment();rnrn break;rn case "桂林市":rn cityEntity.setCity("桂林市");rn changeToAnotherFragment();rnrn break;rn case "梧州市":rn cityEntity.setCity("梧州市");rn changeToAnotherFragment();rnrn break;rn case "北海市":rn cityEntity.setCity("北海市");rn changeToAnotherFragment();rn break;rn case "防城港市":rn cityEntity.setCity("防城港市");rn changeToAnotherFragment();rn break;rn case "钦州市":rn cityEntity.setCity("钦州市");rn changeToAnotherFragment();rn break;rn case "贵港市":rn cityEntity.setCity("贵港市");rn changeToAnotherFragment();rn break;rn case "玉林市":rn cityEntity.setCity("玉林市");rn changeToAnotherFragment();rn break;rn case "百色市":rn cityEntity.setCity("百色市");rn changeToAnotherFragment();rn break;rn case "贺州市":rn cityEntity.setCity("贺州市");rn changeToAnotherFragment();rn break;rn case "河池市":rn cityEntity.setCity("河池市");rn changeToAnotherFragment();rn break;rn case "来宾市":rn cityEntity.setCity("来宾市");rn changeToAnotherFragment();rn break;rn case "崇左市":rn cityEntity.setCity("崇左市");rn changeToAnotherFragment();rn break;rn default:rnrn break;rn rnrnrn catch (Exception e) rn e.printStackTrace();rn rnrn rn );rn mFlowLayout.addView(tv);//添加到父Viewrn rnrnrn rnrn @SuppressLint("ResourceType")rn private void changeToAnotherFragment() rn mChange.changeFragment();rn rnrnrn```rnrn```rnpublic class AttractionsFragment extends Fragment rn private MyListView attr_lv;rn private JSONArray attr_array;rn private ImageLoaderConfiguration configuration;rn public DisplayImageOptions imageOptions;rn private Handler handler;rn private int msggg=0;rn public String city;rnrn private static ChangeFragment mChange;rn public static AttractionsFragment newInstance(ChangeFragment changeFragment) rn mChange = changeFragment;rn Bundle args = new Bundle();rnrn AttractionsFragment fragment = new AttractionsFragment();rn fragment.setArguments(args);rn return fragment;rn rn @Nullablern @Overridern public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) rn //获取fragment的layoutrn View view = inflater.inflate(R.layout.fragment_attractions, container, false);rn //对recycleview进行配置rnrnrnrnrnrn return view;rn rnrnrn @Overridern public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) rn super.onViewCreated(view, savedInstanceState);rnrn attr_lv=view.findViewById(R.id.frag_attractions);rn configuration = ImageLoaderConfiguration.createDefault(getActivity());rn ImageLoader.getInstance().init(configuration);rn imageOptions = DisplayImageOptions.createSimple();rn initData();rn handler=new Handler()rn @Overridern public void handleMessage(Message msg) rn if(msg.what ==msggg)rnrn attr_lv.setAdapter(new AttracListAdapter(getActivity()));rn attr_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() rn @Overridern public void onItemClick(AdapterView parent, View view, int position, long id) rn Toast.makeText(getActivity(),String.valueOf(position),Toast.LENGTH_SHORT).show();rn try rn JSONObject object1=attr_array.getJSONObject(position);rn String a= object1.getString("foodtitle");rn String b=object1.getString("foodcontentimg");rn System.out.println(a);rn System.out.println(b);rnrn catch (JSONException e) rn e.printStackTrace();rn rnrn rn );rnrn rn rn ;rnrn rnrnrnrnrnrnrn private void initData() rn new Thread()rn public void run()rn rn String url = DocUtil.attractions_list;rnrnrnrnrn rn System.out.println(city);rn OkHttpClient okHttpClient = new OkHttpClient();rn String token= CacheUtils.getString(getActivity(), "token", "");rn RequestBody body = new FormBody.Builder()rn .add("token",token)rn .add("city",city)rn .build();rnrn Request request = new Request.Builder()rn .url(url)rn .post(body)rn .build();rnrn Call call = okHttpClient.newCall(request);rn try rn Response response = call.execute();rn //System.out.println(response.body().string());rn try rn final String string=response.body().string();rn final JSONObject object=new JSONObject(string);rn attr_array=object.getJSONArray("attractionsList");rn System.out.println(attr_array);rn if(attr_array.length()>0) rnrn try rnrnrn Message msg = new Message();rn msg.what = msggg;rn handler.sendMessage(msg);rnrnrn catch (Exception e) rn e.printStackTrace();rn rnrn else rn Toast.makeText(getActivity(), "无数据", Toast.LENGTH_SHORT).show();rn rn catch (JSONException e) rn e.printStackTrace();rn rn catch (IOException e) rn e.printStackTrace();rn rn rn .start();rnrnrnrnrnrn rnrn class AttracListAdapter extends BaseAdapter rn private Context mContext;rnrnrn public AttracListAdapter(Context mContext) rn super();rn this.mContext = mContext;rn rnrn @Overridern public int getCount() rn // TODO Auto-generated method stubrn return attr_array.length();rn rnrn @Overridern public Object getItem(int position) rn return position;rn rnrn @Overridern public long getItemId(int position) rn return position;rn rnrn @Overridern public View getView(int position, View convertView, ViewGroup parent) rn if (convertView == null) rn convertView = LayoutInflater.from(mContext).inflate(rn R.layout.attractions_item, parent, false);rn try rn JSONObject object=attr_array.getJSONObject(position);rnrn TextView tvss1=convertView.findViewById(R.id.attrac_title);rn TextView tvss2=convertView.findViewById(R.id.attrac_content);rnrnrn tvss1.setText(object.getString("attractionstitle"));rnrn tvss2.setText("地址:"+object.getString("attractionscontent"));rnrn ImageView img=convertView.findViewById(R.id.attrac_img);rnrnrnrn ImageLoader.getInstance().displayImage(DocUtil.base_url+rn object.getString("attrac_img"), img,rn imageOptions);rn catch (Exception e) rn e.printStackTrace();rn rnrn rnrn return convertView;rn rn rnrnrn```rnrn```rnpublic interface ChangeFragment rnrn void changeFragment();rnrn void changeResult();rnrn void changeAttractionsContent();rnrn``` 问答

fragment跳转另一个fragment的问题!

03-12

项目地址:rn链接: https://pan.baidu.com/s/1OHSva0M5PIQMWNP0iwzlLg 提取码: csf5 rnrn求大能帮我解决一下。我不知道怎么去写这个跳转。rnrn![图片说明](https://img-ask.csdn.net/upload/201903/12/1552331749_241936.png)rnrnrnrn鼠标点击需要跳转(例如点击“苹果手机”);rnrnrn```rnpublic class MsgFragment extends Fragment rnrn View view;rn TextView textView;rn private int i;rn private String str;rnrnrn private String[] mVals = new String[] "苹果手机", "笔记本电脑", "电饭煲", "腊肉",rn "特产", "剃须刀", "宝宝", "康佳" ;rn private LayoutInflater mInflater;rn private FlowLayout mFlowLayout;rnrn //自定义recyclerveiw的适配器rnrnrnrn @Overridern public void onCreate(@Nullable Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rnrn mInflater = LayoutInflater.from(getContext());rnrnrn rnrn public MsgFragment() rn rnrnrn @Overridern public View onCreateView(LayoutInflater inflater, ViewGroup container,rn Bundle savedInstanceState) rnrn view = inflater.inflate(R.layout.fragment_msg, container, false);rnrn mFlowLayout = view.findViewById(R.id.id_flowlayout);rnrnrn initData();rnrnrn return view;rn rn public void initData() rn /**rn * 找到搜索标签的控件rn */rn for ( i = 0; i < mVals.length; i++) rn final TextView tv = (TextView) mInflater.inflate(rn R.layout.search_label_tv, mFlowLayout, false);rn tv.setText(mVals[i]);rn str = tv.getText().toString();rn //点击事件rn tv.setOnClickListener(new View.OnClickListener() rn @Overridern public void onClick(View v) rn try rnrn switch (str) rn case "苹果手机":rnrn rn break;rn case "笔记本电脑":rnrn break;rn case "电饭煲":rnrn break;rn case "腊肉":rnrn break;rn case "特产":rnrn break;rn case "剃须刀":rnrn break;rn case "宝宝":rnrn break;rn case "康佳":rnrn break;rn default:rnrn break;rn rnrnrnrnrnrn catch (Exception e) rn e.printStackTrace();rn rnrn rn );rn mFlowLayout.addView(tv);//添加到父Viewrn rnrnrn rnrnrnrn```rn需要跳转到的fragmentrnrn```rnpublic class CollectFragment extends Fragment rn private View view;//定义view用来设置fragment的layoutrn public RecyclerView mCollectRecyclerView;//定义RecyclerViewrn //定义以goodsentity实体类为对象的数据集合rn private ArrayList goodsEntityList = new ArrayList();rn //自定义recyclerveiw的适配器rn private CollectRecycleAdapter mCollectRecyclerAdapter;rnrn @Nullablern @Overridern public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) rn //获取fragment的layoutrn view = inflater.inflate(R.layout.item_content, container, false);rn //对recycleview进行配置rn initRecyclerView();rn //模拟数据rn initData();rn return view;rn rnrn /**rn * TODO 模拟数据rn */rn private void initData() rn for (int i=0;i<10;i++)rn GoodsEntity goodsEntity=new GoodsEntity();rn goodsEntity.setGoodsName("模拟数据"+i);rn goodsEntity.setGoodsPrice("100"+i);rn goodsEntityList.add(goodsEntity);rn rn rnrn /**rn * TODO 对recycleview进行配置rn */rnrn private void initRecyclerView() rn //获取RecyclerViewrn mCollectRecyclerView=view.findViewById(R.id.collect_recyclerView);rn //创建adapterrn mCollectRecyclerAdapter = new CollectRecycleAdapter(getActivity(), goodsEntityList);rn //给RecyclerView设置adapterrn mCollectRecyclerView.setAdapter(mCollectRecyclerAdapter);rn //设置layoutManager,可以设置显示效果,是线性布局、grid布局,还是瀑布流布局rn //参数是:上下文、列表方向(横向还是纵向)、是否倒叙rn mCollectRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));rn //设置item的分割线rn mCollectRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));rn //RecyclerView中没有item的监听事件,需要自己在适配器中写一个监听事件的接口。参数根据自定义rn mCollectRecyclerAdapter.setOnItemClickListener(new CollectRecycleAdapter.OnItemClickListener() rn @Overridern public void OnItemClick(View view, GoodsEntity data) rn //此处进行监听事件的业务处理rn Toast.makeText(getActivity(),"我是item",Toast.LENGTH_SHORT).show();rn rn );rn rnrnrnrn``` 问答

没有更多推荐了,返回首页