核心基础以及Fragment与Activity传递数据完整示例

时间:2023-12-25 11:43:31

MainActivity如下:

package cc.testsimplefragment0;

import android.os.Bundle;
import android.app.Activity;
import android.app.FragmentTransaction;
import cc.testsimplefragment0.TitlesListFragment.TitlesListFragmentCallBack;
/**
* Demo描述:
* Fragment基本使用以及Fragment与Activity之间数据的传递
*
* 参考资料:
* Android疯狂讲义(第二版)
*
* 备注说明:
* 利用接口实现Fragment与Activity的信息传递.
* 这个思路是不错的.
* 在此总结一下Fragment与Activity之间交换数据的方式:
* 1 Activity向Fragment传递数据
* fragment.setArguments(bundle)
* 2 Fragment向Activity传递数据
* 在Fragment内部定义一个回调接口.让包含该Fragment的
* Activity实现该接口.这样Fragment就可调用该回调方法
* 将数据传给Activity
*
*/
public class MainActivity extends Activity implements TitlesListFragmentCallBack{ @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); } //实现TitlesListFragmentCallBack接口中的方法
@Override
public void onItemSelected(int index) {
DetailFragment detailFragment=new DetailFragment();
Bundle bundle=new Bundle();
bundle.putInt(Data.ID, index);
//向detailFragment传入参数
detailFragment.setArguments(bundle); //开始Fragment的事务Transaction
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
//替换容器(container)原来的Fragment
fragmentTransaction.replace(R.id.relativeLayoutContainer, detailFragment);
//设置转换效果
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//将事务添加到Back栈.即按下Back键时回到替换Fragment之前的状态.类似于Activity的返回
fragmentTransaction.addToBackStack(null);
//提交事务
fragmentTransaction.commit();
} }

TitlesListFragment如下:

package cc.testsimplefragment0;

import android.app.Activity;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* 备注说明:
* 因为是继承自ListFragment
* 所以不用覆写onCreateView()方法
*
*/
public class TitlesListFragment extends ListFragment {
private TitlesListFragmentCallBack mTitlesListFragmentCallBack;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置适配器
ArrayAdapter<String> arrayAdapter=
new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_checked, Data.TITLES);
setListAdapter(arrayAdapter); } //当该Fragment被添加,显示到Activity时调用该方法
//在此判断显示到的Activity是否已经实现了接口
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof TitlesListFragmentCallBack)) {
throw new IllegalStateException("TitlesListFragment所在的Activity必须实现TitlesListFragmentCallBack接口");
}
mTitlesListFragmentCallBack=(TitlesListFragmentCallBack) activity;
} //当该Fragment从它所属的Activity中被删除时调用该方法
@Override
public void onDetach() {
super.onDetach();
mTitlesListFragmentCallBack=null;
} //点击ListFragment中某个条目时调用该方法
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mTitlesListFragmentCallBack.onItemSelected(position);
//设置ListView为单选模式
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//显示选中的条目
getListView().setItemChecked(position, true);
} //定义一个业务接口
//该Fragment所在Activity需要实现该接口
//该Fragment将通过此接口与它所在的Activity交互
public interface TitlesListFragmentCallBack{
public void onItemSelected(int index);
} }

DetailFragment如下:

package cc.testsimplefragment0;

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 DetailFragment extends Fragment {
private int id=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(Data.ID)) {
id=getArguments().getInt(Data.ID);
}
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.detail_fragment, container, false);
TextView titleTextView=(TextView) view.findViewById(R.id.titleTextView);
titleTextView.setText(Data.TITLES[id]); TextView detailTextView=(TextView) view.findViewById(R.id.detailTextView);
detailTextView.setText(Data.DETAILS[id]); return view;
} }

Data如下:

package cc.testsimplefragment0;
public final class Data {
public static final String ID="id";
//标题
public static final String[] TITLES = { "标题1","标题2", "标题3","标题4"};
//内容
public static final String[] DETAILS = { "内容1","内容2", "内容3","内容4"};
}

main.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<!-- 定义一个水平排列的LinearLayout,并指定使用中等分隔条 -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:divider="?android:attr/dividerHorizontal"
android:showDividers="middle"> <!-- 添加一个Fragment -->
<fragment
android:id="@+id/titlesListFragment"
android:name="cc.testsimplefragment0.TitlesListFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" /> <!-- 添加一个RelativeLayout容器 -->
<RelativeLayout
android:id="@+id/relativeLayoutContainer"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" /> </LinearLayout>

detail_fragment.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:orientation="vertical" > <!-- 显示标题 -->
<TextView
android:id="@+id/titleTextView"
style="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp" /> <!-- 显示详细 -->
<TextView
android:id="@+id/detailTextView"
style="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp" /> </LinearLayout>

AndroidManifest.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cc.testsimplefragment0"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="14" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="cc.testsimplefragment0.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application> </manifest>