本篇文章给大家谈谈Androidfragment实现按钮点击事件的示例讲解,以及android点击事件的三种方式的知识点,同时本文还将给你拓展AndroidApp在ViewPager中使用Fragme
本篇文章给大家谈谈Android fragment实现按钮点击事件的示例讲解,以及android点击事件的三种方式的知识点,同时本文还将给你拓展Android App在ViewPager中使用Fragment的实例讲解、Android Fragment 和 FragmentManager 的代码分析、android fragment 控件点击、Android FragmentManage FragmentTransaction 介绍等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:- Android fragment实现按钮点击事件的示例讲解(android点击事件的三种方式)
- Android App在ViewPager中使用Fragment的实例讲解
- Android Fragment 和 FragmentManager 的代码分析
- android fragment 控件点击
- Android FragmentManage FragmentTransaction 介绍
Android fragment实现按钮点击事件的示例讲解(android点击事件的三种方式)
fragment无法直接进行点击事件,需要放到oncreatActivity中
代码如下:
@Override public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_first,null); return view; }
点击事件代码:
@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Button sweepButton = (Button) getActivity().findViewById(R.id.image1); sweepButton.setonClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(),"nihao",Toast.LENGTH_LONG).show(); //从fragment跳转到activity中 startActivity(new Intent(getActivity(),PayMoneyActivity.class)); } }); }
以上这篇Android fragment实现按钮点击事件的示例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。
您可能感兴趣的文章:
- Android开发-之监听button点击事件的多种方法
- Android在Fragment中实现监听触摸事件
Android App在ViewPager中使用Fragment的实例讲解
据说Android最推荐的是在ViewPager中使用FragMent,即ViewPager中的页面不像前面那样用LayoutInflater直接从布局文件加载,而是一个个Fragment。注意这里的Fragment
是android.support.v4.view包里的Fragment,而不是android.app包里的Fragment。
使用v4包里的Fragment的Activity必须继承自FragmentActivity。
其实使用Fragment与前面不使用Fragment非常类似:
第一步 在主布局文件里放一个ViewPager组件
第二步 为每个页面建立布局文件,把界面写好
第三步 为每个页面新建Fragment类,并加载布局文件中的界面
第四部 为ViewPager设定Adapter,只不过这里的Adapter不是PagerAdapter,而是换成
FragmentPagerAdapter,实现两个方法:
getCount():返回页面数目
getItem(position):返回position位置的Fragment。
下面来看一个ViewPager与Fragment实现页面滑动效果的例子:
首先继承FragmentActivity,
为ViewPager提供展示所需的Fragment和FragmentPagerAdapter:
Fragment来指定页面的布局以及功能
// fragment private class MyFragment extends Fragment { private String text; private int color; public MyFragment(String text,int color) { this.text = text; this.color = color; } @Override public View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState) { TextView tv = new TextView(MainActivity.this); tv.setBackgroundColor(color); tv.setText(text); return tv; } }
adapter指定该Viewpager有多少页面以及那个位置需要显示哪个页面:
// adapter private class MyAdapter extends FragmentPagerAdapter { public MyAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return pages.size(); } @Override public Fragment getItem(int arg0) { return pages.get(arg0); } }
设置OnPagechangelistener,指定页面改变时需要做什么其他操作:
@Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0,float arg1,int arg2) { LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) tabline.getLayoutParams(); lp.leftMargin = (int) ((arg0 + arg1) * mTablinewidth); tabline.setLayoutParams(lp); } @Override public void onPageSelected(int arg0) { // set titles for (int i = 0; i < titles.size(); i++) { if (arg0 == i) { titles.get(i).setSelected(true); } else { titles.get(i).setSelected(false); } } }
完整的代码:
package com.hzy.myviewpager; import java.util.ArrayList; import android.graphics.Color; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPagechangelistener; import android.util.displayMetrics; import android.view.display; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.TextView; import com.hzy.myviewpager.R.id; public class MainActivity extends FragmentActivity implements OnPagechangelistener,OnClickListener { ViewPager pager = null; View tabline = null; private int mTablinewidth; // titles TextView title1 = null; TextView title2 = null; TextView title3 = null; ArrayList<TextView> titles = null; ArrayList<Fragment> pages = null; @Override protected void onCreate(Bundle arg0) { super.onCreate(arg0); initView(); initTabline(); } private void initView() { setContentView(R.layout.activity_main); pages = new ArrayList<Fragment>(); titles = new ArrayList<TextView>(); pager = (ViewPager) findViewById(id.main_viewpager); title1 = (TextView) findViewById(id.main_tab1); title2 = (TextView) findViewById(id.main_tab2); title3 = (TextView) findViewById(id.main_tab3); title1.setonClickListener(this); title2.setonClickListener(this); title3.setonClickListener(this); titles.add(title1); titles.add(title2); titles.add(title3); // create new fragments pages.add(new MyFragment("tab1",Color.BLUE)); pages.add(new MyFragment("tab2",Color.RED)); pages.add(new MyFragment("tab3",Color.CYAN)); // set adapter pager.setAdapter(new MyAdapter(getSupportFragmentManager())); pager.setonPagechangelistener(this); pager.setCurrentItem(0); titles.get(0).setSelected(true); } // tablines private void initTabline() { tabline = findViewById(id.main_tab_line); display display = getwindow().getwindowManager().getDefaultdisplay(); displayMetrics outMetrics = new displayMetrics(); display.getMetrics(outMetrics); mTablinewidth = outMetrics.widthPixels / 3; LayoutParams lp = tabline.getLayoutParams(); lp.width = mTablinewidth; tabline.setLayoutParams(lp); } @Override public void onClick(View v) { switch (v.getId()) { case id.main_tab1: pager.setCurrentItem(0,true); break; case id.main_tab2: pager.setCurrentItem(1,true); break; case id.main_tab3: pager.setCurrentItem(2,true); break; default: break; } } @Override public void onPageScrollStateChanged(int arg0) { } @Override public void onPageScrolled(int arg0,int arg2) { LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) tabline.getLayoutParams(); lp.leftMargin = (int) ((arg0 + arg1) * mTablinewidth); tabline.setLayoutParams(lp); } @Override public void onPageSelected(int arg0) { // set titles for (int i = 0; i < titles.size(); i++) { if (arg0 == i) { titles.get(i).setSelected(true); } else { titles.get(i).setSelected(false); } } } // fragment private class MyFragment extends Fragment { private String text; private int color; public MyFragment(String text,int color) { this.text = text; this.color = color; } @Override public View onCreateView(LayoutInflater inflater,@Nullable Bundle savedInstanceState) { TextView tv = new TextView(MainActivity.this); tv.setBackgroundColor(color); tv.setText(text); return tv; } } // adapter private class MyAdapter extends FragmentPagerAdapter { public MyAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return pages.size(); } @Override public Fragment getItem(int arg0) { return pages.get(arg0); } } }
代码中通过实现OnPagechangelistener接口手动设置了页面指示条的位置。
Android Fragment 和 FragmentManager 的代码分析
这两天在研究插件化编程,在使用 Fragment 碰到了一些问题,于是查看源码,顺便分析了一下 Fragment 和 FragmentManager 以及其他几个 API 的原代码,看看他们是怎么工作的。
我们知道 Fragment 有个 onCreateView() 方法,这个方法在 Fragment 创建 View 的时候被调用,并且返回一个 View 对象。那么 onCreateView 在什么时候被调用呢,咱们在 Fragment 这个类里找到了一个方法,performCreateView() 方法。
Fragment.java public View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container,@Nullable Bundle savedInstanceState) { return null; }
performCreateView 这个方法在什么时候会被调用呢,在 Fragment 里找不到调用它的代码。咱们可以猜测一下,大概会在 FragmentManager 里。
View performCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) { if (mChildFragmentManager != null) { mChildFragmentManager.noteStateNotSaved(); } return onCreateView(inflater,container,savedInstanceState); }
在 FragmentManager 里,咱们找到了调用 Fragment.performCreateView 的代码,在 movetoState() 方法里,这个方法有点大,我只粘贴了部分代码。可以看到,它会在 Fragment 初始化或者创建的时候被调用。并且我们知道,创建的View 被赋值给 Fragment 的 mView 成员变量了。
FragmentManager.java void movetoState(Fragment f,int newState,int transit,int transitionStyle,boolean keepActive) { switch (f.mState) { case Fragment.INITIALIZING: if (f.mFromLayout) { f.mView = f.performCreateView(f.getLayoutInflater( f.mSavedFragmentState),null,f.mSavedFragmentState); } break; case Fragment.CREATED: if (!f.mFromLayout) { f.mView = f.performCreateView(f.getLayoutInflater( f.mSavedFragmentState),f.mSavedFragmentState); } break; } }
接下来,咱们要看什么时候会调用 movetoState() 这个方法。找了一下,发现很 N 多的地方调用了这个方法。这样给咱们逆推找代码造成了一定的难度。于是咱们换个思路,正推来分析。怎么正推了,看咱们怎么使用 Fragment 和 FragmentManager 来分析。
一般咱们都是 getFragmentManager() 或者 getSupportFragmentManager() 的方法来获取 FragmentManager.以 FragmentActivity 为例,一般情况下,咱们在这个类的子类里调用这两个方法之一。
咱们在 FragmentActivity 里找到了相应的代码。FragmentManager 是一个抽象类,FragmentManagerImpl 是 FragmentManager 的子类,在 FragmentManager 同一个 java 文件内,是一个内部类。它是 FragmentManager 的实现。
FragmentActivity.java //FragmentManagerImpl is subclass of FragmentManager final FragmentManagerImpl mFragments = new FragmentManagerImpl(); public FragmentManager getSupportFragmentManager() { return mFragments; }
获取到 FragmentManager 后,咱们一般就会调用 beginTransaction() 方法,返回一个 FragmentTransaction 。咱们看代码去。
FragmentManager.java public abstract FragmentTransaction beginTransaction(); FragmentManagerImpl extends FragmentManager @Override public FragmentTransaction beginTransaction() { return new BackStackRecord(this); } /** * Static library support version of the framework's {@link android.app.FragmentTransaction}. * Used to write apps that run on platforms prior to Android 3.0. When running * on Android 3.0 or above,this implementation is still used; it does not try * to switch to the framework's implementation. See the framework SDK * documentation for a class overview. */ public abstract class FragmentTransaction
我们发现 FragmentManager 是一个抽象方法,实现在 FragmentManagerImpl。FragmentManagerImpl.beginTransaction() 返回的是一个BackStackRecord,而 FragmentTransaction 是一个抽象类。那么 BackStackRecord 是个什么鬼。
我们找到了 BackStackRecord 这个类。我们注意到,它继承于 FragmentTransaction,并且实现了 Runable 接口。它的方法有很多,咱们就分析一个咱们比较常用的,比如 add() 方法。
BackStackRecord.java final class BackStackRecord extends FragmentTransaction implements FragmentManager.BackStackEntry,Runnable final FragmentManagerImpl mManager; public BackStackRecord(FragmentManagerImpl manager) { mManager = manager; }
add() 方法其实没干啥,咱们一路追下去看。
public FragmentTransaction add(Fragment fragment,String tag) { doAddOp(0,fragment,tag,OP_ADD); return this; } private void doAddOp(int containerViewId,Fragment fragment,String tag,int opcmd) { fragment.mFragmentManager = mManager; if (tag != null) { if (fragment.mTag != null && !tag.equals(fragment.mTag)) { throw new IllegalStateException("Can't change tag of fragment " + fragment + ": was " + fragment.mTag + " Now " + tag); } fragment.mTag = tag; } if (containerViewId != 0) { if (fragment.mFragmentId != 0 && fragment.mFragmentId != containerViewId) { throw new IllegalStateException("Can't change container ID of fragment " + fragment + ": was " + fragment.mFragmentId + " Now " + containerViewId); } fragment.mContainerId = fragment.mFragmentId = containerViewId; } Op op = new Op(); op.cmd = opcmd; op.fragment = fragment; addOp(op); } void addOp(Op op) { if (mHead == null) { mHead = mTail = op; } else { op.prev = mTail; mTail.next = op; mTail = op; } op.enteranim = mEnteranim; op.exitAnim = mExitAnim; op.popEnteranim = mPopEnteranim; op.popExitAnim = mPopExitAnim; mNumOp++; }
一直追到 addOp() 就断了,好像啥事也没干。不过它大概是在一个 add 操作添加到一个链表上了。那咱们怎么办呢?一般咱们add 完后会 commit 一下,咱们看看 commit 都干了啥。
public int commit() { return commitInternal(false); } int commitInternal(boolean allowStateLoss) { if (mCommitted) throw new IllegalStateException("commit already called"); mCommitted = true; if (mAddToBackStack) { mIndex = mManager.allocBackStackIndex(this); } else { mIndex = -1; } mManager.enqueueAction(this,allowStateLoss); return mIndex; }
commit 好像也没干啥特殊的事情,不过可以看到这么一行代码 mManager.enqueueAction(this,allowStateLoss); 看 enqueueAction 这个方法名,应该会做点事情的。
同样,咱们在 FragmentManagerImpl 里找到了这个方法。
public void enqueueAction(Runnable action,boolean allowStateLoss) { if (!allowStateLoss) { checkStateLoss(); } synchronized (this) { if (mDestroyed || mActivity == null) { throw new IllegalStateException("Activity has been destroyed"); } if (mPendingActions == null) { mPendingActions = new ArrayList<Runnable>(); } mPendingActions.add(action); if (mPendingActions.size() == 1) { mActivity.mHandler.removeCallbacks(mExecCommit); mActivity.mHandler.post(mExecCommit); } } }
这个方法把咱们的 BackStackRecord -- 其实是 FragmentTransaction,也是 Runnable -- 添加到一个 mPendingActions 的 ArrayList 里了。然后调用 mActivity.mHandler.post(mExecCommit); mExecCommit 又是什么鬼?
Runnable mExecCommit = new Runnable() { @Override public void run() { execPendingActions(); } }; mActivity.mHandler.post(mExecCommit); 说明它在主线程里执行了 mExecCommit 的 run 方法。别问我咋知道的。 execPendingActions() 方法稍微比较大,我把注释写在代码里。 public boolean execPendingActions() { if (mExecutingActions) { throw new IllegalStateException("Recursive entry to executePendingTransactions"); } //如果不是在主线程,抛出一个异常。 if (Looper.myLooper() != mActivity.mHandler.getLooper()) { throw new IllegalStateException("Must be called from main thread of process"); } boolean didSomething = false; // 这里有一个 while true 循环。 while (true) { int numActions; // 这里在一个同步语句块里,把上次 mPendingActions 里的元素转移到 mTmpActions 数组里。并且执行 run方法。执行谁的 run 方法呢?!就是 BackStackRecord , 也就是 FragmentTransaction 。我在最后面贴了 BackStackRecord 的 run 方法。 synchronized (this) { if (mPendingActions == null || mPendingActions.size() == 0) { break; } numActions = mPendingActions.size(); if (mTmpActions == null || mTmpActions.length < numActions) { mTmpActions = new Runnable[numActions]; } mPendingActions.toArray(mTmpActions); mPendingActions.clear(); mActivity.mHandler.removeCallbacks(mExecCommit); } mExecutingActions = true; for (int i=0; i<numActions; i++) { mTmpActions[i].run(); mTmpActions[i] = null; } mExecutingActions = false; didSomething = true; } // 这里有好几行代码,不知道干啥的,反正就是做了一些判断,最后可能会调用 startPendingDeferredFragments() 方法。 if (mHavePendingDeferredStart) { boolean loadersRunning = false; for (int i=0; i<mActive.size(); i++) { Fragment f = mActive.get(i); if (f != null && f.mloaderManager != null) { loadersRunning |= f.mloaderManager.hasRunningLoaders(); } } if (!loadersRunning) { mHavePendingDeferredStart = false; startPendingDeferredFragments(); } } return didSomething; }
startPendingDeferredFragments 方法又是一坨不知道啥意思的代码。最后可能调用了 performPendingDeferredStart()
void startPendingDeferredFragments() { if (mActive == null) return; for (int i=0; i<mActive.size(); i++) { Fragment f = mActive.get(i); if (f != null) { performPendingDeferredStart(f); } } }
在 这个方法里,咱们看到了很熟悉的 movetoState() 方法。接着就是上面的分析,Fragment 的 onCreateView 会被调用。
public void performPendingDeferredStart(Fragment f) { if (f.mDeferStart) { if (mExecutingActions) { // Wait until we're done executing our pending transactions mHavePendingDeferredStart = true; return; } f.mDeferStart = false; movetoState(f,mCurState,false); } }
咱们在回来看 BackStackRecord 的 run 方法。这坨代码有点大,我还是写注释在代码里。
public void run() { if (FragmentManagerImpl.DEBUG) Log.v(TAG,"Run: " + this); if (mAddToBackStack) { if (mIndex < 0) { throw new IllegalStateException("addToBackStack() called after commit()"); } } bumpBackStacknesting(1); TransitionState state = null; SparseArray<Fragment> firstOutFragments = null; SparseArray<Fragment> lastInFragments = null; if (SUPPORTS_TRANSITIONS) { firstOutFragments = new SparseArray<Fragment>(); lastInFragments = new SparseArray<Fragment>(); calculateFragments(firstOutFragments,lastInFragments); state = beginTransition(firstOutFragments,lastInFragments,false); } int transitionStyle = state != null ? 0 : mTransitionStyle; int transition = state != null ? 0 : mTransition; // 注意这里要开始 while 循环了,要遍历刚才咱们说的链表了。 Op op = mHead; while (op != null) { int enteranim = state != null ? 0 : op.enteranim; int exitAnim = state != null ? 0 : op.exitAnim; switch (op.cmd) { // OP_ADD 很简单,mManager.addFragment(f,false); 其他的几个也类似,调用 mManager 相应的方法。 case OP_ADD: { Fragment f = op.fragment; f.mNextAnim = enteranim; mManager.addFragment(f,false); } break; case OP_REPLACE: { Fragment f = op.fragment; if (mManager.mAdded != null) { for (int i=0; i<mManager.mAdded.size(); i++) { Fragment old = mManager.mAdded.get(i); if (FragmentManagerImpl.DEBUG) Log.v(TAG,"OP_REPLACE: adding=" + f + " old=" + old); if (f == null || old.mContainerId == f.mContainerId) { if (old == f) { op.fragment = f = null; } else { if (op.removed == null) { op.removed = new ArrayList<Fragment>(); } op.removed.add(old); old.mNextAnim = exitAnim; if (mAddToBackStack) { old.mBackStacknesting += 1; if (FragmentManagerImpl.DEBUG) Log.v(TAG,"Bump nesting of " + old + " to " + old.mBackStacknesting); } mManager.removeFragment(old,transition,transitionStyle); } } } } if (f != null) { f.mNextAnim = enteranim; mManager.addFragment(f,false); } } break; case OP_REMOVE: { Fragment f = op.fragment; f.mNextAnim = exitAnim; mManager.removeFragment(f,transitionStyle); } break; case OP_HIDE: { Fragment f = op.fragment; f.mNextAnim = exitAnim; mManager.hideFragment(f,transitionStyle); } break; case OP_SHOW: { Fragment f = op.fragment; f.mNextAnim = enteranim; mManager.showFragment(f,transitionStyle); } break; case OP_DETACH: { Fragment f = op.fragment; f.mNextAnim = exitAnim; mManager.detachFragment(f,transitionStyle); } break; case OP_ATTACH: { Fragment f = op.fragment; f.mNextAnim = enteranim; mManager.attachFragment(f,transitionStyle); } break; default: { throw new IllegalArgumentException("UnkNown cmd: " + op.cmd); } } op = op.next; } // 最后还调用了movetoState() 这个方法。跟刚才的区别,看最后一个参数,一个true,一个false。 // 而且注意,这行代码在 while 循环之后。 mManager.movetoState(mManager.mCurState,transitionStyle,true); if (mAddToBackStack) { mManager.addBackStackState(this); } }
以上所述是小编给大家介绍的Android Fragment 和 FragmentManager 的代码分析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持!
android fragment 控件点击
在一个fragment中的控件无法点击是咋回事,事件监听也写了
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mlist" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/biz_pc_main_bg" android:gravity="center_horizontal" android:orientation="vertical" > <Button android:id="@+id/right_btn" android:clickable="true" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <LinearLayout android:id="@+id/rightLogin" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center|top" android:orientation="vertical" android:descendantFocusability="blocksDescendants" android:padding="5dip" > <ImageView android:id="@+id/user_login_header" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:adjustViewBounds="true" android:background="@drawable/main_info_login" android:contentDescription="@string/action_settings" android:cropToPadding="true" android:maxHeight="150dp" android:maxWidth="150dp" android:scaleType="fitXY" /> <TextView android:id="@+id/right_login_text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:gravity="center" android:text="@string/right_login" android:textColor="@color/white" android:textIsSelectable="false" android:textSize="18sp" /> </LinearLayout> <ListView android:id="@+id/right_list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@null" android:cacheColorHint="@color/color1" android:descendantFocusability="blocksDescendants" android:divider="@color/color2" android:dividerHeight="1dip" android:fadingEdge="none" /> </LinearLayout> fragment 代码public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.right, null); login = (LinearLayout)view.findViewById(R.id.rightLogin); btn = (Button)view.findViewById(R.id.right_btn); rightList = (ListView)view.findViewById(R.id.right_list); rightList.setItemsCanFocus(false); return view; } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); login.setOnClickListener(new RightClickListener()); btn.setOnClickListener(new RightClickListener()); list = new ArrayList<Map<String,Object>>(); itemText = getActivity().getResources().getStringArray(R.array.right); adapter = new RightAdapter(getActivity(), list); rightList.setAdapter(adapter); rightList.setOnItemClickListener(new RightClickListener()); setListViewHeightBasedOnChildren(rightList); } class RightClickListener implements OnClickListener,OnItemClickListener{ @Override public void onItemClick(AdapterView<?> parent, View v, int position, long a) { // TODO Auto-generated method stub Toast.makeText(getActivity(), itemText[position], Toast.LENGTH_SHORT).show(); Log.i("", itemText[position]); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()){ case R.id.rightLogin: intent = new Intent(getActivity(),LoginActivity.class); startActivity(intent); break; case R.id.right_btn: Log.i("btn", "button click success"); break; } } }
Android FragmentManage FragmentTransaction 介绍

FragmentManage:
FragmentManager 能够实现管理 activity 中 fragment. 通过调用 activity 的 getFragmentManager () 取得它的实例.
1、使用 findFragmentById () (用于在 activity layout 中提供一个 UI 的 fragment) 或 findFragmentByTag ()(适用于有或没有 UI 的 fragment) 获取 activity 中存在的 fragment2、将 fragment 从后台堆栈中弹出,使用 popBackStack () (模拟用户按下 BACK 命令).3、使用 addOnBackStackChangeListener () 注册一个监听后台堆栈变化的 listener.
FragmentTransaction:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Create new fragment and transaction Fragment newFragment = new ExampleFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); // Commit the transaction transaction.commit();
- 必须最后调用 commit ().
- 如果添加多个 fragment 到同一个容器,那么添加的顺序决定了它们在 view hierarchy 中显示的顺序.
* @author 张兴业
* 邮箱: xy-zhang#163.com
* android 开发进阶群: 278401545
*
*/
今天的关于Android fragment实现按钮点击事件的示例讲解和android点击事件的三种方式的分享已经结束,谢谢您的关注,如果想了解更多关于Android App在ViewPager中使用Fragment的实例讲解、Android Fragment 和 FragmentManager 的代码分析、android fragment 控件点击、Android FragmentManage FragmentTransaction 介绍的相关知识,请在本站进行查询。
本文标签: