繁体   English   中英

如何用Android上的Kotlin片段替换FrameLayout

[英]How to replace a FrameLayout with a fragment with Kotlin on Android

我正在尝试用Kotlin开发一个Android应用程序,但是当我尝试动态移动片段时,我遇到了一些麻烦。 我想要做的是用一个片段替换Activity的布局中的FrameLayout。 目前,每当我尝试运行我的应用程序时,它只会在工具栏下方显示一个白色屏幕,让我相信该片段没有按照我预期的方式添加到FrameLayout。

这是我执行第一笔交易的主要活动:

package net.ma.ttrobinson.kchan

import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.EditText
import com.androidquery.callback.AjaxStatus
import net.ma.ttrobinson.kchan.api.ChanThread
import net.ma.ttrobinson.kchan.api.Request
import org.jdeferred.DoneCallback
import org.jdeferred.FailCallback
import org.json.JSONArray
import org.json.JSONObject

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toolbar = findViewById(R.id.toolbar) as Toolbar
        setSupportActionBar(toolbar)

        getSupportFragmentManager().beginTransaction()
            .replace(R.id.main_content_frame, MainFragment())
            .commit()
    }
}

这是我试图创建的片段。 它只是在按下按钮时添加回调时为视图充气:

package net.ma.ttrobinson.kchan

import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import com.androidquery.callback.AjaxStatus
import net.ma.ttrobinson.kchan.api.ChanThread
import net.ma.ttrobinson.kchan.api.Request
import org.jdeferred.DoneCallback
import org.jdeferred.FailCallback

/**
 * Holds the main content
 */
class MainFragment : Fragment() {
    companion object {
        val TAG = "MainFragment"
    }

    val debugBoard = "g"
    val debugThread = "48667796"

    override fun onCreateView(inflater : LayoutInflater, parent : ViewGroup?, savedInstanceState : Bundle?) : View {
        val v = inflater.inflate(R.layout.fragment_main, parent, false)
        val boardText = v.findViewById(R.id.board_text) as EditText
        val threadText = v.findViewById(R.id.thread_text) as EditText
        val request = Request(getActivity())

        boardText.setText(debugBoard)
        threadText.setText(debugThread)

        val button = v.findViewById(R.id.submit) as Button
        button.setOnClickListener({ v ->
            val board = boardText.getText().toString()
            val thread = threadText.getText().toString().toInt()

            val promise = request.getThread(board, thread)
            promise.done({ thread ->
                val fm = getActivity().getSupportFragmentManager()
                fm.beginTransaction()
                    .replace(R.id.main_content_frame, ThreadFragment(thread), ThreadFragment.TAG)
                    .addToBackStack(null)
                    .commit()
            }).fail({ result ->
                Log.v(TAG, "Failed to get thread")
            })
        })

        return v
    }
}

这是主Activity与setContentView一起使用的布局:

<?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">

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

    <FrameLayout
        android:id="@+id/main_content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

最后这里是片段膨胀的布局:

<?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" >

    <EditText
        android:id="@+id/board_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/board_hint"/>

    <EditText
        android:id="@+id/thread_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone"
        android:hint="@string/thread_hint"/>

    <Button
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/submit"/>
</LinearLayout>

我觉得这是一个相当简单的主Activity的设置,它有一个可以与其他片段交换的FrameLayout。 有谁知道我可能做错了什么?

与此同时,我想我会尝试做一个更简单的案例来尝试复制行为。

编辑:这么简单的解决方案。 我忘记在我的LinearLayout中添加android:orientation="vertical" 这是更新的代码:

<?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">

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

    <FrameLayout
        android:id="@+id/main_content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

问题是Activity的LinearLayout应该有orientation="vertical"

<?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">

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

    <FrameLayout
        android:id="@+id/main_content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

只是我想支付扩展功能的意图它是如此有用。 在这里,我将分享一些步骤来做到这一点

  1. 例如,创建一个名为util的kotlin文件,并添加允许添加和替换片段的函数

util.kt

fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int){
    supportFragmentManager.inTransaction { add(frameId, fragment) }
}
fun AppCompatActivity.replaceFragment(fragment: Fragment, frameId: Int) {
    supportFragmentManager.inTransaction{replace(frameId, fragment)}
}

inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> FragmentTransaction) {
    beginTransaction().func().commit()
}
  1. 创建片段布局。 我称之为father_fragment,例如fahter_fragment

      <!-- You can put whatever you want here--> 

  2. 在您的Activity xml中创建一个将占用片段的布局:

activity_principal.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.tharwa.tdm2_exo2.Principal">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/container"
        >
    </FrameLayout>
</android.support.design.widget.CoordinatorLayout>
  1. 现在,在您的活动中,您可以轻松创建片段

    主要

    class Principal:AppCompatActivity(){

      override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_principal) //Create and add the fragment val fatherView=FatherPresentation() addFragment(fatherView,R.id.container) } } 

如果你想从你的活动中替换片段,那么只需要做replaceFragment(Fragment_you_want_to_replace_with(),id_of_of_your_frame_layout)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM