SoFunction
Updated on 2025-04-12

News application that implements basic functions of Android

Prepare a news entity first

package 
/**
  * title: The entity class that represents news
  * content: the content of the news
  */
class News(val title: String, val content: String) {
}

Create a new layout file news_content_frag.xml as the content of the news layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:visibility="invisible">
        <TextView
            android:
            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:
            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>
  • The news layout is mainly divided into two parts: the head part displays the news title, the main part displays the content, and a horizontal thin line is separated from the middle. In addition, there is a thin line of vertical defense. Its function is to separate the news list on the left and the news content on the right in the double-page mode.
  • We also need to set the layout of the news content to be invisible, because in two-page mode, if any news in the news list is not selected, the layout of the news content should not be displayed.
  • Next, create a new NewsContentFragment class
class NewsContentFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return (.news_content_frag, container, false)
    }
    /**
      * This method is used to display the title and content of the news on the interface we just defined,
      * When the refresh method is called, the news content layout we just hidden needs to be set to be visible
      */
    fun refresh(title: String, content: String) {
        //Set the layout to be visible         = 
        //Set news title content         = title
        //Set news content         = content
    }
}
  • The layout we just created is loaded in the onCreatView() method
  • This creates the fragment and layout of the news content, but they are all used in the two-page mode. If you want to use it in the single-page mode, we also need to create an Activity
  • Create a NewsContentActivity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <fragment
        android:
        android:name=""
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
  • This place brings out the reusability of the code and directly introduces NewsContentFragment into the layout. This is equivalent to automatically adding the content of the news_content_frag layout.
  • Modify the code in NewsContentActivity
class NewsContentActivity : AppCompatActivity() {
    companion object {
        fun actionStart(context: Context, title: String, content: String) {
            val intent = Intent(context, NewsContentActivity::).apply {
                putExtra("news title", title)
                putExtra("news content", content)
            }
            (intent)
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        (savedInstanceState)
        setContentView(.activity_news_content)
        val title = ("news title")//Get the incoming news title        val content = ("news content")//Get incoming news content        if (title != null &amp;&amp; content!= null) {
            val fragment = newsContentFrag as NewsContentFragment
            (title, content) //Refresh the NewsContentFragment interface        }
    }
}
  • In the onCreate() method, we obtain the incoming news title and news content through Intent, then obtain the NewsContentFragment instance, and then call its refresh() method to pass the news title and content in, and then display these data.
  • Next create a layout for displaying news lists and create a new news_title_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <
        android:
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

The layout is relatively simple, there is only one RecyclerView for displaying news lists. Since you want to use RecyclerView, you have to write the layout of the child item. Create news_item.xml as the layout of the child item of the RecyclerView.

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:andro
    android:
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:ellipsize="end"
    android:textSize="18sp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingTop="15dp"
    android:paddingBottom="15dp">
</TextView>
  • The layout of the child item is also relatively simple, there is only one TextView
  • where android:padding means adding fillers around the space so that the text content will not be close to the edge.
  • android:ellipsize is used to set the abbreviation method when the text content exceeds the control width. Here, it is specified as end to indicate that it is omitted at the end.
  • The news list and sub-layout have been created. Now we need a place to display the news list. Here we create a new NewsTitleFragment as the list of Fragment
class NewsTitleFragment : Fragment() {
    private var isTwoPane = false
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return (.news_title_frag, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        (savedInstanceState)
        isTwoPane = activity?.findViewById<View>() != null
    }
}
  • The onActivityCreated() method can determine whether it is currently a double-page mode or a single-page mode by finding a View with id of newsContentLayout in the Activity.
  • Therefore, we need to make this View with the id of newsContentLayout only appear in the dual-page mode.
  • Views with id newsContentLayout using qualifiers can only appear in double page mode.
  • Modify the code in activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:andro
    android:
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment
        android:
        android:name=""
        android:layout_width="match_parent"
        android:layout_height="match_parent"
</FrameLayout>
  • The above code means that only a single news title will be loaded in single page mode
  • Then create a new layout-sw600dp folder, and create an activity_main.xml file under this folder. The code is as follows
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <fragment
        android:
        android:name=""
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
    <FrameLayout
        android:
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3">
        <fragment
            android:
            android:name=""
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </FrameLayout>
</LinearLayout>
  • It can be seen that in the double-page mode, two fragments are introduced at the same time, and the fragment of the news content is placed under the Fragment layout. The layout id of this Fragment is newsContentFrag
  • Therefore, as long as the id of this layout can be found, it means it is a double-page mode, otherwise it is a single-page mode.
  • Next is to display the news list through RecyclerView in NewsTitleFragment
  • Create a new internal class NewsAdapter in NewsTitleFragment to serve as an adapter for RecyclerView
package 
import 
import 
import 
import 
import 
import 
import 
import 
import .activity_news_content.*
import .news_item.view.*
import .news_title_frag.*
/**
  * Used to display news lists
  */
class NewsTitleFragment : Fragment() {
    private var isTwoPane = false
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return (.news_title_frag, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        (savedInstanceState)
        isTwoPane = activity?.findViewById&lt;View&gt;() != null
        val layoutManager = LinearLayoutManager(activity)
         = layoutManager
        val adapter = NewsAdapter(getNews())
         = adapter
    }
    private fun getNews(): List&lt;News&gt; {
        val newsList = ArrayList&lt;News&gt;()
        for (i in 1..50) {
            val news =
                News("This is news title $i", getRandomLengthString("This is news content $i."))
            (news)
        }
        return newsList
    }
    private fun getRandomLengthString(str: String): String {
        val n = (1..20).random()
        val builder = StringBuilder()
        repeat(n) {
            (str)
        }
        return ()
    }
    /**
      * Internal class, used as an adapter for RecyclerView
      */
    inner class NewsAdapter(val newsList: List&lt;News&gt;) :
        &lt;&gt;() {
        inner class ViewHolder(view: View) : (view) {
            val newsTitle: TextView = 
        }
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view =
                ().inflate(.news_item, parent, false)
            val holder = ViewHolder(view)
             {
                //Get the news instance first in the newsList                val news = newsList[]
                //Judge whether it is single page mode or double page mode according to isTwoPane                if (isTwoPane) {
                    //If it is in double page mode, refresh the content in newsContentFragment                    val fragment = newsContentFrag as NewsContentFragment
                    (, )
                } else {
                    //If it is single page mode, directly start NewsContentActivity                    (, , )
                }
            }
            return holder
        }
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val news = newsList[position]
             = 
        }
        override fun getItemCount(): Int {
            return 
        }
    }
}
  • The final step is to add data to the RecyclerView
  • Modify the code in NewsTitleFragment

This is the end of this article about news applications that implement basic functions of Android. For more related Android news applications, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!