Android开发,怎么在activity添加fragment中获取fragment中的imageview

本帖子已过去太久远了,不再提供回复功能。Android进阶之Fragment与Activity之间的数据交互 - CSDN博客
Android进阶之Fragment与Activity之间的数据交互
因为Fragment和Activity一样是具有生命周期,不是一般的bean通过构造函数传值,会造成异常。
2 参考链接
2 Activity把值传递给Fragment
2.1 第一种方式,也是最常用的方式,就是使用Bundle来传递参数
(1)宿主Activity/FragmentAdapter中:
Bundle bundle = new Bundle();
bundle.putString(Constant.INTENT_ID, productId);
Fragment fragment = null;
switch (position) {
fragment = new ProductImageDetailFragment();
fragment = new ProductParamFragment();
fragment = new ProductCommentFragment();
fragment.setArguments(bundle);
(2)Activity/FragmentAdapter中:
Fragment中的onCreatView/onStart()方法中,通过getArgments()方法,获取到bundle对象,然后通过getString的key值拿到我们传递过来的值。
public void onStart() {
super.onStart();
if (isAdded()) {
productId = getArguments().getString(Constant.INTENT_ID);
2.2 第二种方式,是在宿主Activity中定义方法,将要传递的值传递到Fragment中,在Fragment中的onAttach方法中,获取到这个值。
(1)宿主activity中的getTitles()方法
public String getTitles(){
return "hello";
(2)Fragment中的onAttach方法
public void onAttach(Activity activity) {
super.onAttach(activity);
titles = ((MainActivity) activity).getTitles();
2.3 第三种方式,是扩展一下创建Fragment和传递数值
(1)在宿主activity中,创建Fragment
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,android.R.anim.fade_out)
fragment1 = MyFragment.newInstance("这是第一个fragment")
fragment2 = MyFragment.newInstance("这是第二个fragment")
(2)Fragment中
static MyFragment newInstance(String s){
MyFragment myFragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("DATA",s);
myFragment.setArguments(bundle);
return myF
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle bundle = getArguments();
String data = bundle.getString("DATA");
3 Fragment把值传递给Activity
(1)在fragment中定义一个内部回调接口,再让包含该fragment的activity实现该回调接口,这样fragment即可调用该回调方法将数据传给activity。其实接口回调的原理都一样,以前的博客有讲到,接口回调是java不同对象之间数据交互的通用方法。
(2)activity实现完了接口怎么传给刚才的fragment呢?当fragment添加到activity中时,会调用fragment的方法onAttach(),这个方法中适合检查activity是否实现了OnArticleSelectedListener接口,检查方法就是对传入的activity的实例进行类型转换,然后赋值给我们在fragment中定义的接口。
(3)在一个fragment从activity中剥离的时候,就会调用onDetach方法,这个时候要把传递进来的activity对象释放掉,不然会影响activity的销毁,产生不必要的错误。注意看onAttach方法中的代码,在赋值之前要做一个判断,看看Activity中有没有实现了这个接口,用到了instanceof。如果没有实现接口,我们就抛出异常。
(1)在宿主activity中,创建Fragment
public class MainActivity extends Activity implements MenuFragment.FragmentInteraction{
private TextView textV
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.content_text);
public void process(String str) {
if (str != null) {
textView.setText(str);
(2)Fragment中
public class MenuFragment extends Fragment implements View.OnClickListener {
private FragmentIn
public interface FragmentInteraction {
void process(String str);
public void onAttach(Activity activity) {
super.onAttach(activity);
if(activity instanceof FragmentInteraction) {
listterner = (FragmentInteraction)
throw new IllegalArgumentException("activity must implements FragmentInteraction");
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu, container, false);
View btn = view.findViewById(R.id.tv_button);
View btn_m = view.findViewById(R.id.movie_button);
if (btn != null||btn_m!=null) {
btn.setOnClickListener(this);
btn_m.setOnClickListener(this);
public void onClick(View v) {
= v.getId();
switch (id) {
case R.id.tv_button:
listterner.process("我是电视剧");
case R.id.movie_button:
listterner.process("我是电影");
public void onDetach() {
super.onDetach();
listterner = null;
4 Fragment与Fragment之间的传值
在Activity中加载Fragment的时候、有时候要使用多个Fragment切换、并传值到另外一个Fragment、也就是说两个Fragment之间进行参数的传递,有两个方法。
4.1 通过共同的Activity传递(主要方法)
在Activity里面添加一个字段、来临时保存要一些值。在Activity中定义一个字段、然后添加set和get方法。
(1)在宿主activity中
public class DemoActivity {
private String mT
public String getmTitle() {
public void setmTitle(String title) {
this.mTitle =
(2)Fragment中
((DemoActivity)getActivity()).getmTitle();
4.1 通过Bundle来传递(本质还是Activity–&Fragment)
(1)在宿主activity中
ft.hide(getActivity().getSupportFragmentManager().findFragmentByTag(""))
DemoFragment demoFragment = new DemoFragment()
Bundle bundle = new Bundle()
bundle.putString("key", "这是方法二")
demoFragment.setArguments(bundle)
ft.add(R.id.fragmentRoot, demoFragment, SEARCHPROJECT)
ft.commit()
(2)Fragment中
String string = getArguments().getString("key");
本文已收录于以下专栏:
相关文章推荐
1、第一种方式,也是最常用的方式,就是使用Bundle来传递参数 MyFragment myFragment = new MyFragment();
Bundle bundle = n...
当Activity类动态加载fragment时可以通过fragment的setArguments()传入值,并在fragment类中通过fragment的getArguments()方法获得传入的值;...
在实际开发中经常会碰到需要在Fragment中获取到父Activity的控件进行操作。比如我这次碰到的。 在Fragment中点击按钮切换Fragment。Fragment切换最好是放在Activit...
首先我们需要在Activity中添加Fragment
转载请表明出处:http://blog.csdn.net/lmj/article/details/,本文出自:【张鸿洋的博客】1、概述最近大家面试说经常被问到Even...
笔者近期看官方training,发现了很多有用又好玩的知识。其中,fragment与Activity通信就是一个。
fragment与Activity通信主要是两点:
1、fragment传递信息给...
Android-ListView适配器BaseAdapter的使用
这是BaseAdapter的相应的方法属性。
像SimpleAdapter和ArrayAdapter都是继承于BaseAdapt...
他的最新文章
讲师:宋宝华
讲师:何宇健
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)2015年2月 移动开发大版内专家分月排行榜第二
2015年4月 移动开发大版内专家分月排行榜第三2015年1月 移动开发大版内专家分月排行榜第三
匿名用户不能发表回复!|
每天回帖即可获得10分可用分!小技巧:
你还可以输入10000个字符
(Ctrl+Enter)
请遵守CSDN,不得违反国家法律法规。
转载文章请注明出自“CSDN(www.csdn.net)”。如是商业用途请联系原作者。Android中保存和恢复Fragment状态的最好方法
英文原文:Probably be the best way (?) to save/restore
Fragment&s state so far
关键点:Fragment的Arguments。
经过这几年使用Fragment之后,我想说,Fragment的确是一种充满智慧的设计,但是使用Fragment时有太多需要我们逐一解决的问题,尤其是在处理数据保持的时候。
首先,虽然其有类似于activity的onSaveInstanceState,但是别想仅仅靠onSaveInstanceState就能保持数据。
下面就是一些案例:
情景一:stack中只有一个Fragment的时候旋转屏幕
是的,旋转屏幕是测试数据保持最简单的方法。这种情况非常简单,你只需在onSaveInstanceState存储会在旋转的时候会丢失的数据,包括变量,然后在onActivityCreated或者onViewStateRestored中取出来:
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(someVar, someVar);
outState.putString(&text&, tv1.getText().toString());
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
someVar = savedInstanceState.getInt(someVar, 0);
tv1.setText(savedInstanceState.getString(&text&));
看起来很简单是吧,但是存在这样的情况,View重建,但是onSaveInstanceState未被调用,这意味着UI上的所有东西都丢失了,请看下面的案例。
情景2:Fragment从回退栈的返回
当fragment从backstack中返回(这里是Fragment A),根据 官方文档 对Fragment生命周期的描述,Fragment A中的view会重建。
从这张图可以看到,当Fragment从回退栈中返回的时候,onDestroyView 和 onCreateView被调用,但是onSaveInstanceState貌似没有被调用,这就导致了一切UI数据都回到了xml布局中定义的初始状态。当然,那些内部实现了状态保存的view,比如有android:freezeText属性的EditText和TextView,仍然可以保持其状态,因为Fragment可以为他们保持数据,但是开发者没法获得这些事件,我们只能手动的在onDestroyView中保存这些数据。
大概流程如下:
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// 这里保存数据
public void onDestroyView() {
super.onDestroyView();
// 如果onSaveInstanceState没被调用,这里也可以保存数据
但是问题来了onSaveInstanceState中保存数据很简单,因为它有Bundle参数,但是onDestroyView没有,那保存在哪里呢?答案是能和Fragment一起共存的Argument。
代码大致如下:
Bundle savedS
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Restore State Here
if (!restoreStateFromArguments()) {
// First Time running, Initialize something here
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save State Here
saveStateToArguments();
public void onDestroyView() {
super.onDestroyView();
// Save State Here
saveStateToArguments();
private void saveStateToArguments() {
savedState = saveState();
if (savedState != null) {
Bundle b = getArguments();
b.putBundle(&internalSavedViewState7&, savedState);
private boolean restoreStateFromArguments() {
Bundle b = getArguments();
savedState = b.getBundle(&internalSavedViewState7&);
if (savedState != null) {
restoreState();
/////////////////////////////////
// 取出状态数据
/////////////////////////////////
private void restoreState() {
if (savedState != null) {
//tv1.setText(savedState.getString(&text&));
//////////////////////////////
// 保存状态数据
//////////////////////////////
private Bundle saveState() {
Bundle state = new Bundle();
//state.putString(&text&, tv1.getText().toString());
现在你可以轻松的在fragment的saveState和restoreState中分别存储和取出数据了。现在看起来好多了,几乎快要成功了,但是还有更极端的情况。
情景3:在回退栈中有一个以上的Fragment的时候旋转两次
当你旋转一次屏幕,onSaveInstanceState被调用,UI的状态会如预期的那样被保存,,但是当你再一次旋转屏幕,上面的代码就可能会崩溃。原因是虽然onSaveInstanceState被调用了,但是当你旋转屏幕,回退栈中Fragment的view将会销毁,同时在返回之前不会重建。这就导致了当你再一次旋转屏幕,没有可以保存数据的view。saveState()将会引用到一个不存在的view而导致空指针异常NullPointerException,因此需要先检查view是否存在。如果存在保存其状态数据,将Argument中的数据再次保存一遍,或者干脆啥也不做,因为第一次已经保存了。
private void saveStateToArguments() {
if (getView() != null)
savedState = saveState();
if (savedState != null) {
Bundle b = getArguments();
b.putBundle(&savedState&, savedState);
下面是我正在使用的fragment模版。
import android.os.B
import android.support.v4.app.F
import android.view.LayoutI
import android.view.V
import android.view.ViewG
import com.inthecheesefactory.thecheeselibrary.R;
* Created by nuuneoi on 11/16/2014.
public class StatedFragment extends Fragment {
Bundle savedS
public StatedFragment() {
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Restore State Here
if (!restoreStateFromArguments()) {
// First Time, Initialize something here
onFirstTimeLaunched();
protected void onFirstTimeLaunched() {
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save State Here
saveStateToArguments();
public void onDestroyView() {
super.onDestroyView();
// Save State Here
saveStateToArguments();
////////////////////
// Don't Touch !!
////////////////////
private void saveStateToArguments() {
if (getView() != null)
savedState = saveState();
if (savedState != null) {
Bundle b = getArguments();
b.putBundle(internalSavedViewState7, savedState);
////////////////////
// Don't Touch !!
////////////////////
private boolean restoreStateFromArguments() {
Bundle b = getArguments();
savedState = b.getBundle(internalSavedViewState7);
if (savedState != null) {
restoreState();
/////////////////////////////////
// Restore Instance State Here
/////////////////////////////////
private void restoreState() {
if (savedState != null) {
// For Example
//tv1.setText(savedState.getString(text));
onRestoreState(savedState);
protected void onRestoreState(Bundle savedInstanceState) {
//////////////////////////////
// Save Instance State Here
//////////////////////////////
private Bundle saveState() {
Bundle state = new Bundle();
// For Example
//state.putString(text, tv1.getText().toString());
onSaveState(state);
protected void onSaveState(Bundle outState) {
如果你使用这个模版,你只需继承StatedFragment类然后在onSaveState()保存数据,在onRestoreState()中取出数据,其余的事情上面的代码已经为你做好了,我相信覆盖了我所知道的所有情况。
现在本文描述的StatedFragment已经被做成了一个易于使用的库,并且发布到了jcenter,你现在只需在build.gradle中添加依赖就行了:
dependencies {
compile 'com.inthecheesefactory.thecheeselibrary:stated-fragment-support-v4:0.9.1'
继承StatedFragment,同时分别在onSaveState(Bundle outState)和onRestoreState(Bundle savedInstanceState)中保存和取出状态数据。如果你想在fragment第一次启动的时候做点什么,你也可以重写onFirstTimeLaunched(),它只会在第一次启动的时候被调用。
public class MainFragment extends StatedFragment {
* Save Fragment's State here
protected void onSaveState(Bundle outState) {
super.onSaveState(outState);
// For example:
//outState.putString(text, tvSample.getText().toString());
* Restore Fragment's State here
protected void onRestoreState(Bundle savedInstanceState) {
super.onRestoreState(savedInstanceState);
// For example:
//tvSample.setText(savedInstanceState.getString(text));本帖子已过去太久远了,不再提供回复功能。

我要回帖

更多关于 activity传值fragment 的文章

 

随机推荐