试图从片段中调用我的活动中的方法。我想要片段给方法数据,并在方法返回时获得数据。我想实现类似于对静态方法的调用,但不使用静态,因为它会在活动中产生问题。
新的片段,所以我需要一个简单的和教学的解释!
谢谢!
试图从片段中调用我的活动中的方法。我想要片段给方法数据,并在方法返回时获得数据。我想实现类似于对静态方法的调用,但不使用静态,因为它会在活动中产生问题。
新的片段,所以我需要一个简单的和教学的解释!
谢谢!
当前回答
谢谢@BIJAY_JHA和@Manaus。我使用Kotlin版本来调用我的signIn()方法,该方法存在于活动中,并且我从一个片段中调用。我在Android中使用导航架构,所以监听器接口模式不在片段中:
(activity as MainActivity).signIn()
其他回答
对于Kotlin,请尝试一下
class DataForm : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
Tasks(this).getData()
}
fun getResponse(response: String) {
// code
}
}
class Tasks(private val context: Any) {
fun getData() {
val getContext = (context as DataForm).activity
val getFragment = (context as DataForm)
val responseListener = Response.Listener<String> { response ->
getFragment.getResponse(response)
}
val errorListener = Response.ErrorListener { error ->
error.printStackTrace();
}
val stringRequest = StringRequest(Request.Method.GET, url, responseListener, errorListener)
Volley.newRequestQueue(getContext).add(stringRequest)
}
}
谢谢@BIJAY_JHA和@Manaus。我使用Kotlin版本来调用我的signIn()方法,该方法存在于活动中,并且我从一个片段中调用。我在Android中使用导航架构,所以监听器接口模式不在片段中:
(activity as MainActivity).signIn()
虽然我完全喜欢Marco的回答,但我认为指出你也可以使用基于发布/订阅的框架来实现相同的结果是公平的,例如,如果你使用事件总线,你可以做到以下几点
片段:
EventBus.getDefault().post(new DoSomeActionEvent());
活动:
@Subscribe
onSomeActionEventRecieved(DoSomeActionEvent doSomeActionEvent){
//Do something
}
在kotlin中,你可以从片段中调用activity方法,如下所示:
var mainActivity: MainActivity = activity as MainActivity
mainActivity.showToast() //Calling show toast method of activity
以下是我的做法:
首先制作接口
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()
}