watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

同一个Activity,不同container间的參数传递

第一:在Fragment中怎样获得自己控件的引用,比較这里Fragment1里的listview控件。

第二:在Fragment中怎样获得其他Fragment页面中控件的引用,比方这里Fragment2里的TextView控件。

直接在fragment中操作

activity_main.xml

<span style="color:#000000;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:baselineAligned="false" > <fragment
android:id="@+id/fragment1"
android:name="com.example.harvicblog5_2.Fragment1"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1" /> <fragment
android:id="@+id/fragment2"
android:name="com.example.harvicblog5_2.Fragment2"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout></span>

fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff00ff"
android:orientation="vertical" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is fragment 1"
android:textColor="#000000"
android:textSize="25sp" /> <ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</LinearLayout>

fragment2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00"
android:orientation="vertical" > <TextView
android:id="@+id/fragment2_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is fragment 2"
android:textColor="#000000"
android:textSize="25sp" /> </LinearLayout>

Fragment1

package com.example.harvicblog5_2;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView; public class Fragment1 extends Fragment {
private String[] mStrings = { "Abbaye de Belloc",
"Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu",
"Airag", "Airedale", "Aisy Cendre", "Allgauer Emmentaler",
"Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam",
"Abondance", "Ackawi", "Acorn", "Adelost", "Affidelice au Chablis",
"Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
"Allgauer Emmentaler" }; private TextView mFragment2_tv;
private ListView listView; @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
// listView = (ListView)
// rootView.findViewById(R.id.list);//获取自己视图里的控件引用,方法一
return rootView;
} @Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState); mFragment2_tv = (TextView) getActivity()
.findViewById(R.id.fragment2_tv);// 获取其他fragment中的控件引用的唯一方法!!!
listView = (ListView) getView().findViewById(R.id.list);// 获取自己视图里的控件引用,方法二 ArrayAdapter arrayAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mStrings);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String str = mStrings[position];
mFragment2_tv.setText(str);
}
});
}
}

Fragment2

package com.example.harvicblog5_2;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; public class Fragment2 extends Fragment { @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
} }

MainActivity

package com.example.harvicblog5_2;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity; public class MainActivity extends FragmentActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

*************************************************操作2****************************************************

方法二:在各自的fragment中操作

好。我们先想想要怎么解决问题。首先,我们把各自的事件放在各自的fragment中处理,即在fragment1中能得到当前用户点击的ITEM的String字符串,在fragment2中能够设置textview的值。

那问题来了。各自获得了各自的东东,那通过什么让他们交互呢?

答案显然是activity。

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:baselineAligned="false" > <fragment
android:id="@+id/fragment1"
android:name="com.example.harvicblog5_3.Fragment1"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1" /> <fragment
android:id="@+id/fragment2"
android:name="com.example.harvicblog5_3.Fragment2"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>

fragment1.xml

<?

xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff00ff"
android:orientation="vertical" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is fragment 1"
android:textColor="#000000"
android:textSize="25sp" /> <ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00"
android:orientation="vertical" > <TextView
android:id="@+id/fragment2_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is fragment 2"
android:textColor="#000000"
android:textSize="25sp" /> </LinearLayout>

Fragment1

package com.example.harvicblog5_3;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView; public class Fragment1 extends Fragment {
private String[] mStrings = { "Abbaye de Belloc",
"Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu",
"Airag", "Airedale", "Aisy Cendre", "Allgauer Emmentaler",
"Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam",
"Abondance", "Ackawi", "Acorn", "Adelost", "Affidelice au Chablis",
"Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
"Allgauer Emmentaler" }; private ListView listView; // 定义接口变量
private titleSelectInterface mSelectInterface; // Fragment间传递參数方法三,定义接口
public interface titleSelectInterface {
public void onTitleSelect(String title);
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment1, container, false);
} /**
* 将点击事件,写成一个接口,让外部去实现
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState); listView = (ListView) getView().findViewById(R.id.list);// 获取自己视图里的控件引用,方法二
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mStrings);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String str = mStrings[position];
mSelectInterface.onTitleSelect(str);
}
});
} /**
* (2)、接口变量赋值
* 接口是给activity用的。所以要在activity中给这里的接口变量赋值,能够有非常多方法,当然能够选择写一个setXXX(
* )函数来赋值,也能够要强制用户赋值。 所以採用强转的方式。在fragment与activity相关联时,进行强转赋值:
*/
// onAttach() 回调方法(当加入fragment到activity时由系统调用)
@Override
public void onAttach(Activity activity) {
super.onAttach(activity); try {
mSelectInterface = (titleSelectInterface) activity;
} catch (Exception e) {
throw new ClassCastException(activity.toString()
+ "must implement OnArticleSelectedListener");
}
}
}

Fragment2

package com.example.harvicblog5_3;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; public class Fragment2 extends Fragment {
private TextView mTv; @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment2, container, false);
} @Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mTv = (TextView) getView().findViewById(R.id.fragment2_tv);
} public void setText(String text) {
mTv.setText(text);
}
}

MainActivity

package com.example.harvicblog5_3;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager; public class MainActivity extends FragmentActivity implements Fragment1.titleSelectInterface { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
} @Override
public void onTitleSelect(String title) {
FragmentManager manager = getSupportFragmentManager();
Fragment2 fragment2 = (Fragment2)manager.findFragmentById(R.id.fragment2);
fragment2.setText(title);
}
}

***************************************方式3*********************************************************

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.harvic.fragmentarguments.MainActivity" > <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" /> </RelativeLayout>

fragment1.xml

<?xml version="1.0" encoding="utf-8"?

>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<ImageView
android:id="@+id/img_result"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="center"/> <Button
android:id="@+id/load_fragment2_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="载入第二个Fragment"/> </LinearLayout>

fragment2.xml

<?xml version="1.0" encoding="utf-8"?

>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"> <TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is fragment 2"
android:textColor="#000000"
android:textSize="25sp" /> <ImageView
android:id="@+id/img1"
android:layout_width="100dip"
android:layout_height="100dp"
android:scaleType="center"
android:src="@drawable/animal1"/> <ImageView
android:id="@+id/img2"
android:layout_width="100dip"
android:layout_height="100dp"
android:scaleType="center"
android:src="@drawable/animal2"/> <ImageView
android:id="@+id/img3"
android:layout_width="100dip"
android:layout_height="100dp"
android:scaleType="center"
android:src="@drawable/animal3"/> <ImageView
android:id="@+id/img4"
android:layout_width="100dip"
android:layout_height="100dp"
android:scaleType="center"
android:src="@drawable/animal4"/> </LinearLayout>

MainActivity

package com.harvic.fragmentarguments;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem; public class MainActivity extends Activity { /**
* 初始化显示fragmen1
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment1 fragment1 = new Fragment1();
getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();
}
}

Fragment1

package com.harvic.fragmentarguments;

import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView; public class Fragment1 extends Fragment { @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1, container, false);
Button btn = (Button) view.findViewById(R.id.load_fragment2_btn);
//button点击是生成fragment2页面,
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
//创建fragment2对象
Fragment2 fragment2 = Fragment2.newInstance("从Fragment1传来的參数"); //点击fragment2中不论什么一张图片进行的回调实现方法
fragment2
.setResultListener(new Fragment2.ICustomDialogEventListener() {
@Override
public void customDialogEvent(int selectID) {
//在fragment1中显示选中的图片就可以
ImageView imageView = (ImageView) getView()
.findViewById(R.id.img_result);
imageView.setImageResource(selectID);
}
});
//開始事物
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
//替换成fragment2布局视图控件
transaction.add(R.id.main_layout, fragment2);
//加入到回退栈
transaction.addToBackStack(null);
//提交事物就可以
transaction.commit();
}
});
return view;
}
}

Fragment2

package com.harvic.fragmentarguments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView; public class Fragment2 extends Fragment implements View.OnClickListener{
/**
* 回调结果值
* @param listener
*/
public interface ICustomDialogEventListener {
public void customDialogEvent(int selectID);
}
private ICustomDialogEventListener mCustomDialogEventListener;
public void setResultListener(ICustomDialogEventListener listener){
mCustomDialogEventListener = listener;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment2, container, false);
//获取携带过来的參数
if (getArguments() != null) {
String mParam1 = getArguments().getString("param");
TextView tv = (TextView)view.findViewById(R.id.textview);
tv.setText(mParam1);
}
view.findViewById(R.id.img1).setOnClickListener(this);
view.findViewById(R.id.img2).setOnClickListener(this);
view.findViewById(R.id.img3).setOnClickListener(this);
view.findViewById(R.id.img4).setOnClickListener(this);
return view;
} //生成fragment2的实例对象---接收传递过来的參数
public static Fragment2 newInstance(String text) {
Fragment2 fragment = new Fragment2();
Bundle args = new Bundle();
args.putString("param", text);
fragment.setArguments(args);
return fragment;
} @Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.img1:{
//imageview图片參数回传!! !!! !
mCustomDialogEventListener.customDialogEvent(R.drawable.animal1);
}
break;
case R.id.img2:{
mCustomDialogEventListener.customDialogEvent(R.drawable.animal2);
}
break;
case R.id.img3:{
mCustomDialogEventListener.customDialogEvent(R.drawable.animal3);
}
break;
case R.id.img4:{
mCustomDialogEventListener.customDialogEvent(R.drawable.animal4);
}
break;
}
//点击后,退出当前fragment
getFragmentManager().popBackStack();
}
}

Fragment进阶(四)-----&gt;參数传递3种写法的更多相关文章

  1. FPGA编程基础(一)--參数传递与寄存器使用

    一.參数映射 參数映射的功能就是实现參数化元件.所谓的"參数化元件"就是指元件的某些參数是可调的,通过调整这些參数从而可实现一类结构类似而功能不同的电路.在应用中.非常多电路都可採 ...

  2. java參数传递机制浅析

    欢迎转载,转载请声明出处! ----------------------------------------- 前言: java语言中,參数的传递仅仅有一种机制.那就是值传递. 举例: 以下将通过几个 ...

  3. c++參数传递

    定义: 形參:指出如今Sub 和Function过程形參表中的变量名.数组名,该过程在被调用前.没有为它们分配内存.其作用是说明自变量的类型和形态以及在过程中的作用.形參能够是除定长字符串变量之外的合 ...

  4. struts开发&lt;struts中的參数传递.三&gt;

    不说废话,直接上干货 1.通过set和get传递參数 添加username 和password两个属性并添加set和get方法 package fzl.user.struts.demo; import ...

  5. activity之间參数传递&amp;&amp;获取activity返回值&amp;&amp;activity生命周期

    Activity之间參数传递 A activity想将參数传给B activity时能够利用Intent将消息带过去 Intent intent = new Intent(this,BActivity ...

  6. 再次学习javascript中的參数传递

     javascript中的全部函数的參数传递都是依照值传递的,做了以下測试:    function addTen(num){ num +=10; return num; } var count = ...

  7. ionic新手教程第七课-简要说明几种界面之间的參数传递及优缺点

    截至2016年4月13日19点32分,我公布的ionic新手教程,已经公布6课了, 总訪问量将近6000,平均每节课能有1000的訪问量.当中訪客最多的是第三课有2700的訪客. watermark/ ...

  8. 关于mybatis中,批量增删改查以及參数传递的问题

    1.參数传递的问题 大多数情况下,我们都是利用map作为參数,而且大部分情况下都是仅仅有一个參数. 可是,我们也能够利用@param注解,来传入多个參数,此时,mybatis会自己主动将參数封装成ma ...

  9. Android开发之Fragment传递參数的几种方法

    Fragment在Android3.0開始提供,而且在兼容包中也提供了Fragment特性的支持. Fragment的推出让我们编写和管理用户界面更快捷更方便了. 但当我们实例化自己定义Fragmen ...

随机推荐

  1. UVM基础之----uvm_object

    uvm_void The uvm_void class is the base class for all UVM classes. uvm_object: The uvm_object class ...

  2. Hive扩展功能(三)--使用UDF函数将Hive中的数据插入MySQL中

    软件环境: linux系统: CentOS6.7 Hadoop版本: 2.6.5 zookeeper版本: 3.4.8 主机配置: 一共m1, m2, m3这五部机, 每部主机的用户名都为centos ...

  3. jQuery——多库共存

    多库共存:jQuery占用了$ 和jQuery这两个变量.当在同一个页面中引用了jQuery这个js库,并且引用的其他库(或者其他版本的jQuery库)中也用到了$或者jQuery这两个变量,那么,要 ...

  4. java攻城师之路--复习java web之Cookie_Session

    Servlet技术 用来动态生成 网页数据资源Servlet生成HTML 页面数据时,所有内容都是通过 response.getWriter response.getOutputStream 向浏览器 ...

  5. log4net 局部代码 看不懂....

    public interface ILogger {} public interface ILoggerWrapper { ILogger Logger {get;} } public interfa ...

  6. PHP 之CURL请求封装GET、POST、PUT、DELETE

    /** * @Description: curl请求 * @Author: Yang * @param $url * @param null $data * @param string $method ...

  7. Linux下/var/log/btmp文件

    今天查看了一下服务器,发现/var/log/btmp日志文件比较大占用磁盘空间,搜索一下,此文件是记录错误登录的日志,就是说有很多人试图使用密码字典登录ssh服务,此日志需要使用lastb程序打开. ...

  8. vivado2018.3 与 modelsim联合仿真

    我用的是目前最新版本的软件,vivado2018.3与modelsim10.6d.废话不多说,直接上操作 1.modelsim编译vivado库 1)双击启动vivado软件,如下图操作 2)Simu ...

  9. js 阻止冒泡事件和默认事件

    阻止事件冒泡 window.enent ? window.enent.cancelBubble = true : e.stopPropagation() function stopBubble(eve ...

  10. 关于MySQL中自增的理解和设置

    show create table t10;--查看表的创建结果 show create table t10\G;--竖列查看 --设置自增为20 ); insert into t2(name) va ...