创建一个布局文件,里面的控件就是Fragment中的内容了。
<?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="#00ff00" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="this is a test" android:textColor="#000000" android:textSize="25sp" /> </LinearLayout>
然后写一个类继承自android.app.Fragment,这里顺便说一些它的生命周期。
import android.annotation.SuppressLint; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @SuppressLint("NewApi") public class Fragment1 extends Fragment { //一旦Fragment被创建,要创建它自己的用户界面时调用 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fra1, container, false); } //一旦父Activity和Fragment的UI已被创建则调用 @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } //调用该方法时Fragment会被连接到它的父Activity上 @Override public void onAttach(Activity activity) { super.onAttach(activity); } //调用该方法来进行Fragment的初始创建 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } //在整个生命周期结束时调用 @Override public void onDestroy() { super.onDestroy(); } //当Fragment的View被分离时调用 @Override public void onDestroyView() { super.onDestroyView(); } //当Fragment从它的父Activity上分离时调用 @Override public void onDetach() { super.onDetach(); } //在活动生命周期结束时被调用 @Override public void onPause() { super.onPause(); } //在活动生命周期开始时被调用 @Override public void onResume() { super.onResume(); } //活动生命周期结束时,调用该方法保存UI的状态变化 @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } //开始时被调用 @Override public void onStart() { super.onStart(); } //在可见生命周期结束时调用 @Override public void onStop() { super.onStop(); } }
在主布局文件中引用
<fragment android:id="@+id/menu_fragment" android:name="com.yc.fragmentdemo.MenuFragment" android:layout_width="fill_parent" android:layout_height="fill_parent" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/main_layout" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="false" > </LinearLayout>
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Display display=getWindowManager().getDefaultDisplay(); //获取屏幕的宽度和高度 if(display.getWidth()>display.getHeight()){ Fragment1 fragment1=new Fragment1(); getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit(); //开启事务加入Fragment并提交 }else{ Fragment2 fragment2=new Fragment2(); getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit(); } }
res/layout/activity_main
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <fragment android:id="@+id/menu_fragment" android:name="com.yc.fragmentdemo.MenuFragment" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" android:baselineAligned="false" tools:context=".MainActivity" > <fragment android:id="@+id/left_fragment" android:name="com.yc.fragmentdemo.MenuFragment" android:layout_width="0dip" android:layout_height="fill_parent" android:layout_weight="1"/> <FrameLayout android:id="@+id/details_layout" android:layout_width="0dip" android:layout_height="fill_parent" android:layout_weight="3" /> </LinearLayout>
而MenuFragment里面是一个ListView
import android.annotation.SuppressLint; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.os.Bundle; import android.util.Log; 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.AdapterView.OnItemClickListener; @SuppressLint("NewApi") public class MenuFragment extends Fragment implements OnItemClickListener { private ListView menuList; private ArrayAdapter<String> adapter; // 适配器 private String[] menuItems = { "sound", "Display" }; private boolean isTwoPane; // 是否是双页模式 // 当Activity和Fragment关联的时候,初始化适配器数据 @Override public void onAttach(Activity activity) { super.onAttach(activity); adapter = new ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, menuItems); Log.i("fragment", "attach"); } //加载menu_fragment文件,为ListViwe绑定了适配器,并设置监听事件 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.menu_fragment, container,false); menuList=(ListView) view.findViewById(R.id.menu_list); menuList.setAdapter(adapter); menuList.setOnItemClickListener(this); Log.i("fragment", "onCreateView"); return view; } /*当Activity创建完毕后,尝试获取一下布局文件中是否有details_layout这个元素, * 如果有说明当前是双页模式,反之则是单页 */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if((getActivity().findViewById(R.id.details_layout))!=null){ isTwoPane=true; }else{ isTwoPane=false; } Log.i("fragment", "onActivityCreated"); } /** * 处理ListViw点击事件,会根据当前是否是双页模式进行判断 * 如果是会动态添加Fragment,如果不是会打开新的Activity */ @Override public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3) { if(isTwoPane){ Fragment fragment=null; if(index == 0){ //点击第一个 fragment=new SoundFragment(); }else if(index==1){ //点击第二个 fragment=new DisplayFragment(); } getFragmentManager().beginTransaction().replace(R.id.details_layout, fragment).commit(); }else{ Intent intent=null; if(index==0){ intent=new Intent(getActivity(),SoundActivity.class); Log.i("fragment", "OnItemClick.intent"); }else{ intent=new Intent(getActivity(),DisplayActivity.class); } startActivity(intent); } } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <FrameLayout android:id="@+id/content" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" > </FrameLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="60dp" android:background="@drawable/tab_bg" > </LinearLayout> </LinearLayout>
<RelativeLayout android:id="@+id/message_layout" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" > <ImageView android:id="@+id/message_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/message_unselected" /> <TextView android:id="@+id/message_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="@string/message" android:textColor="#82858b" /> </LinearLayout> </RelativeLayout> <RelativeLayout android:id="@+id/contacts_layout" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" > <ImageView android:id="@+id/contacts_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/contacts_unselected" /> <TextView android:id="@+id/contacts_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="@string/contact" android:textColor="#82858b" /> </LinearLayout> </RelativeLayout> <RelativeLayout android:id="@+id/news_layout" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" > <ImageView android:id="@+id/news_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/news_unselected" /> <TextView android:id="@+id/news_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="@string/news" android:textColor="#82858b" /> </LinearLayout> </RelativeLayout> <RelativeLayout android:id="@+id/setting_layout" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" > <ImageView android:id="@+id/setting_image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:src="@drawable/setting_unselected" /> <TextView android:id="@+id/setting_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="@string/setting" android:textColor="#82858b" /> </LinearLayout> </RelativeLayout>
完成了UI设计,再写业务,根据点击事件来确定显示哪个Fragment
import com.yc.fragment.ContactsFragment; import com.yc.fragment.MessageFragment; import com.yc.fragment.NewsFragment; import com.yc.fragment.SettingFragment; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.ImageView; import android.widget.TextView; import android.annotation.SuppressLint; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.graphics.Color; @SuppressLint("NewApi") public class MainActivity extends Activity implements OnClickListener { private MessageFragment messageFragment; private ContactsFragment contactsFragment; private NewsFragment newsFragment; private SettingFragment settingFragment; private View messageLayout; private View contactsLayout; private View newsLayout; private View settingLayout; private ImageView messageImage; private ImageView contactsImage; private ImageView newsImage; private ImageView settingImage; private TextView messageText; private TextView contactsText; private TextView newsText; private TextView settingText; private FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); initViews(); fragmentManager = getFragmentManager(); setTabSelection(0); } /** * 初始化界面 */ private void initViews() { messageLayout = findViewById(R.id.message_layout); contactsLayout = findViewById(R.id.contacts_layout); newsLayout = findViewById(R.id.news_layout); settingLayout = findViewById(R.id.setting_layout); messageImage = (ImageView) findViewById(R.id.message_image); contactsImage = (ImageView) findViewById(R.id.contacts_image); newsImage = (ImageView) findViewById(R.id.news_image); settingImage = (ImageView) findViewById(R.id.setting_image); messageText = (TextView) findViewById(R.id.message_text); contactsText = (TextView) findViewById(R.id.contacts_text); newsText = (TextView) findViewById(R.id.news_text); settingText = (TextView) findViewById(R.id.setting_text); messageLayout.setOnClickListener(this); contactsLayout.setOnClickListener(this); newsLayout.setOnClickListener(this); settingLayout.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.message_layout: setTabSelection(0); break; case R.id.contacts_layout: setTabSelection(1); break; case R.id.news_layout: setTabSelection(2); break; case R.id.setting_layout: setTabSelection(3); break; } } private void setTabSelection(int index) { clearSelection(); // 清除上次选择的状态 FragmentTransaction transaction = fragmentManager.beginTransaction(); hideFragments(transaction); // 隐藏所有Fragment,防止多个Fragment出现的情况 switch (index) { case 0: messageImage.setImageResource(R.drawable.message_selected); messageText.setTextColor(Color.WHITE); if(messageFragment==null){ messageFragment=new MessageFragment(); transaction.add(R.id.content , messageFragment ); }else{ transaction.show(messageFragment); } break; case 1: contactsImage.setImageResource(R.drawable.contacts_selected); contactsText.setTextColor(Color.WHITE); if(contactsFragment==null){ contactsFragment=new ContactsFragment(); transaction.add(R.id.content , contactsFragment ); }else{ transaction.show(contactsFragment); } break; case 2: newsImage.setImageResource(R.drawable.news_selected); newsText.setTextColor(Color.WHITE); if(newsFragment==null){ newsFragment=new NewsFragment(); transaction.add(R.id.content , newsFragment ); }else{ transaction.show(newsFragment); } break; case 3: default: settingImage.setImageResource(R.drawable.setting_selected); settingText.setTextColor(Color.WHITE); if(settingFragment==null){ settingFragment=new SettingFragment(); transaction.add(R.id.content , settingFragment ); }else{ transaction.show(settingFragment); } break; } transaction.commit(); //一定要提交 } private void hideFragments(FragmentTransaction transaction) { if(messageFragment!=null){ transaction.hide(messageFragment); } if(contactsFragment!=null){ transaction.hide(contactsFragment); } if(newsFragment!=null){ transaction.hide(newsFragment); } if(settingFragment!=null){ transaction.hide(settingFragment); } } private void clearSelection() { messageImage.setImageResource(R.drawable.message_unselected); messageText.setTextColor(Color.parseColor("#82858b")); contactsImage.setImageResource(R.drawable.contacts_unselected); contactsText.setTextColor(Color.parseColor("#82858b")); newsImage.setImageResource(R.drawable.news_unselected); newsText.setTextColor(Color.parseColor("#82858b")); settingImage.setImageResource(R.drawable.setting_unselected); settingText.setTextColor(Color.parseColor("#82858b")); } }
这只是我的一个粗略总结,以后拿来用的,如果想要深入学习安卓,那么去找郭神吧! 下面有他博客的地址。真的很牛!!!
我是菜鸟,我在路上。