Fragment进阶(四)----->參数传递3种写法

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>

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*********************************************************

Fragment进阶(四)-----&gt;參数传递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();
}
}
上一篇:ionic新手教程第七课-简要说明几种界面之间的參数传递及优缺点


下一篇:equals和hashcode