1.1動態添加Fragment
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener{
replaceFragment(AnotherFragment())
}
replaceFragment(RightFragment())
}
private fun replaceFragment( fragment : Fragment){
val fragmentManager = supportFragmentManager
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.rightLayout,fragment)
transaction.commit()
}
}
1.2Fragment實現返回棧
transaction.addToBackStack(null)
...
private fun replaceFragment( fragment : Fragment){
val fragmentManager = supportFragmentManager
val transaction = fragmentManager.beginTransaction()
transaction.replace(R.id.rightLayout,fragment)
transaction.addToBackStack(null)
transaction.commit()
}
1.3Fragment生命週期
1.運行狀態
2.暫停狀態
3.停止狀態
4.銷燬狀態
onAttach():當Fragment和Activity建立關聯時調用
onCreateView():爲Fragment創建視圖(加載佈局)時調用
onActivityCreated():確保與Fragment相關聯的Activity已經創建完畢時調用
onDestroyView():當與Fragment關聯的視圖被移除時調用
onDetach():當Fragment和Activity解除關係時調用
1.4使用限定符區別平板與手機端
在res目錄下創建layout-large文件夾,在文件夾內創建同名佈局
使用最小寬度限定符
在res目錄下創建layout-sw600dp文件夾,在文件夾內創建同名佈局
最小寬度限定符允許我們對屏幕的寬度制定一個最小值(以dp爲單位),以這個最小值爲臨界點。
2.實踐 一個簡易版的新聞應用
修改layout目錄下activity_main文件
<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/newsTitleLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/newsTitleFrag"
android:name="com.example.fragmenttest.NewsTitleFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"></fragment>
</FrameLayout>
在layout-sw600dp目錄下創建activity_main文件
<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"
tools:context=".MainActivity">
<fragment
android:id="@+id/newsTitleFrag"
android:name="com.example.fragmenttest.NewsTitleFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"></fragment>
<FrameLayout
android:id="@+id/newsContentLayout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
>
<fragment
android:id="@+id/newsContentFrag"
android:name="com.example.fragmenttest.NewsContentFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
></fragment>
</FrameLayout>
</LinearLayout>
創建News實體類
class New (val title:String,val content:String){
}
創建news_title_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/newsTitleRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
創建news_title_frag.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/newsTitleRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
創建news_item.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/newsTitle"
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>
創建NewsFragFragment 並在內部創建內部類NewsAdapter
class NewsTitleFragment :Fragment(){
private var isTwoPane=false
inner class NewsAdaapter(val newsList:List<New>):RecyclerView.Adapter<NewsAdaapter.ViewHolder>(){
inner class ViewHolder(view:View) : RecyclerView.ViewHolder(view){
val newsTitle : TextView=view.findViewById(R.id.newsTitle)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view =LayoutInflater.from(parent.context).inflate(R.layout.news_item,parent,false)
val holder = ViewHolder(view)
holder.itemView.setOnClickListener {
val news = newsList[holder.adapterPosition]
if(isTwoPane){
//如果是雙頁模式
val fragment=newsContentFrag as NewsContentFragment
fragment.refresh(news.title,news.content)
}else{
//如果是單頁模式
NewsContentActivity.actionStart(parent.context,news.title,news.content)
}
}
return holder
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val news=newsList[position]
holder.newsTitle.text=news.title
}
override fun getItemCount(): Int {
return newsList.size
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.news_title_frag,container,false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
isTwoPane = activity?.findViewById<View>(R.id.newsContent) !=null
val layoutManager=LinearLayoutManager(activity)
newsTitleRecyclerView.layoutManager=layoutManager
val adapter = NewsAdaapter(getNews())
newsTitleRecyclerView.adapter=adapter
}
private fun getNews() : List<New>{
val newsList=ArrayList<New>()
for(i in 1..50){
val news = New("這是新聞$i",getRandomLengthString("新聞$i 正在播報,看懂看不懂由你."))
newsList.add(news)
}
return newsList
}
private fun getRandomLengthString(str:String) :String{
val n=(1..20).random()
val builder=StringBuilder()
repeat(n){
builder.append(str)
}
return builder.toString()
}
}
創建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/contentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible"
android:orientation="vertical">
<TextView
android:id="@+id/newsTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:textSize="20sp"
></TextView>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000"
></View>
<TextView
android:id="@+id/newsContent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:padding="15dp"
android:textSize="18sp"
></TextView>
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:background="#000"
></View>
</RelativeLayout>
創建NewsContentFragment
class NewsContentFragment : Fragment(){
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.new_content_frag,container,false)
}
fun refresh(title : String,content : String){
contentLayout.visibility = View.VISIBLE
newsTitle.text=title
newsContent.text=content
}
}
創建NewsContentActivity
class NewsContentActivity : AppCompatActivity() {
companion object{
fun actionStart(context : Context,title:String,content:String){
val intent = Intent(context,NewsContentActivity::class.java).apply {
putExtra("news_title",title)
putExtra("news_content",content)
}
context.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_news_content)
val title =intent.getStringExtra("news_title")
val content=intent.getStringExtra("news_content")
if(title!=null &&content !=null){
val fragment =newsContentFrag as NewsContentFragment
fragment.refresh(title,content)
}
}
}
3.Kotlin擴充
3.1擴展函數
模板:fun ClassName.methodName(param1 : Int , param2 : Int) : Int { }
fun String.lettersCount ( ) : Int {
var count = 0
for(char in this){
if(char.isLetter()){
count++
}
}
}
定義好可以直接這樣使用
val count = "ABC123xyz^%#"
3.2運算符重載
關鍵字:operator
模板:
class Obj{
operator fun plus(pbj : Obj) :Obj{
//處理相加邏輯
}
}
之後可以這樣直接用
val obj1=Obj()
val obj2=Obj()
val obj3=obj1+obj2
比如Money類,錢是可以相加的這樣設計