首页 > 代码库 > Fragment 基本用法总结:
Fragment 基本用法总结:
Fragment的生命周期:
</FrameLayout>
ListFragment
显示一个由适配器管理的条目列表(例如SimpleCursorAdapter),类似于ListActivity。并且提供了许多管理列表视图的函数,例如处理点击事件的onListItemClick()回调函数。
PreferenceFragment
显示一个Preference对象的体系结构列表,类似于preferenceActivity。这在为应用程序创建“设置”activity时是很实用的。
Fragment与Fragment和Fragment与Activity通讯
FragmentActivity兼容2.3系统的Activity;
// 获得activity的传递的值
// 实例化成员变量
// 给当前的fragment绘制UI布局,可以使用线程更新UI
// 表示activity执行oncreate方法完成了的时候会调用此方法
// 和activity一致
// 和activity一致
// 和activity一致
// 和activity一致
// 表示fragment销毁相关联的UI布局 ;
The fragment returns to the layout from the back stack;讲放回到oncreateview();
// 销毁fragment对象
// 脱离activity
FragmentManager & FragmentTransaction添加视图界面和管理Fragment:
有三种方法给fragment提供ID:
1 为android:id属性赋一个特定的标识符。
2 为android:tag属性赋一个标记名称。
2 为android:tag属性赋一个标记名称。
3如果你没有使用上述任何一种方法,系统将使用fragment的容器的ID。
1使用方法findFragmentById()或findFragmentByTag(),获取activity中已存在的fragment们。
2使用方法popBackStack()从activity的后退栈中弹出fragment们(这可以模拟后退键引发的动作)。
3用方法addOnBackStackChangedListerner()注册一个侦听器以监视后退栈的变化。
findFragmentById和findFragmentByTag的区别:
// findFragmentById;for fragment that privide a ui activity layout 以ID作为唯一的标识符
// findFragmentByTag; for fragments that do or don‘t provide a UI;
// frament = (MyFragment) manager.findFragmentById(R.id.fragment1);
frament = (MyFragment) manager.findFragmentByTag("fragment1"); <fragment
android:tag="fragment1"
android:name="com.example.android_fragment_manager.MyFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="143dp" /> (1):代码操作添加;
private FragmentManager manager;
private FragmentTransaction transaction;// 事物 manager = getFragmentManager();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
transaction = manager.beginTransaction();
MyFragment myFragment = new MyFragment();
transaction.add(R.id.right, myFragment);
transaction.commit();
}
}); private void showFragments(String tag, boolean needback) {
FragmentTransaction trans = mFragMgr.beginTransaction();
if (needback) {
trans.setCustomAnimations(R.anim.frag_enter, R.anim.frag_exit);
trans.add(R.id.content, getFragmentByTag(tag), tag);
trans.addToBackStack(tag);
} else {
trans.replace(R.id.content, getFragmentByTag(tag), tag);
}
trans.commit();
} (2):xml中直接添加Fragment;
<FrameLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<fragment
android:tag="introduce"
android:name="com.huika.twm.member.ui.fragment.ShopIntroduceFra"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<fragment
android:tag="takeout"
android:name="com.huika.twm.member.ui.fragment.ShopTakeoutFra"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
@Override
protected void initWidget() {
super.initWidget();
TitleBarHelper titleBarHelper = new TitleBarHelper(this, R.string.common_back, -1, R.string.shop_name);
titleBarHelper.setTitleMsg(bean.merchantName);
customer_radio_group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.takeout_rb:
// takeout_rb.setTextColor(Color.parseColor("#ffa215"));
// takeout_introduce.setTextColor(Color.parseColor("#333333"));
changeFragment(TAKEOUT);
break;
case R.id.takeout_introduce:
// takeout_rb.setTextColor(Color.parseColor("#333333"));
// takeout_introduce.setTextColor(Color.parseColor("#ffa215"));
changeFragment(INTRODUCE);
break;
}
}
});
takeoutFragment = fragManager.findFragmentByTag(TAKEOUT);
introFragment = fragManager.findFragmentByTag(INTRODUCE);
} 控制Fragment显示和隐藏;
不是v4;
protected void changeFragment(String tag) {
Fragment showFragment = null;
Fragment hideFragment = null;
FragmentTransaction transaction = fragManager.beginTransaction();
if(TAKEOUT.equals(tag)){
showFragment = takeoutFragment;
hideFragment = introFragment;
}else{
showFragment = introFragment;
hideFragment = takeoutFragment;
}
transaction.hide(hideFragment);
transaction.show(showFragment);
transaction.commit();
} v4;
private void showFrag(String flag) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = getSupportFragmentManager().findFragmentByTag(flag);
if (fragment == null) {
if (RETURN.equals(flag)) {
fragment = new MyCashBackRecordFragment();
} else {
fragment = new MyDividendRecordFragment();
}
transaction.add(R.id.content, fragment, flag);
}
List<Fragment> frags = getSupportFragmentManager().getFragments();
if (frags != null)
for (Fragment f : frags) {
if (f != fragment)
transaction.hide(f);
}
transaction.show(fragment);
transaction.commit();
}
(3):添加一个没有界面的fragment;待研究;
上面演示了如何添加fragment来提供界面,然而,你也可以使用fragment为activity提供后台的行为而不用显示fragment的界面。
要添加一个没有界面的fragment,需在activity中调用方法add(Fragment,String)(它支持用一个唯一的字符串做为fragment的”tag”,而不是viewID)。这样添加的fragment由于没有界面,所以你在实现它时不需调用实现onCreateView()方法。
使用tag字符串来标识一个fragment并不是只能用于没有界面的fragment上,你也可以把它用于有界面的fragment上,但是,如果一个fragment没有界面,tag字符串将成为它唯一的选择。获取以tag标识的fragment,需使用方法findFragmentByTab()。
ListFragment &PreferenceFragment &DialogFragment ;
DialogFragment
显示一个浮动的对话框。使用这个类创建对话框是使用Activity类对话框工具方法之外的另一个不错的选择,因为你可以把fragment对话框并入到由activity管理的fragments后台栈中,允许用户返回到一个已经摒弃的fragment。
显示一个浮动的对话框。使用这个类创建对话框是使用Activity类对话框工具方法之外的另一个不错的选择,因为你可以把fragment对话框并入到由activity管理的fragments后台栈中,允许用户返回到一个已经摒弃的fragment。
ListFragment
显示一个由适配器管理的条目列表(例如SimpleCursorAdapter),类似于ListActivity。并且提供了许多管理列表视图的函数,例如处理点击事件的onListItemClick()回调函数。
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
transaction = manager.beginTransaction();
ArticleListFragment fragment = new ArticleListFragment();
transaction.add(R.id.center, fragment, "article");
transaction.commit();
}
}); 方法一ArrayAdatper: ( 不用写界面)
ArticleListFragment extends ListFragment ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<String> data = new ArrayList<String>();
for (int i = 0; i < 30; i++) {
data.add("rose" + i);
}
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, data);
setListAdapter(adapter);
manager = getFragmentManager();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, getData()));
return super.onCreateView(inflater, container, savedInstanceState);
} @Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String item = adapter.getItem(position);
transaction = manager.beginTransaction();
// Fragment直接传递值;
DetailFragment fragment = new DetailFragment();
Bundle args = new Bundle();
args.putString("item", item);
fragment.setArguments(args);
transaction.replace(R.id.right, fragment, "rightfragment");
transaction.addToBackStack("rightfragment");
transaction.commit();
// Toast.makeText(getActivity(), "-->>" + item, 1).show();
} (也可以自定义界面显示,这个就得重写onCreateView()方法)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//注意这里; android:id="@android:id/list"
View view = inflater.inflate(R.layout.fragment_pager_list, null);
TextView textView = (TextView) view.findViewById(R.id.text);
textView.setText("Fragment #" + num);
return view;
} DetailFragment :
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail, null);
// getArguments()
TextView textView = (TextView) view.findViewById(R.id.textView1);
textView.setText("" + getArguments().getString("item"));
return view;
} 方法二Adatper: ( 写界面)
private MyAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new MyAdapter();
adapter.bindData(getData());
} // 数据源
public List<String> getData() {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 20; i++) {
list.add("jack" + i);
}
return list;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// android:id="@id/android:list"
View view = inflater.inflate(R.layout.article, null);
setListAdapter(adapter);
// 这样设置不对;
// ListView listView = (ListView)view.findViewById(R.id.listView);
// listView.setAdapter(adapter);
return view;
}PreferenceFragment
显示一个Preference对象的体系结构列表,类似于preferenceActivity。这在为应用程序创建“设置”activity时是很实用的。
Fragment与Fragment和Fragment与Activity通讯
Fragment与Fragment
(1):SharedPreferences进行传递;
(2):transaction = manager.beginTransaction();
// Fragment直接传递值;
DetailFragment fragment = new DetailFragment();
Bundle args = new Bundle();
args.putString("item", item);
fragment.setArguments(args);
transaction.replace(R.id.right, fragment, "rightfragment");
transaction.addToBackStack("rightfragment");
transaction.commit();
(3):查找传递(LeftFragment) manager.findFragmentByTag("left");
这个方法有点极限;只有当两个界面都显示时,才有效;
MainActivity:
LeftFragment leftFragment = new LeftFragment();
RightFragment rightFragment = new RightFragment();
transaction.add(R.id.left, leftFragment, "left");
transaction.add(R.id.right, rightFragment, "right");
// transaction.add(containerViewId, fragment, tag);
transaction.commit(); LeftFragment:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RightFragment rightFragment = (RightFragment) manager.findFragmentByTag("right");
String msg = ((EditText) rightFragment.getView().findViewById(R.id.editText1)).getText().toString();
Toast.makeText(getActivity(), "-right->>" + msg, 1).show();
}
});RightFragment:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LeftFragment leftFragment = (LeftFragment) manager.findFragmentByTag("left");
String msg = ((EditText) leftFragment.getView().findViewById(R.id.editText1)).getText().toString();
Toast.makeText(getActivity(), "-left->" + msg, 1).show();
}
}); Fragment与Activity
方法一:(回调处理);
Activity获取Fragment中的数据;
MainActivity:
final LeftFragment leftFragment = new LeftFragment();
transaction.add(R.id.left, leftFragment, "left");
transaction.commit();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
leftFragment.getEditText(new CallBack() {
@Override
public void getResult(String result) {
Toast.makeText(MainActivity.this, "-->>" + result, 1).show();
}
});
}
}); LeftFragment:
// 接口回调
public void getEditText(CallBack callBack) {
String msg = editText.getText().toString();
callBack.getResult(msg);
}
public interface CallBack {
public void getResult(String result);
} ----------------------------------------------------------------------------------------
public static void main(String[] args) {
A a = new A();
a.loadImage("http://www.baidu.com/a.gif", new CallBack() {
@Override
public void getResult(String result) {
System.out.println("---->>" + result);
}
});
} // 下载图片的操作
public void loadImage(String image_path, final CallBack callBack) {
new Thread(new Runnable() {
@Override
public void run() {
// 完成下载图片的功能byte[] bitmap
// byte[] result = new byte[1024];
String msg = "hell world";
callBack.getResult(msg);
}
}).start();
}
public interface CallBack {
public void getResult(String result);
} Fragment和Activity之间相互的数据;
1.首先我需要定义一个公共接口,用于将Fragment与FragmentActivity中的控件进行交互
public interface IBtnCallListener {
public void transfermsg();
}
public class LaunchUIFragment extends Fragment implements IBtnCallListener{
IBtnCallListener mbtnListener;
private Button btn_Click;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_selection_launch, container, false);
btn_Click=(Button) rootView.findViewById(R.id.bt_click);
btn_Click.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mbtnListener.transfermsg();
}
});
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
try {
mbtnListener=(IBtnCallListener) activity;
} catch (Exception e) {
// TODO: handle exception
throw new ClassCastException(activity.toString() + "must implement mbtnListener");
}
super.onAttach(activity);
}
@Override
public void transfermsg() {
// TODO Auto-generated method stub
System.out.println("由Activity传输过来的信息");
}
}
public class MainActivity extends FragmentActivity implements IBtnCallListener{
private IBtnCallListener mBtnCallListener;
@Override
public void onAttachFragment(Fragment fragment) {
// TODO Auto-generated method stub
try {
mBtnCallListener=(IBtnCallListener) fragment;
} catch (Exception e) {
// TODO: handle exception
}
super.onAttachFragment(fragment);
}
@Override
public void transfermsg() {
// TODO Auto-generated method stub
System.out.println("由Fragment传输过来的信息");
}
方法二:(直接写方法处理调用Activity和Fragment中的方法);
菜单:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/sys"
android:orderInCategory="100"
android:showAsAction="always"
android:title="@string/sys"/>
<item
android:id="@+id/user"
android:orderInCategory="100"
android:showAsAction="always"
android:title="@string/user"/>
<item
android:id="@+id/product"
android:orderInCategory="100"
android:showAsAction="always"
android:title="@string/product"/>
</menu> @Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
transaction = manager.beginTransaction();
switch (item.getItemId()) {
case R.id.sys:
SysFragment sysFragment = new SysFragment();
transaction.replace(R.id.main, sysFragment, "sysFragment");
transaction.addToBackStack("sysFragment");
break;
case R.id.user:
UserFragmnet userFragmnet = new UserFragmnet();
transaction.replace(R.id.main, userFragmnet, "userFragmnet");
transaction.addToBackStack("userFragmnet");
break;
case R.id.product:
ProductFragment productFragment = new ProductFragment();
transaction.replace(R.id.main, productFragment, "productFragment");
transaction.addToBackStack("productFragment");
break;
}
transaction.commit();
return super.onOptionsItemSelected(item);
}
} 来自为知笔记(Wiz)
Fragment 基本用法总结:
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。