这个demo是依照书上的内容,一步一步的编出来的。博文加上自己的理解,给自己疏通一下。最终效果如下:
1.效果图
运行在平板上
运行在手机上
demo会依据运行在平板上还是运行在手机上来选择不同的fragment,这就是动态加载的好处,我们无需开发平板和手机两个版本的app。下面附上源代码。
2.代码及理解
首先,我们需要哪些部分呢?第一,肯定要新闻类,用它来规范每一条新闻
News.java
package com.example.fragmentbestpractice;
/**
* 项目名称:FragmentBestPractice
* 类描述:
* 创建人:吴乐
* 创建时间:2016/3/29 15:29
* 修改人:吴乐
* 修改时间:2016/3/29 15:29
* 修改备注:
*/
public class News {
private String title;
private String content;
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
public void setContent(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
接着我们想到News要放在哪里,那肯定放在ListView中合适了,所以采用自定义Listview的方法来给出规范。
news_item.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:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/news_title"
android:singleLine="true"
android:ellipsize="end"
android:textSize="18sp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingBottom="15dp"
android:paddingTop="15dp"
/>
</LinearLayout>
NewsAdapter.java 作为新闻列表的适配器
package com.example.fragmentbestpractice;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* 项目名称:FragmentBestPractice
* 类描述:
* 创建人:吴乐
* 创建时间:2016/3/29 15:42
* 修改人:吴乐
* 修改时间:2016/3/29 15:42
* 修改备注:
*/
public class NewsAdapter extends ArrayAdapter<News>{
private int resourceId;
public NewsAdapter(Context context, int textViewResourceId, List<News> objects){
super(context,textViewResourceId,objects);
resourceId = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
News news = getItem(position);
View view;
//if是一个优化的方法
if (convertView == null){
view = LayoutInflater.from(getContext()).inflate(resourceId,null);
}else {
view = convertView;
}
TextView newsTitleText = (TextView)view.findViewById(R.id.news_title);
newsTitleText.setText(news.getTitle());
return view;
}
}
news_content_fragment.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" />
<ImageView
android:layout_width="match_parent"
android:layout_height="1dp"
android:scaleType="fitXY"
android:src="@drawable/split_line" />
<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>
<ImageView
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:scaleType="fitXY"
android:src="@drawable/line_vertical"/>
</RelativeLayout>
NewsContentFragment.java
package com.example.fragmentbestpractice;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* 项目名称:FragmentBestPractice
* 类描述:
* 创建人:吴乐
* 创建时间:2016/3/29 16:05
* 修改人:吴乐
* 修改时间:2016/3/29 16:05
* 修改备注:
*/
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);
newsContentText.setText(newsContent);
}
}
news_content.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">
<fragment
android:id="@+id/news_content_fragment"
android:name="com.example.fragmentbestpractice.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
这里直接将fragment放入xml中,减少了我们工作量,这就是fragment的好处之一。
NewsContentActivity.java
package com.example.fragmentbestpractice;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
/**
* 项目名称:FragmentBestPractice
* 类描述:
* 创建人:吴乐
* 创建时间:2016/3/29 17:02
* 修改人:吴乐
* 修改时间:2016/3/29 17:02
* 修改备注:
*/
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);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.news_content);
String newsTitle = getIntent().getStringExtra("news_title");
String newsContent = getIntent().getStringExtra("news_content");
NewsContentFragment newsContentFragment = (NewsContentFragment)getFragmentManager().findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(newsTitle,newsContent);
}
}
第一,该Activity是通过intent来启动的,我们通过获取intent隐含的数值更新新闻内容活动中的文本信息。
第二,我们要从Activity中调用Fragment的方法,就是获取实例加上调用。
这里的actionStart方法可以告诉别人我需要的是什么intent参数,你开启我这个获得也会很方便,利人利己,手留余香。这样基本完成的内容部分的工作,接下来要对新闻题目列表部分进行操作(关键所在)。
首先,这个列表应该完成几件事呢:
1,它应该是打开app就出现的,所以是第一个出现的
2,他决定了是对右侧fragment进行更新(平板模式),还是开启一个新的Activity来显示内容。
3,它有可能是一个单独的Activity显示,或者一个Activity中的一个小小的fragment,所以决定它是个fragment,这样只要根据情况选择加载哪一个就行了,是不是很方便。
news_title_frag.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">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/news_title_list_view">
</ListView>
</LinearLayout>
这个碎片中只有一个 listview,接下来是关键代码了:
NewsTitleFragment.java
package com.example.fragmentbestpractice;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* 项目名称:FragmentBestPractice
* 类描述:
* 创建人:吴乐
* 创建时间:2016/3/29 16:33
* 修改人:吴乐
* 修改时间:2016/3/29 16:33
* 修改备注:
*/
public class NewsTitleFragment extends Fragment implements AdapterView.OnItemClickListener {
private static final String TAG = "FragmentTest";
private ListView newsTitleListView;
private List<News> newsList;
private NewsAdapter adapter;
private boolean isTwoPane;
/*
* onAttach(Context) is not called on pre API 23 versions of Android and onAttach(Activity) is deprecated
* Use onAttachToContext instead
*/
@TargetApi(23)
@Override
public void onAttach(Context context) {
super.onAttach(context);
onAttachToContext(context);
}
/*
* Deprecated on API 23
* Use onAttachToContext instead
*/
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
onAttachToContext(activity);
}
}
/*
* Called when the fragment attaches to the context
*/
protected void onAttachToContext(Context context) {
newsList = getNews();
adapter = new NewsAdapter(getActivity(), R.layout.news_item, newsList);
Log.d(TAG, "onAttach: 此处被调用");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.news_title_flag,container,false);
newsTitleListView = (ListView)view.findViewById(R.id.news_title_list_view);
newsTitleListView.setAdapter(adapter);
newsTitleListView.setOnItemClickListener(this);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if ((getActivity().findViewById(R.id.news_content_layout))!= null){
isTwoPane = true;
}else {
isTwoPane = false;
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
News news = newsList.get(position);
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());
}
}
private List<News> getNews() {
List<News> newsList = new ArrayList<>();
News news1 = new News();
news1.setTitle("Aldridge has 31 points, 13 boards, Spurs beat Memphis 101-87");
news1.setContent("MEMPHIS, TN - MARCH 28: LaMarcus Aldridge #12 of the San Antonio " +
"Spurs shakes hands with his teammates during the game against the Memphis " +
"Grizzlies on March 28, 2016 at FedExForum in Memphis, Tennessee. (Photo by " +
"Joe Murphy/NBAE via Getty Images)");
newsList.add(news1);
News news2 = new News();
news2.setTitle("Jazz knock it out of the park with this tribute to Kobe Bryant");
news2.setContent("The Jazz did a great job saying goodbye to the Black Mamba on Monday.\n" +
" Grey Papke / Larry Brown Sports / Yardbarker");
newsList.add(news2);
return newsList;
}
}
2、其次在onCreateView中加载了布局以及设置了点击事件;
3、在onActivityCreate中获取这是动态加载了哪个模式(双页模式还是单页模式),这里依据news_content_layout(该layout定义在大屏幕时才会加载,见下文)是否出现来
判别。
4、在点击事件中,我们根据不同的模式进行不同的更新操作。
剩下的工作就是MainActivity了,它会根据屏幕大小加载不同的Fragment,这是怎么做到的呢?
首先,修改activity_main.xml
activity_main.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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.fragmentbestpractice.MainActivity">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.example.fragmentbestpractice.NewsTitleFragment"
android:id="@+id/news_title_fragment"/>
</LinearLayout>
齐次在res中创建一个 layout_large文件夹,并且在里面创建另一个activity_main.xml
activity_main.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">
<fragment
android:id="@+id/news_title_fragment"
android:name="com.example.fragmentbestpractice.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.fragmentbestpractice.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
当屏幕大时,会调用layout_large中的xml,当屏幕小时,会调用layout中的xml,这都是系统完成的,我们要做的只是写出large这个限定符。可以看见layout_large中有一个news_content_layout这个view,如果加载了这个,那么在NewsTitleFragment中就会判断出是双页模式了,一切都联系上了!
最后一步是MainActivity
MainActivit.jva
package com.example.fragmentbestpractice;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
/**
*
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
这样整个小demo就完成了
ps:去除title以及全屏工作,我在去除title中遇到了一点小问题,发现
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
并没有起到该有的作用,我怀疑和theme主题有关。app中的每个Activity都继承了 AppCompatActivity,而不是传统的Activity,所以对界面会更加严谨。最终我在
values/styles中进行了去title操作,很顺利的去除了title。有知道的人谢谢告诉我。
styles.xml
这个小实验的学习,初步认识了Fragment,梳理一下,有问题会继续补充。Fighting,Fighting,Fighting!!!
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="windowNoTitle">true</item>
<item name="windowActionBar">true</item>
<item name="android:windowFullscreen">false</item>
<item name="android:windowContentOverlay">@null</item>
</style>
</resources>