Fragment进阶(四)----->參数传递3种写法
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>
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进阶(四)----->參数传递3种写法的更多相关文章
- FPGA编程基础(一)--參数传递与寄存器使用
一.參数映射 參数映射的功能就是实现參数化元件.所谓的"參数化元件"就是指元件的某些參数是可调的,通过调整这些參数从而可实现一类结构类似而功能不同的电路.在应用中.非常多电路都可採 ...
- java參数传递机制浅析
欢迎转载,转载请声明出处! ----------------------------------------- 前言: java语言中,參数的传递仅仅有一种机制.那就是值传递. 举例: 以下将通过几个 ...
- c++參数传递
定义: 形參:指出如今Sub 和Function过程形參表中的变量名.数组名,该过程在被调用前.没有为它们分配内存.其作用是说明自变量的类型和形态以及在过程中的作用.形參能够是除定长字符串变量之外的合 ...
- struts开发<struts中的參数传递.三>
不说废话,直接上干货 1.通过set和get传递參数 添加username 和password两个属性并添加set和get方法 package fzl.user.struts.demo; import ...
- activity之间參数传递&&获取activity返回值&&activity生命周期
Activity之间參数传递 A activity想将參数传给B activity时能够利用Intent将消息带过去 Intent intent = new Intent(this,BActivity ...
- 再次学习javascript中的參数传递
javascript中的全部函数的參数传递都是依照值传递的,做了以下測试: function addTen(num){ num +=10; return num; } var count = ...
- ionic新手教程第七课-简要说明几种界面之间的參数传递及优缺点
截至2016年4月13日19点32分,我公布的ionic新手教程,已经公布6课了, 总訪问量将近6000,平均每节课能有1000的訪问量.当中訪客最多的是第三课有2700的訪客. watermark/ ...
- 关于mybatis中,批量增删改查以及參数传递的问题
1.參数传递的问题 大多数情况下,我们都是利用map作为參数,而且大部分情况下都是仅仅有一个參数. 可是,我们也能够利用@param注解,来传入多个參数,此时,mybatis会自己主动将參数封装成ma ...
- Android开发之Fragment传递參数的几种方法
Fragment在Android3.0開始提供,而且在兼容包中也提供了Fragment特性的支持. Fragment的推出让我们编写和管理用户界面更快捷更方便了. 但当我们实例化自己定义Fragmen ...
随机推荐
- Maven密码加密
第1步执行shell: mvn --encrypt-master-password "SomeMadeUpMasterPassword" {nDpn1bE1vX4HABCDEFG ...
- Laravel5.1学习笔记12 系统架构4 服务容器
Service Container 介绍 绑定的用法 绑定实例到接口 上下文绑定 标签 解析 容器事件 #介绍 The Laravel service container is a powerful ...
- Python语言之变量1(数值,字符串,布尔)
1.数值 整数:2, -2 长整数:2**1024, 2**2048(真的可以很~长~~~,手残算了个2**100000,IDLE还真给打出来了,ORZ) 浮点数:7.05, 1E2(100.0), ...
- docloud后台管理项目(前端篇)
以下内容与主题无关,如果不想看可以直接忽视 !--忽视开始--! 给大家推荐一款强大的编辑器,那就是集响应快.体验好.逼格高.功能丰富为一体的sublime text 3.它除了以上特点,还有一个最重 ...
- STL_string用法总结
参考自:http://blog.csdn.net/y990041769/article/details/8763366 1:string对象的定义和初始化以及读写 string s1; 默认 ...
- 配置git使用ssh方式克隆gitlab的代码
配置ssh key https://www.cnblogs.com/hafiz/p/8146324.html 配置host https://www.cnblogs.com/kaerxifa/p/109 ...
- CF997A Convert to Ones
CF997A Convert to Ones 题目大意: 给你一个长度为 nn 的01串( n $\leq 3*10^5$ ),你有两种操作: 1.将一个子串翻转,花费 XX 2.将一个子串中的0变成 ...
- Unity jointmoto
jointmoto是模拟电机的,他的参数包括了最高车速和最大扭矩 扭矩总是正数,而目标车速决定了方向
- Whl自助搜索下载器
本文转载自以下链接:https://github.com/Light-City/AutoDownloadWhl 源码地址: https://github.com/Light-City/AutoDown ...
- Switch组件
Switch组件,业务需求中经常遇到.我司的旧项目中,由于没有使用较为成熟点的组件库.自己实现了一个switch组件,但是实现的略微有些丑陋. 实现基本需求 https://jsfiddle.net/ ...