1. フラグメントの簡単な使用法
2 つのフラグメントをアクティビティに追加し、2 つのフラグメントでアクティビティ スペースを均等に分割します。
ステップ 1: まず、レイアウト内に left_fragment.xml を作成します。
<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 :
<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="文本"></TextView>
</LinearLayout>
ステップ 2: leftFragment.class クラスと rightFragment.class クラスを作成する
public class LeftFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
View view=inflater.inflate(R.layout.left_fragment,container,false);
return view;
}
}
と:
public class RightFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.left_fragment,container,false);
return view;
}
}
ステップ 3: mainActivity.xml ファイルを変更し、名前を指定してインポートします。
<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_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
/>
<fragment
android:id="@+id/right_fragment"
android:name="com.example.fragmenttest.RightFragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
/>
</LinearLayout>
実現するもの:
これは、フロントエンドのコンポーネントとあまり変わりません。
2 番目に、フラグメントを動的に追加します
1. 最初のステップ: 追加するフラグメント インスタンスの another_right_fragment.xml を作成します。
<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:text="另一个碎片"
android:textSize="20sp"/>
</LinearLayout>
2. 2 番目のステップ: mainActivity.xml を変更します。
FrameLayout レイアウトを LinearLayout レイアウトの下にネストします。
<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_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
/>
<FrameLayout
android:id="@+id/right_layout"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
/>
</LinearLayout>
3. mainActivity.classのメインアクティビティを変更します
つまり、デフォルトでは、フラグメントは最初に右側のフラグメントにレンダリングされ、次にボタンをクリックすることで FrameLayout コンテナ内のフラグメントが切り替わります。
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//右侧活动初始展示的碎片
replaceFragment(new RightFragment());
//点击左侧的按钮
Button button =(Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.button:
replaceFragment(new AnotherRightFragment());
break;
default:
break;
}
}
private void replaceFragment(Fragment fragment) {
//1,创建新的碎片实例new AnotherRightFragment()
//2,获取FragmentManager
FragmentManager fragmentManager =getSupportFragmentManager();
//3,通过beginTransaction()开启一个事务
FragmentTransaction transaction=fragmentManager.beginTransaction();
//4,向容器内添加事务,(容器的id,待添加的碎片实例)
transaction.replace(R.id.right_layout,fragment);
//提交事务才能完成
transaction.commit();
}
}
4. フラグメントでリターンスタックをシミュレートする
私が実現したい効果は、「戻る」ボタンをクリックすると、フラグメントが前のアクティブなスタックに直接戻るのではなく、戻ることができるということです。
MainActivity.class ファイルを変更します。
private void replaceFragment(Fragment fragment) {
//1,创建新的碎片实例new AnotherRightFragment()
//2,获取FragmentManager
FragmentManager fragmentManager =getSupportFragmentManager();
//3,通过beginTransaction()开启一个事务
FragmentTransaction transaction=fragmentManager.beginTransaction();
//4,向容器内添加事务,(容器的id,待添加的碎片实例)
transaction.replace(R.id.right_layout,fragment);
//将事务添加到返回栈中,一般传入null就行,这样碎片中的活动就会和已经加入返回栈中一样
transaction.addToBackStack(null);
//提交事务才能完成
transaction.commit();
}
このようにして、フラグメント内のアクティビティがすべてバックスタック上にあるかのようになります。
5. フラグメントとアクティビティ間のコミュニケーション
フラグメントはアクティビティ内にネストされていますが、実際にはそれほど密接な関係はありません。フラグメントとアクティビティが別のクラスに存在し、それらの間で直接通信する明白な方法がないことがわかります。
次に、アクティビティ内のフラグメント内のメソッドを今すぐ呼び出したい場合、またはフラグメント内のアクティビティのメソッドを呼び出したい場合です。それはどのように達成されるべきでしょうか?
FragmentManager は、レイアウト ファイルからフラグメント インスタンスを取得するために特別に使用される findViewById() に似たメソッドを提供します。コードは次のとおりです。
RightFragment rightFragment = (RightFragment) getFragmentManager().findFragmentById(R.id.right fragment);
FragmentManager の findFragmentById() メソッドを呼び出すと、アクティビティ内の対応するフラグメントのインスタンスを取得でき、フラグメント内のメソッドを簡単に呼び出すことができます。
フラグメント内のアクティビティのインスタンスを取得するにはどうすればよいですか?
MainActivity activity = (MainActivity) getActivity();
3、フラグメントのライフサイクル
4. レイアウトを動的にロードするためのテクニック
1. 修飾子を使用する
修飾子を使用すると、プログラムは現在のプログラムが実行されている環境を判断できるため、シングルページ モードまたはダブルページ モードを使用できます。
例: ただし、携帯電話で 1 ページを表示する必要があり、ワイドスクリーン タブレットで 2 ページのタイルを表示する必要がある場合は、次のようにすることができます。まず、通常のシングル ページ モードのレイアウトをlayout/
activity_main.xml に書き込みます。
次に、res:layout-large の下に新しいフォルダーを作成し、同じ名前で新しいファイル activity_main.xml を作成します。ライティングタブレットのデュアルスクリーンレイアウト。
プログラムの実行後、環境を判断し、タブレットの場合はレイアウト大でコードを読み取り、タブレットの場合はレイアウトでコードを読み取ります。
2. min-width 修飾子を使用する
メディアクエリを正確に制御したい場合。
res の下に新しいlayout-sw660dpフォルダーを作成し、同じ名前で新しい activity_main.xml ファイルを作成してレイアウトを書き込みます。このようにして、幅が 600dp を超えるデバイスでプログラムが実行されると、layout-sw600dp/activity_main レイアウトがロードされ、それ以外の場合は、デフォルトのlayout/activity_main レイアウトがロードされます。
五、フラグメントの最適な応用
このように機器ごとに一連のコードを記述すると作業量が膨大になり、その後のメンテナンスも困難になります。
ステップ 1: build.gradle に recycleview を導入する
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.1.0'
}
ステップ 2: ニュース エンティティ クラスを準備する News:
public class News {
public String title;
public 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 を作成する
<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>
ニュース内容のレイアウトは主に 2 つの部分に分かれており、見出しにはニュースのタイトルが表示され、本文にはニュースの内容が表示され、中央の細線で区切られています。
ステップ 4: 新しい NewsContentFragment クラスを作成します。
package com.example.fragmenttest;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
public class NewsContentFragment extends Fragment {
private View view;
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);//把visibilityLayout设置成可见
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() メソッドに読み込まれますが、これについては説明する必要はありません。次に、インターフェース上にニュースのタイトルと内容を表示するために使用される、refresh() メソッドが提供されます。ニュース タイトルとコンテンツのコントロールがそれぞれ findViewBvId) メソッドを通じて取得され、メソッドによって渡されるパラメーターが設定されていることがわかります。
このようにして、ニュースコンテンツのフラグメントクラスファイルとXMLレイアウトが作成されます。
ただし、これらはすべて見開きページ モードで使用されます。シングルページモードで使用したい場合。もう 1 つのアクティビティを作成する必要があります。
ステップ 5: 新しい NewsContentActivity ファイルを作成する
対応する news_content.xml ファイルが自動的に作成され、次のように変更されます。
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.example.fragmenttest.NewsContentFragment"/>
</LinearLayout>
ここでは、上で作成した NewsContentFragment クラスを直接導入します。これは、news_content_frag.xml レイアウト ファイルを導入するのと同じです。
次に、newsContentActivity のコードを変更します。
public class NewsContentActivity extends AppCompatActivity {
/**
* 构建Intent,传递所需数据
*/
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 = (NewsContentFragment) getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
//刷新NewsContentFragment 显示数据
newsContentFragment.refresh(newsTitle,newsContent);
}
}
onCreate() メソッドで、Intent を通じて受信ニュースのタイトルとコンテンツを取得します。
次に、FragmentManager の findFragmentById() メソッドを呼び出して NewsContentFragment のインスタンスを取得します。
次に、refresh() メソッドを呼び出し、ニュースのタイトルと内容を渡してデータを表示します。
ステップ 6: ニュース リストのレイアウト news_title_frag.xm を作成する
次に、次のように、ニュース リストを表示するレイアウト news_title_frag.xml を作成する必要があります。
<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>
ステップ 7: 上記の RecyclerView サブアイテムのレイアウトとして新しい 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:padding="10dp"/>
サブアイテムのレイアウトはTextViewの
ニュースリストのみで、サブアイテムのレイアウトを作成した後、ニュースリストを表示する場所が必要になるので、ニュースリストを
表示するためのフラグメントとしてNewsTitleFragmentを新規作成します。
/**
* 新闻列表fragment
*/
public class NewsTitleFragment extends Fragment{
private boolean isTowPane;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.news_content_frag, container, false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getActivity().findViewById(R.id.news_content_layout)!= null){
// 可以找到 news_content_layout 布局时,为双页模式
isTowPane = true;
}else {
// 找不到 news_content_layout 布局时,为单页模式
isTowPane = false;
}
}
}
前述の onActivityCreated() メソッドで次に現在の見開きモードか片ページモードかを判断するメソッドを実現するには、
以下のように NewsTitleFragemt に内部クラス NewsAdapter を RecyclerView のアダプターとして作成します。
public class NewsTitleFragment extends Fragment{
private boolean isTowPane;
. . .
/**
* RecyclerViews适配器
* */
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);
//每个Item的点击事件
final ViewHolder holder = new ViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
News news = mNewsList.get(holder.getAdapterPosition());
//如果是双页模式,则刷新NewsContentActivity中的数据
if (isTwoPane) {
NewsContentFragment newsContentFragment = (NewsContentFragment) getFragmentManager().findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(news.getTitle(), news.getContent());
} else {
//如果是单页模式,则直接启动NewsContentActivity
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();
}
}
ここでは、アダプターが NewsTitleFragment の変数に直接アクセスするための内部クラスとして記述されていることに注意してください。例
: isTowPane
には、最終作業の最後のステップがあり、RecyclerView に data を入力します
。NewsTitleFragment のコードを次のように変更します。以下に続きます:
public class NewsTitleFragment extends Fragment{
. . .
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.news_title_frag, container, false);
//RecyclerView实例
RecyclerView newsTitleRecyclerView = (RecyclerView) view.findViewById(R.id.news_title_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
newsTitleRecyclerView.setLayoutManager(layoutManager);//指定布局为线性布局
NewsAdapter adapter = new NewsAdapter(getNews());//把模拟新闻数据传入到NewsAdapter构造函数中
newsTitleRecyclerView.setAdapter(adapter);//完成适配器设置
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getActivity().findViewById(R.id.news_content_layout) != null) {
// 可以找到news_content_layout布局时,为双页模式
isTwoPane = true;
} else {
// 找不到news_content_layout布局时,为单页模式
isTwoPane = false;
}
}
/**
* 初始化50条模拟新闻数据
* @return
*/
private List<News> getNews() {
//创建集合
List<News> newsList = new ArrayList<>();
//实例化数据
for (int i = 1; i <= 50; i++) {
News news = new News();
news.setTitle("标题" + i);
news.setContent(getRandomLengthContent("东营职业学院电子信息与传媒学院" + i + ". "));
newsList.add(news);
}
return newsList;
}
/**
* 随机生成不同长度的新闻内容
* @param content
* @return
*/
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();
}
. . .
}
以下は見開きページ モードです。
まず、最初の数ページのコードの最初の数行を読んだ人は、画面が表示されたときに、res の下にある新しいlayout-sw600dp フォルダーがこのフォルダーの下のファイルを自動的に選択することを知っているはずです。解像度は 600 を超えています。フォルダーの下に新しい activity_main ファイルを作成します。
<?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.yiyajing.mypremission.fragment.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.yiyajing.mypremission.fragment.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
見開きモードでは 2 つのフラグメントを同時に導入し、ニュース コンテンツ フラグメントを FrameLayout レイアウトの下に配置し、このレイアウトの ID は news_content_layout であることがわかります。この ID が見つかると、このレイアウトが見つかります。それ以外の場合は、シングルページ モードです。ダブルページ モードの場合、システムは自動的にこのレイアウトを選択します。