很多時候我們希望我們的app能夠在手機/Pad上通用,但是Pad屏幕面積比較大,手機上可以一個屏幕都在展示一個項目,但是如果平板也這樣,可能就比較浪費,爲了應對這個問題,安卓有一個特別好用的東西,叫碎片Fragment。具體的可以看前面的博客。
1.修改build.gradle,添加依賴的類庫。
首先,創建一個安卓項目:SimpleNewsApp,因爲我們項目中使用到了RecyclerView,因此需要在app/build.gradle中添加依賴庫,如下圖所示:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:recyclerview-v7:25.3.1'
testCompile 'junit:junit:4.12'
}
其中,第7行就是我們需要添加的東西。
2.創建News類,新聞實體類
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;
}
}
這個就是一個普通實體類,沒什麼好說的。
3.新建佈局文件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="#000000" />
<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="#000000"
/>
</RelativeLayout>
這裏重要的是有兩個<TextView>,第一個id爲news_title,用來顯示新聞的標題,第二個id爲news_content,用來顯示新聞的內容。其中<View>標籤是用來分割標題與內容的,即中間的那條黑色的細線。設置width寬度爲1,背景顏色爲#000000黑色。
截至目前,我們已經有了一個展示新聞的佈局,以及一個新聞的實體。
4.新建一個NewsContentFrage類,繼承了Fragment(support.v4下面的)。
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);
}
這個碎片類的作用是,展示新聞的內容。
首先在onCreateView()方法加載了我們的news_content_frag佈局。下面的refresh()方法則是將新聞的標題內容顯示出來。
目前爲止,我們已經創建好了新聞內容的碎片與佈局。這個只是在雙頁模式下使用的,如果不知道什麼是雙頁模式,可以看我前一篇博客。接下來我們需要實現單頁模式下使用。單頁下,其實就是一個新的活動。
5.創建佈局命名爲news_content.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"
>
<fragment
android:id="@+id/news_content_fragment"
android:name="com.example.ustcg.simplenewsapp.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
我們在這裏重用了代碼,直接佈局中引入了NewsContentFragement,這樣就相當於把news_content_frage佈局的內容添加進來。代碼比較就簡單,我們繼續下面的。
6.創建佈局對應的活動,NewsContentActivity
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");
String newsContent = getIntent().getStringExtra("news_content");
NewsContentFragment newsContentFragment = (NewsContentFragment) getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(newsTitle, newsContent);
}
}
首先在onCreate()方法中,我們通過getIntent,然後在intent中獲取到傳入的新聞標題與內容。獲取之後,我們該怎麼展示呢?當然實在fragment,即碎片。怎麼做呢,首先我們獲取到目標碎片(fragment)的實例,getSupportFragmentManager().findFragmentById(R.id.news_content_fragment)即實現這個功能,然後調用碎片中的refresh方法,將標題與內容傳入,然後顯示出來。
actionStart方法的用途,類似實現一個intent,但是爲什麼不寫在源activity而是目標activity?原因比較簡單,如果寫在了目標的activity,源activity調用的時候,就需要傳入規定的參數。使用情景就是:假如兩個activity是兩個不同的人開發的,當一個人需要跳轉的另外一個人的activiy時,需要提供參數,但是怎麼知道需要提供哪些參數呢?如果不用這種方式,那麼這個人就需要去都目標activity的代碼,然後才能知道需要提供什麼數據。
7.創建一個顯示新聞列表的佈局,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">
<android.support.v7.widget.RecyclerView
android:id="@+id/news_title_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
代碼比較少,比較簡單,其實主要是用到了一個顯示新聞列表的RecyclerView標籤,具體的作用,可以百度。嘿嘿。用到了RecyclerView就要定義子項的佈局,接下來我們定義子項佈局。
8.子項佈局news_item.xml
<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"
/>
子佈局只有一個TextView,幾個關鍵的屬性介紹一下,android:singleLine="true"的含義是讓這個TextView只會單行顯示,android:ellipsize設置文本內容超出控件寬度之後文本的縮略方式,end表示尾部縮略。其他的都比較簡單,如果看不明白可以百度。
新聞列表以及子項的佈局都已經創建好了,接下來就需要找一個展示的地方了。
9.創建NewsTitleFragment作爲展示的的碎片
public class NewsTitleFragment extends Fragment {
private boolean isTwoPane;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.news_title_frag, container, false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getActivity().findViewById(R.id.news_content_layout) != null) {
isTwoPane = true;
} else {
isTwoPane = false;
}
}
}
代碼簡單,在onCreateView()方法中加載了news_title_frag佈局,在onActiivityCreated中主要是添加了一個標誌,判斷當前是雙頁模式還是單頁模式,即平板還是手機。怎
麼才能實現判斷的功能呢?這個比較簡單。
10.創建兩個activity_main.xml佈局
這兩個佈局文件不能放到一個地方,不然就重名報錯了。一個放在layout下面,作爲普通的佈局,即手機佈局。另一個需要放到一個新的文件夾layout-sw600dp下面,即
機器像素大於600dp使用的佈局,即平板佈局。系統會自動根據你的機器尺寸選擇合適的佈局。
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.ustcg.simplenewsapp.NewsTitleFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
單頁模式下,只加載NewsTitleFragment的碎片。layout-sw600dp文件夾下的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"
android:orientation="horizontal">
<fragment
android:id="@+id/news_title_fragment"
android:name="com.example.ustcg.simplenewsapp.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.ustcg.simplenewsapp.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
</LinearLayout>
這裏加載了兩個碎片,並把新聞內容碎片放在了一個FrameLayout佈局下面,佈局的id爲news_content_layout,如果能找到這個id,則證明爲雙頁模式,即平板。鬥則就是
手機。
至此我i們完成了大部分工作。接下來我們需要在NewsTitleFragment碎片中,通過RecyclerView將新聞咧白哦展示出來。這個比較複雜。
11.修改NewsTitleFragment
public class NewsTitleFragment extends Fragment {
private boolean isTwoPane;
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(NewsAdapter.ViewHolder holder, int position) {
News news = mNewsList.get(position);
holder.newsTitleText.setText(news.getTitle());
}
@Override
public int getItemCount() {
return mNewsList.size();
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable 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;
}
private List<News> getNews() {
List<News> newsList = new ArrayList<>();
for (int i = 0; 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();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getActivity().findViewById(R.id.news_content_layout) != null) {
isTwoPane = true;
} else {
isTwoPane = false;
}
}
}
原諒我比較懶,直接把這個類粘貼出來了。
首先最開始我們新建了一個內部類NewsAdapter作爲RecyclerView的適配器。很抱歉的是,我對於適配器的代碼也沒太搞明白,因此這裏就先不說了,直接跳過,後期在我
搞明白之後,我會再來編輯的。
其他的代碼就比較簡單了,就不解釋了。直接運行吧。
項目代碼我已經放到github上了,你們可以去download。簡單的新聞安卓app
有問題可以留言,大家一起探討吧,畢竟我現在還沒入門。