<第二行代码>中的新闻应用

这个应用分五个部分

1.News类

2.内容碎片及布局

3.内容活动及布局

4.标题碎片及布局

5.主活动及布局

 

由于会用到recyclerview,所以先添加依赖库

compile 'com.android.support:recyclerview-v7:24.2.1'

 

 

1.News类

是新闻实体类,封装了标题和内容

package com.scx040407.fragmentbestpractice2;

/**
 * Created by Administrator on 2017/4/9 0009.
 */

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

 

2.内容碎片及布局

package com.scx040407.fragmentbestpractice2;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


/**
 * Created by Administrator on 2017/4/9 0009.
 */

public class NewsContentFragment extends Fragment {
    @Nullable
    @Override//onCreateView表示为碎片创建视图
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.news_content_frag,container,false);
        return view;
    }
    //刷新方法   为什么要有刷新方法?因为在平板中,点击了新闻标题,在新闻内容出要相应的出现新闻内容,所以要有刷新方法随时来响应标题的变化。在没有点击的时候不显示内容。
    public void refresh(String newsTitle,String newsContent){
        View visibilityLayout= getView().findViewById(R.id.visibility_layout);
       //将属性改为可见
        visibilityLayout.setVisibility(View.VISIBLE);
        TextView newsTitleText= (TextView) getView().findViewById(R.id.news_title);
        TextView newsContentText= (TextView) getView().findViewById(R.id.news_content);
        newsTitleText.setText(newsTitle);
        newsContentText.setText(newsContent);
    }
}

 

<?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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="invisible"//设置了不可见的属性
        android:id="@+id/visibility_layout">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/news_title"
            android:gravity="center"
            android:padding="10dp"
            android:textSize="20sp"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp" //横线
            android:background="#000"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:id="@+id/news_content"
            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"/>

</RelativeLayout>

 

3.内容活动及布局

这个活动是给手机用的,手机由于屏幕的原因标题和内容要分开展示,所以需要两个活动,点击标题会跳转到内容活动中去。所以我们创建内容活动,布局直接引用内容碎片。

package com.scx040407.fragmentbestpractice2;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

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

 

 

<?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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.scx040407.fragmentbestpractice2.NewsContentFragment"/>

</LinearLayout>

 

4.标题碎片及布局

package com.scx040407.fragmentbestpractice2;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Administrator on 2017/4/9 0009.
 */

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设置layoutmanager和adapter
        RecyclerView newsTitleRecyclerView= (RecyclerView) view.findViewById(R.id.news_title_recycler_view);
        LinearLayoutManager layoutManager=new LinearLayoutManager(getActivity());
        newsTitleRecyclerView.setLayoutManager(layoutManager);
       //参数是News类的集合,List<News>
        NewsAdapter adapter=new NewsAdapter(getNews());
        newsTitleRecyclerView.setAdapter(adapter);
        return view;
    }

    //生成新闻标题和内容的方法
    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 s) {
        Random random=new Random();
        int length=random.nextInt(20)+1;
        StringBuilder builder=new StringBuilder();
        for(int i=0;i<length;i++){
            builder.append(s);
        }
        return builder.toString();
    }

    @Override//确保与碎片相关联的活动一定已经创建完毕时调用
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
       //判断是平板还是手机,在当前活动中找内容布局id,如果是平板的话就为true否则false。布局id请参考主活动及布局。
if(getActivity().findViewById(R.id.news_content_layout)!=null){
            isTwoPane=true;//平板
        }else {
            isTwoPane=false;//手机
        }
    }

//适配器,继承了recyclerview的Adapter类,泛型是内部类ViewHolder继承了recyclerview的ViewHolder类。
    class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder>{

        List<News> mNewsList;//所有的消息类的集合

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView textView;
            public ViewHolder(View itemView) {
                super(itemView);
       //拿到子项布局中需要改变显示内容的控件
                textView= (TextView) itemView.findViewById(R.id.news_item);  
            }
        }
       //构造方法,参数是所有消息类的集合,用我们定义的集合来接收。
        public NewsAdapter(List<News> newsList){
            mNewsList=newsList;
        }

        @Override//必须重写的方法之一
        public NewsAdapter.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);
//给视图添加点击监听,目的是将News类传到内容碎片中去展示。
//这里有个问题,为什么不把监听放到onBindViewHolder中去呢?
//那样的话News类更方便获取。
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//holder.getAdapterPosition获取索引。
//mNewsList .get(int position)意思是获取指定索引的内容,即News类。
                    News news=mNewsList.get(holder.getAdapterPosition());
                    if(isTwoPane){
//这里是适配器,相当于活动,想拿到碎片要借助于FragmentManager。
                        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) {
//这里的position代表什么?如图是index,系统自动为每个子项分配索引。
//将List索引处的内容赋给news。
            News news=mNewsList.get(position);
//在这里设置了每一个子项应该展示的内容,即新闻标题news.getTitle()。
            holder.textView.setText(news.getTitle());
        }

        @Override//必须重写的方法之三
        public int getItemCount() {
//返回的值代表什么?如图是5,是列表中子项的个数。
            return mNewsList.size();
        }
    }
}


 

//标题碎片的布局,只有一个recyclerview

<?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:layout_width="match_parent"
        android:layout_height="match_parent"               android:id="@+id/news_title_recycler_view">
    </android.support.v7.widget.RecyclerView>
</LinearLayout>

 

//recyclerview的子项布局

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/news_item"
    android:maxLines="1"
    android:ellipsize="end"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="15dp"
    android:paddingBottom="15dp"
    android:textSize="18sp">
</TextView>

 

5.主活动及布局

主活动中什么都不用写

package com.scx040407.fragmentbestpractice2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

 

手机中,主布局引用标题碎片

<?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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/news_title_fragment"
        android:name="com.scx040407.fragmentbestpractice2.NewsTitleFragment"/>
</FrameLayout>

 

平板中主布局引用标题碎片和内容碎片,放到一起展示

这里要注意,如图在res文件夹中新建layout-sw600dp文件夹,把布局文件放进去,系统会自动根据设备屏幕的大小进行选择,如果屏幕大于600dp就启用这个布局。


<?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:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:id="@+id/news_title_fragment"
        android:name="com.scx040407.fragmentbestpractice2.NewsTitleFragment"/>
    <FrameLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:id="@+id/news_content_layout"

        >

        <fragment
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="com.scx040407.fragmentbestpractice2.NewsContentFragment"
            android:id="@+id/news_content_fragment"/>

    </FrameLayout>

</LinearLayout>

 

 

抱歉,作为AI语言模型,我无法提供完整的安卓应用程序。下面是一个简单的示例,可用于开始编写新闻应用程序: 1. 在Android Studio创建一个新项目,并选择Kotlin作为主要语言。 2. 在项目创建一个RecyclerView,用于显示新闻列表。 3. 创建一个新闻数据模型类,包括标题、描述、图片等信息。例如: ``` data class News(val title: String, val description: String, val image: Int) ``` 4. 创建一个新闻适配器类,用于将新闻数据绑定到RecyclerView的项。例如: ``` class NewsAdapter(private val newsList: List<News>) : RecyclerView.Adapter<NewsAdapter.ViewHolder>() { class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val titleTextView: TextView = view.findViewById(R.id.title_text_view) val descriptionTextView: TextView = view.findViewById(R.id.description_text_view) val imageView: ImageView = view.findViewById(R.id.image_view) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.news_item, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val news = newsList[position] holder.titleTextView.text = news.title holder.descriptionTextView.text = news.description holder.imageView.setImageResource(news.image) } override fun getItemCount() = newsList.size } ``` 5. 在MainActivity初始化新闻数据,并将其传递给适配器。例如: ``` class MainActivity : AppCompatActivity() { private lateinit var newsRecyclerView: RecyclerView private lateinit var newsAdapter: NewsAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) newsRecyclerView = findViewById(R.id.news_recycler_view) newsAdapter = NewsAdapter(getNewsList()) newsRecyclerView.adapter = newsAdapter newsRecyclerView.layoutManager = LinearLayoutManager(this) } private fun getNewsList(): List<News> { return listOf( News("新闻标题1", "新闻描述1", R.drawable.news_image1), News("新闻标题2", "新闻描述2", R.drawable.news_image2), News("新闻标题3", "新闻描述3", R.drawable.news_image3), // 添加更多新闻... ) } } ``` 6. 在布局文件添加RecyclerView和新闻项布局。例如: ``` <androidx.recyclerview.widget.RecyclerView android:id="@+id/news_recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> <LinearLayout android:id="@+id/news_item" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/image_view" android:layout_width="match_parent" android:layout_height="200dp" android:scaleType="centerCrop"/> <TextView android:id="@+id/title_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:textStyle="bold" android:padding="8dp"/> <TextView android:id="@+id/description_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:padding="8dp"/> </LinearLayout> ``` 这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值