本系列學(xué)習(xí)筆記第4章
前言
打算把a(bǔ)ndroid基本知識(shí)點(diǎn)寫一個(gè)系列,旨在把a(bǔ)ndroid基礎(chǔ)書,例如《Android 第一行代碼 第2版》名斟、《愛上android》蒸眠、《瘋狂android講義》等書的一些知識(shí)點(diǎn)記錄一下楞卡,會(huì)持續(xù)更新內(nèi)容蒋腮,為了方便自己復(fù)習(xí),也希望可以幫助到大家作彤!
目錄
1竭讳、碎片是什么
2绢慢、碎片的使用方式
2.1 靜態(tài)添加碎片(布局文件中添加碎片)
2.2 動(dòng)態(tài)態(tài)添加碎片
2.2.1 案例一
2.2.2 案例二
2.3 在碎片中模擬返回棧
2.4 碎片和活動(dòng)之間進(jìn)行通信
2.5 片段管理的一些說明
3骚露、碎片的生命周期
3.1 碎片的狀態(tài)和回調(diào)
3.2 體驗(yàn)碎片的生命周期
4棘幸、動(dòng)態(tài)加載布局的技巧
4.1 使用限定符
4.2 使用最小寬度限定符
5、碎片的最佳實(shí)現(xiàn)---------一個(gè)簡(jiǎn)易版的新聞應(yīng)用
6、FragmentTabHost實(shí)現(xiàn)底部標(biāo)簽
1诞帐、碎片是什么
碎片(Fragment)是一種可以嵌入在活動(dòng)當(dāng)中的UI片段停蕉,它能讓程序更加合理和充分地利用大屏幕的空間,因而在平板上應(yīng)用得非常廣泛蚓挤。
2灿意、碎片的使用方式
2.1 靜態(tài)添加碎片(布局文件中添加碎片)
left_fragment.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Button"
/>
</LinearLayout>
right_fragment.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#00ff00"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="20sp"
android:text="This is right fragment"
/>
</LinearLayout>
LeftFragment.java文件
public class LeftFragment extends Fragment {
public static final String TAG = LeftFragment.class.getSimpleName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.left_fragment, container, false);
return view;
}
}
RightFragment.java文件
public class RightFragment extends Fragment {
public static final String TAG = RightFragment.class.getSimpleName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.right_fragment, container, false);
return view;
}
}
activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.fragmenttest.MainActivity">
<fragment
android:id="@+id/left_fragment"
android:name="com.example.fragmenttest.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<fragment
android:id="@+id/right_fragment"
android:name="com.example.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
效果圖如下:
2.2 動(dòng)態(tài)態(tài)添加碎片
2.2.1 案例一
在上一節(jié)的代碼基礎(chǔ)上修改荒辕,新建another_right_fragment.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#ffff00"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="20sp"
android:text="This is another right fragment"
/>
</LinearLayout>
AnotherRightFragment.java文件
public class AnotherRightFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.another_right_fragment, container, false);
return view;
}
}
activity_main.xml.文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.fragmenttest.MainActivity">
<fragment
android:id="@+id/left_fragment"
android:name="com.example.fragmenttest.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
<FrameLayout
android:id="@+id/right_layout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
/>
</LinearLayout>
MainActivity.java文件
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
replaceFragment(new RightFragment());
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
replaceFragment(new AnotherRightFragment());
break;
default:
break;
}
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.right_layout,fragment);
transaction.commit();
}
}
效果圖如下:
2.2.2 案例二
layout_left_fragment.xml文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent"
>
</android.support.constraint.ConstraintLayout>
layout_right_fragment.xml文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
>
</android.support.constraint.ConstraintLayout>
activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.fragmenttest2.MainActivity">
<FrameLayout
android:id="@+id/container_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
LeftFragment.java文件
public class LeftFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_left_fragment, null);
return view;
}
}
RightFragment.java 文件
public class RightFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_right_fragment, null);
return view;
}
}
MainActivity.java文件
public class MainActivity extends AppCompatActivity {
private LeftFragment leftFragment;
private RightFragment rightFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WindowManager windowManager = getWindowManager();
DisplayMetrics displayMetrics = new DisplayMetrics();
//測(cè)量屏幕的尺寸
windowManager.getDefaultDisplay().getMetrics(displayMetrics);
//測(cè)量屏幕寬高
int widthPixels = displayMetrics.widthPixels;
int heightPixels = displayMetrics.heightPixels;
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
if (widthPixels > heightPixels){
transaction.replace(R.id.container_content,getLeftFragment());
}else if (widthPixels < heightPixels){
transaction.replace(R.id.container_content, getRightFragment());
}
transaction.addToBackStack(null);
transaction.commit();
}
// 獲取左邊的Fragment
private LeftFragment getLeftFragment(){
if (leftFragment == null){
leftFragment = new LeftFragment();
}
return leftFragment;
}
// 獲取左邊的Fragment
private RightFragment getRightFragment(){
if (rightFragment == null){
rightFragment = new RightFragment();
}
return rightFragment;
}
}
2.3 在碎片中模擬返回棧
修改MainActivity.java文件
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
replaceFragment(new RightFragment());
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
replaceFragment(new AnotherRightFragment());
break;
default:
break;
}
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.right_layout,fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
效果圖如下:
2.4 碎片和活動(dòng)之間進(jìn)行通信
1)活動(dòng)中使用碎片的方法(獲得碎片的實(shí)例,就可以獲取碎片的方法)
LeftFragment leftFragment = (LeftFragment) getSupportFragmentManager().findFragmentById(R.id.left_fragment);
2)碎片中使用活動(dòng)的方法
MainActivity activity = (MainActivity) getActivity();
3)碎片與碎片之間的通信
基本思路如下:
在一個(gè)碎片中可以獲取得到與它相關(guān)聯(lián)的活動(dòng)厌衔,然后再通過這個(gè)活動(dòng)去獲取另外一個(gè)碎片的實(shí)例富寿,這樣也就實(shí)現(xiàn)了不同碎片之間的通信功能。
2.5 片段管理的一些說明
1)從Activity通過getSupportFragmentManager()方法(建議用這個(gè)兼容版本)或者getFragmentManager()方法獲取FragmentManager
2)通過fragmentManager.findFragmentById()方法(對(duì)于在Activity布局中提供UI片段)獲取Activity中存在的Fragment
3)通過fragmentManager.findFragmentByTag()方法(對(duì)于提供或不提供UI片段)獲取Activity中存在的Fragment
4) 通過fragmentManager.popBackStack()(模擬用戶按Back返回鍵)將片段從返回棧中彈出
5)通過fragmentManager.beginTransaction()開啟一個(gè)事務(wù)
6) 通過fragmentManager.addOnBackStackChangedListener()注冊(cè)一個(gè)監(jiān)聽返回棧的監(jiān)聽器
7)transaction.addToBackStack(null)添加返回棧
3变勇、碎片的生命周期
3.1 碎片的狀態(tài)和回調(diào)
1)運(yùn)行狀態(tài)
當(dāng)一個(gè)碎片是可見的搀绣,并且它所關(guān)聯(lián)的活動(dòng)正處于運(yùn)行狀態(tài)時(shí),該碎片也處于運(yùn)行狀態(tài)麻捻。
2)暫停狀態(tài)
當(dāng)一個(gè)活動(dòng)進(jìn)入暫停狀態(tài)時(shí)(由于另外一個(gè)未占滿屏幕的活動(dòng)被添加到了棧頂)芯肤,與它相關(guān)聯(lián)的可見碎片就會(huì)進(jìn)入暫停狀態(tài)
3)停止?fàn)顟B(tài)
當(dāng)一個(gè)活動(dòng)進(jìn)入停止?fàn)顟B(tài)時(shí)崖咨,與它相關(guān)聯(lián)的碎片就會(huì)進(jìn)入到停止?fàn)顟B(tài)击蹲,或者通過FragmentTransaction的remove()歌豺、replace()方法將碎片從活動(dòng)中移除馒铃,但是如果在事務(wù)提交之前調(diào)用addToBackStack()方法区宇,這時(shí)的碎片也會(huì)進(jìn)入到停止?fàn)顟B(tài)议谷∥韵總的來說逼裆,進(jìn)入停止?fàn)顟B(tài)的碎片對(duì)用戶來說是完全不可見的,也可能會(huì)被系統(tǒng)回收。
4)銷毀狀態(tài)
碎片總是依附于活動(dòng)而存在的然评,因此當(dāng)活動(dòng)被銷毀時(shí)碗淌,與它相關(guān)聯(lián)的碎片就會(huì)進(jìn)入到銷毀狀態(tài)亿眠。或者通過調(diào)用FragmentTransaction的remove()竟趾、replace()方法將碎片從活動(dòng)中移除岔帽,但是在事務(wù)提交之前并沒有調(diào)用addToBackStack()方法犀勒,這時(shí)的碎片也會(huì)進(jìn)入到銷毀狀態(tài)贾费。
3.2 體驗(yàn)碎片的生命周期
修改RightFragment,java文件
public class RightFragment extends Fragment {
public static final String TAG = RightFragment.class.getSimpleName();
@Override
public void onAttach(Context context) {
super.onAttach(context);
Log.d(TAG, "onAttach");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
View view = inflater.inflate(R.layout.right_fragment, container, false);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated");
}
@Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart");
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume");
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause");
}
@Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop");
}
@Override
public void onDestroyView() {
super.onDestroyView();
Log.d(TAG, "onDestroyView");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
}
@Override
public void onDetach() {
super.onDetach();
Log.d(TAG, "onDetach");
}
}
運(yùn)行上面的項(xiàng)目,觀察發(fā)現(xiàn)RightFragment 的生命周期如下:
點(diǎn)擊按鈕切換Fragment
如果在替換的時(shí)候沒有調(diào)用addToBackStack()方法,生命周期如下:
點(diǎn)擊返回按鈕,RightFragment 的生命周期如下:
4、動(dòng)態(tài)加載布局的技巧
4.1 使用限定符
layout/activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.fragmenttest.MainActivity">
<fragment
android:id="@+id/left_fragment"
android:name="com.example.fragmenttest.LeftFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
layout-large目錄下的activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/left_fragment"
android:name="com.example.fragmenttest.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/right_fragment"
android:name="com.example.fragmenttest.RightFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" />
</LinearLayout>
4.2 使用最小寬度限定符
最小寬度限定符允許我們對(duì)屏幕的寬度指定一個(gè)最小值(以dp為單位)九孩,然后以這個(gè)最小值為臨界點(diǎn)躺彬,屏幕寬度大于這個(gè)值的設(shè)備就加載一個(gè)布局宪拥,屏幕寬度小于這個(gè)值的設(shè)備就加載另一個(gè)布局
例如她君,res目錄下新建layout-sw6600dp的文件夾鳖枕,就是以屏幕寬度600dp為臨界點(diǎn)
5宾符、碎片的最佳實(shí)現(xiàn)---------一個(gè)簡(jiǎn)易版的新聞應(yīng)用
創(chuàng)建實(shí)體類News,java
···
public class News {
private String title;
private String content;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
···
列表item布局news_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/news_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="end"
android:textSize="18sp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
/>
news_content_frag.xml布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/visibility_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="invisible" >
<TextView
android:id="@+id/news_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:textSize="20sp" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000" />
<TextView
android:id="@+id/news_content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:padding="15dp"
android:textSize="18sp" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:background="#000" />
</RelativeLayout>
NewsContentFragment文件
public class NewsContentFragment extends Fragment {
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.news_content_frag, container, false);
return view;
}
public void refresh(String newsTitle, String newsContent) {
View visibilityLayout = view.findViewById(R.id.visibility_layout);
visibilityLayout.setVisibility(View.VISIBLE);
TextView newsTitleText = (TextView) view.findViewById (R.id.news_title);
TextView newsContentText = (TextView) view.findViewById(R.id.news_content);
newsTitleText.setText(newsTitle); // 刷新新聞的標(biāo)題
newsContentText.setText(newsContent); // 刷新新聞的內(nèi)容
}
}
NewsContentActivity.java文件
public class NewsContentActivity extends AppCompatActivity {
public static void actionStart(Context context, String newsTitle, String newsContent) {
Intent intent = new Intent(context, NewsContentActivity.class);
intent.putExtra("news_title", newsTitle);
intent.putExtra("news_content", newsContent);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_content);
String newsTitle = getIntent().getStringExtra("news_title"); // 獲取傳入的新聞標(biāo)題
String newsContent = getIntent().getStringExtra("news_content"); // 獲取傳入的新聞內(nèi)容
NewsContentFragment newsContentFragment = (NewsContentFragment) getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(newsTitle, newsContent); // 刷新NewsContentFragment界面
}
}
news_title_frag.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/news_title_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
NewsTitleFragment.java文件
public class NewsTitleFragment extends Fragment {
private boolean isTwoPane;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.news_title_frag, container, false);
RecyclerView newsTitleRecyclerView = (RecyclerView) view.findViewById(R.id.news_title_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
newsTitleRecyclerView.setLayoutManager(layoutManager);
NewsAdapter adapter = new NewsAdapter(getNews());
newsTitleRecyclerView.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getActivity().findViewById(R.id.news_content_layout) != null) {
isTwoPane = true; // 可以找到news_content_layout布局時(shí)稀蟋,為雙頁(yè)模式
News news = newsList.get(0);
NewsContentFragment newsContentFragment = (NewsContentFragment)
getFragmentManager().findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(news.getTitle(), news.getContent());
} else {
isTwoPane = false; // 找不到news_content_layout布局時(shí)退客,為單頁(yè)模式
}
}
private List<News> getNews() {
List<News> newsList = new ArrayList<>();
for (int i = 1; i <= 50; i++) {
News news = new News();
news.setTitle("This is news title " + i);
news.setContent(getRandomLengthContent("This is news content " + i + ". "));
newsList.add(news);
}
return newsList;
}
private String getRandomLengthContent(String content) {
Random random = new Random();
int length = random.nextInt(20) + 1;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length; i++) {
builder.append(content);
}
return builder.toString();
}
class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private List<News> mNewsList;
class ViewHolder extends RecyclerView.ViewHolder {
TextView newsTitleText;
public ViewHolder(View view) {
super(view);
newsTitleText = (TextView) view.findViewById(R.id.news_title);
}
}
public NewsAdapter(List<News> newsList) {
mNewsList = newsList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
News news = mNewsList.get(holder.getAdapterPosition());
if (isTwoPane) {
NewsContentFragment newsContentFragment = (NewsContentFragment)
getFragmentManager().findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(news.getTitle(), news.getContent());
} else {
NewsContentActivity.actionStart(getActivity(), news.getTitle(), news.getContent());
}
}
});
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
News news = mNewsList.get(position);
holder.newsTitleText.setText(news.getTitle());
}
@Override
public int getItemCount() {
return mNewsList.size();
}
}
}
layout目錄下的activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/news_title_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/news_title_fragment"
android:name="com.example.fragmenttest.NewsTitleFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
layout-sw600dp目錄下的activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/news_title_fragment"
android:name="com.example.fragmenttest.NewsTitleFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<FrameLayout
android:id="@+id/news_content_layout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3" >
<fragment
android:id="@+id/news_content_fragment"
android:name="com.example.fragmenttest.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
6、FragmentTabHost實(shí)現(xiàn)底部標(biāo)簽
準(zhǔn)備好圖片資源务傲,制作selector樣式
tab1.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/tab1_normal" android:state_selected="false"/>
<item android:drawable="@drawable/tab1_selected" android:state_selected="true"/>
</selector>
tab2.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/tab2_normal" android:state_selected="false"/>
<item android:drawable="@drawable/tab2_selected" android:state_selected="true"/>
</selector>
layout_left_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:background="@color/colorAccent"
>
</LinearLayout>
layout_right_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:background="@color/colorPrimaryDark"
>
</LinearLayout>
LeftFragment.java文件
public class LeftFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_left_fragment, null);
return view;
}
}
RightFragment.java文件
public class RightFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_right_fragment, null);
return view;
}
}
layout_indicator_view.xml文件
<?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="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_gravity="center"
android:id="@+id/iv_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@null"
tools:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/tv_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="標(biāo)簽"/>
</LinearLayout>
activity_fragment_tab_host.xml文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!--用來加載Fragment -->
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<!--分割線 用來分割Fragment和底部標(biāo)簽-->
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#d9d9d9"
android:orientation="vertical"/>
<!--標(biāo)簽組件-->
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_gravity="bottom" />
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
FragmentTabHostActivity.java文件
public class FragmentTabHostActivity extends AppCompatActivity {
private FragmentTabHost fragmentTabHost;
//標(biāo)簽的圖片
private int imageIds[] = {R.drawable.tab1, R.drawable.tab2,
};
//加載的Fragment
private Class<?> mFragmentClasses[] = {LeftFragment.class, RightFragment.class};
//標(biāo)簽文字
private String[] text=new String[]{"首頁(yè)","娛樂"};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_tab_host);
fragmentTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
//初始化
fragmentTabHost.setup(this,getSupportFragmentManager(),android.R.id.tabcontent);
//去掉分割線
fragmentTabHost.getTabWidget().setDividerDrawable(null);
//添加標(biāo)簽
for (int i = 0; i < imageIds.length; i++) {
//Tab按鈕添加文字和圖片
TabHost.TabSpec tabSpec = fragmentTabHost.newTabSpec(i + "").setIndicator(getIndicatorView(this, i));
//添加到fragment
fragmentTabHost.addTab(tabSpec,mFragmentClasses[i],null);
}
//切換標(biāo)簽時(shí)調(diào)用
fragmentTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String s) {
}
});
}
//獲取標(biāo)簽的View
private View getIndicatorView(Context context,int i){
View view = View.inflate(context,R.layout.layout_indicator_view, null);
ImageView imageView = (ImageView) view.findViewById(R.id.iv_tab);
TextView textView = (TextView) view.findViewById(R.id.tv_tab);
imageView.setImageResource(imageIds[i]);
textView.setText(text[i]);
return view;
}
}