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. C#模拟百度登录并到指定网站评论回帖(一)

    核心信息: 请求网址:  https://passport.baidu.com/v2/api/?login请求方法:  POST状态码:  HTTP/1.1 200 OK请求头  //用户代理 Use ...

  2. bootstrap图标乱码问题-解决方案

    楼主在使用bootstrap时,出现了图标乱码问题,经过多次查找,才解决了问题(最后发现真的是很好解决的问题(^^)) 如果出现乱码 请直接在自己写的CSS中重新引入一下font文件中的字体就好了 @ ...

  3. [转][IPC通信]基于管道的popen和pclose函数

    标准I/O函数库提供了popen函数,它启动另外一个进程去执行一个shell命令行. 这里我们称调用popen的进程为父进程,由popen启动的进程称为子进程. popen函数还创建一个管道用于父子进 ...

  4. js技巧(二)

    1.封装获取id: function show(Id){ var aa=document.getElementById(Id); return aa; } 调用:console.log(show(&q ...

  5. html5——全屏显示

    基本概念 1.HTML5规范允许用户自定义网页上任一元素全屏显示 2.requestFullscreen() 开启全屏显示.cancleFullscreen() 关闭全屏显示 3.不同浏览器兼容性不一 ...

  6. html——特殊字符

  7. Gradle与Makefile构建工具的对比

    随着Android Studio的普及,越来越多的Android开发者也要开始了解和学习Gradle这款强大的代码构建工具了.我们在学习和了解一项新事物的时候,最快速的方法往往是与已知的事物进行比较, ...

  8. C# SqlParameter 使用

    //System.Data.SqlClient.SqlParameter[] sqlParameters = new System.Data.SqlClient.SqlParameter[]{ };  ...

  9. 关于JS闭包的一点理解

    通常来讲,闭包通常是指函数内部可以访问到外部作用域的一个过程. 一.广义的定义:任何函数都产生了闭包. 二.狭义的定义:函数内部能访问到其他变量函数的作用域. 我们来看个例子 var a = 10; ...

  10. time模块和datatime模块

    一.time模块 time.time() 获取时间戳 time.sleep() 睡几秒 time.gmtime() utc时间元组 time.localtime() 本地时间元组 time.mktim ...