Fragment基本描述(四)

上一章讲到fragment的生命周期,这一章我们使用fragment完成一个新闻客户端。并使用一套代码适配手机和pad的UI。

先看一下效果图“

    

具体如何使用一套代码实现配置不同的UI呢?

新建一个News的对象:

public class News {
    private String title;
    private String content;

    public News(String title, String content) {
        this.title = title;
        this.content = 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;
    }
}

分别创建两个fragment,一个是NewsTitleFragment,另一个是NewsContentFragment。

先来说NewsContentFragment,这个简单些许

public class NewsContentFragment extends Fragment {
    private View view;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.news_content_frag, container, false);

        return view;

    }

    public void refresh(String newsTitle, String newsContent) {
        View visiblityLayout = view.findViewById(R.id.visiblity_layout);
        visiblityLayout.setVisibility(View.VISIBLE);
        TextView newsViewTitle = view.findViewById(R.id.news_title);
        TextView newsViewContent = view.findViewById(R.id.news_content);
        newsViewTitle.setText(newsTitle);
        newsViewContent.setText(newsContent);
    }
}

 

重写onCreateView方法,加载咱们的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/visiblity_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="invisible"
        android:orientation="vertical">

        <TextView
            android:id="@+id/news_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="10dp"
            android:text="454324555"
            android:layout_gravity="center"
            android:textColor="#000000"
            android:textSize="20sp" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#000000" />

        <TextView
            android:text="45646"
            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>

这个不多解释了。

其中refresh(String newsTitle, String newsContent)就是获取数据后更形UI的。

然后我们说NewsTitleFragment这个就比较复杂了,在原来的加载fragment的基础基础上多了一个新闻标题列表,这个列表我们使用的是recyclerview来实现的。具体如下:

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);

        RecyclerView newsTitleRecyclerView = view.findViewById(R.id.news_title_recycler_view);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        newsTitleRecyclerView.setLayoutManager(linearLayoutManager);
        NewsAdapter newsAdapter = new NewsAdapter(getNews());
        newsTitleRecyclerView.setAdapter(newsAdapter);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity().findViewById(R.id.news_content_layout) != null) {
            isTwoPane = true;
            NewsContentFragment newsContentFragment = (NewsContentFragment)
                    getFragmentManager().findFragmentById(R.id.news_content_fragment);
            newsContentFragment.refresh("这是标题:0", "这是内容:0");


        } else {
            isTwoPane = false;
        }
    }

    public List<News> getNews() {
        List<News> news = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            news.add(new News("这是标题:" + i, "这是内容:" + i));
        }
        return news;
    }


    class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {


        private List<News> mNewsList;

        public NewsAdapter(List<News> mNewsList) {
            this.mNewsList = mNewsList;
        }

        @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();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView newsTitleText;

            public ViewHolder(View itemView) {
                super(itemView);
                newsTitleText = itemView.findViewById(R.id.news_title);
            }
        }
    }
}

对应的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>

和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:ellipsize="end"
    android:paddingBottom="15dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="15dp"
    android:singleLine="true"
    android:textSize="18sp">

</TextView>

里面有用到NewsContentActivity,当是手机的时候就挑转到这个activity里面展示内容:

public class NewsContentActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_content);
        String news_title = getIntent().getStringExtra("news_title");
        String news_content = getIntent().getStringExtra("news_content");

        NewsContentFragment newsContentFragment = (NewsContentFragment) getSupportFragmentManager().
                findFragmentById(R.id.news_content_fragment);

        newsContentFragment.refresh(news_title, news_content);
    }

    public static void actionStart(Activity activity, String newsTitle, String newsContent) {
        Intent intent = new Intent(activity, NewsContentActivity.class);
        intent.putExtra("news_title", newsTitle);
        intent.putExtra("news_content", newsContent);
        activity.startActivity(intent);
    }
}

对应的activity_news_content   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"
    android:orientation="vertical">

    <fragment
        android:id="@+id/news_content_fragment"
        android:name="com.example.myfragment4.NewsContentFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

最后看:MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

对应的xml有连个一个是默认的activity_main:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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: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.myfragment4.NewsTitleFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

另一个是需要和在和layout同目录下新建一个layout-sw600dp目录,里面新建一个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:id="@+id/news_title_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <fragment
        android:id="@+id/news_title_fragment"
        android:name="com.example.myfragment4.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.myfragment4.NewsContentFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>

</LinearLayout>

 

转发表明出处https://blog.csdn.net/qq_35698774/article/details/106457599

点击下载源码

android互助群:

感谢:郭霖的《第一行代码 第二版》

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Android开发中,Fragment是一个可重用的UI部分,它可以独立于Activity存在,并且可以根据需要添加到不同的Activity中。Fragment有自己的生命周期管理,这包括一系列的方法,用于描述Fragment从创建、显示、活跃到销毁的整个过程。 1. **onCreate()**: 当Fragment实例被创建时调用,这是初始化阶段,可以在此设置基本属性和数据。 2. **onCreateView()**: 如果Fragment没有预先创建视图,这个方法会被调用来生成视图。返回null则会使用默认布局。 3. **onStart()**: 当Fragment成为活动焦点或可见时调用,可以在这里开始执行耗时操作。 4. **onResume()**: 当Fragment变为活动的前景或者用户正在交互时,这个方法会被调用,意味着它是完全活跃的。 5. **onPause()**: 当Fragment不再接收用户交互或成为活动焦点时,但依然可见时,这个方法会被调用。 6. **onStop()**: 当Fragment失去焦点并且不处于可见状态时,例如切换到其他Activity,这个方法会被调用。 7. **onDestroyView()**: 当Fragment的视图不再需要时,这个方法会被调用,通常在onPause之后。 8. **onSaveInstanceState()**: 在onPause或onStop之前调用,用于保存Fragment的状态,以便在恢复时使用。 9. **onDestroy()**: 当Fragment被系统卸载,不再需要内存时,这个方法会被调用。 10. **onActivityCreated()**: 当Fragment的视图已经创建完毕,并且所有的依赖项都可用时,这个方法会被调用。 11. **onDestroyView()**: 视图销毁后调用,释放资源。 12. **onDetach()**: 当Fragment从其宿主Activity中分离出来时,这个方法会被调用,通常发生在用户切换回其他Activity时。 理解Fragment的生命周期对于管理其行为、数据和资源至关重要。开发者可以根据这些阶段进行必要的资源管理、数据保存和状态更新。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大不懂

码字不易,一块也是爱,么么

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值