试图从片段中调用我的活动中的方法。我想要片段给方法数据,并在方法返回时获得数据。我想实现类似于对静态方法的调用,但不使用静态,因为它会在活动中产生问题。

新的片段,所以我需要一个简单的和教学的解释!

谢谢!


当前回答

从碎片到活动:

((YourActivityClassName) requireActivity ()) .yourPublicMethod ();

其他回答

在kotlin中,你可以从片段中调用activity方法,如下所示:

var mainActivity: MainActivity = activity as MainActivity
        mainActivity.showToast() //Calling show toast method of activity

更新后,我了解更多的碎片如何工作。每个片段都属于一个父活动。所以只需使用:

getActivity().whatever

从片段内部。这是一个更好的答案,因为可以避免多余的类型转换。如果这个解决方案不能避免强制转换,请使用下面的方法。

============

你要做的就是投射到外部活动

((MainActivity) getActivity()).Method();

创建一个新的实例将使android框架感到困惑,它将无法识别它。 参见:

https://stackoverflow.com/a/12014834/1984636

https://stackoverflow.com/a/2042829/1984636

我已经尝试了这个线程中显示的所有方法,没有一个对我有效,试试这个。这对我很管用。

((MainActivity) getContext().getApplicationContext()).Method();

以下是我的做法:

首先制作接口

interface NavigationInterface {
    fun closeActivity()
}

接下来确保activity实现了接口并覆盖了接口方法

class NotesActivity : AppCompatActivity(), NavigationInterface {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_notes)
        setSupportActionBar(findViewById(R.id.toolbar))
    }

    override fun closeActivity() {
        this.finish()
    }
}

然后确保在片段中创建接口侦听器

private lateinit var navigationInterface: NavigationInterface

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
): View? {
    //establish interface communication
    activity?.let {
        instantiateNavigationInterface(it)
    }
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_notes_info, container, false)
}

private fun instantiateNavigationInterface(context: FragmentActivity) {
    navigationInterface = context as NavigationInterface
}

然后你就可以这样打电话了:

view.findViewById<Button>(R.id.button_second).setOnClickListener {
    navigationInterface.closeActivity()
}

我一直在寻找最好的方法来做到这一点,因为不是每个方法,我们要调用位于片段与相同的活动父。

在你的碎片里

public void methodExemple(View view){

        // your code here

        Toast.makeText(view.getContext(), "Clicked clicked",Toast.LENGTH_LONG).show();
    }

在活动中

new ExempleFragment().methodExemple(context);