[英]Android: How to programmatically click on a button previously located in an activity in the activity stack, from a fragment?
When I am in a fragmentB, how to simulate a click on a button located in an activity in the stack.当我在 fragmentB 中时,如何模拟单击位于堆栈中活动中的按钮。
LoginActivityA => fragmentB.登录活动A => 片段B。
I want to simulate something like this:我想模拟这样的事情:
LoginActivityA.btnClick() from the fragmentB来自片段B的LoginActivityA.btnClick()
I tried to use this tickets with no success: Ticket1 , Ticket2 , Ticket3我尝试使用这张票但没有成功: Ticket1 、 Ticket2 、 Ticket3
Here is my code:这是我的代码:
FragmentB:片段B:
//BEGIN TEST
String message="hello ";
Intent intent = new Intent(getActivity(), LoginActivity.class);
intent.putExtra("MESSAGE",message);
getActivity().setResult(2,intent);
getActivity().startActivityForResult(intent,2);
getActivity().finish();//finishing activity
//END TEST
LoginActivityA:登录活动A:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
//do the things u wanted
}
}
I precise that I try not to get multiple LoginActivity and Fragment launched.我确切地说我尽量不启动多个 LoginActivity 和 Fragment。 I would like to get only one stack with LoginActivity => Fragment我只想使用 LoginActivity => Fragment 获得一个堆栈
Any ideas?有任何想法吗?
EDIT:编辑:
I tried this from this tichet with no success:我从这张票中尝试了这个,但没有成功:
((LoginActivity)getActivity()).login();
I launched the activity function from the presented fragment with an error我从呈现的片段启动了活动功能,但出现错误
"No acceptable module found. Local version is 0 and remote version is 0." “未找到可接受的模块。本地版本为 0,远程版本为 0。”
You can use an interface with an onClick method that is implemented by your activity and then in fragment B call the method onClick whenever you want and pass the activity to it.您可以使用带有 onClick 方法的接口,该方法由您的活动实现,然后在片段 B 中随时调用 onClick 方法并将活动传递给它。
Although I presume what you are doing is wrong and you should change your mind around it.虽然我认为你在做什么是错误的,你应该改变主意。
This is not a good practice, but if you want you can call your activity UI elements by这不是一个好的做法,但如果您愿意,可以通过以下方式调用您的活动 UI 元素
((Button) getActivity().findViewById(R.id.button_id)).performClick();
Always remember, Android is a well architect platform, if you are trying to do something which is difficult, probably you should not do it.永远记住,Android 是一个架构良好的平台,如果你正在尝试做一些困难的事情,你可能不应该这样做。 Rethink about your your design patterns.重新考虑您的设计模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.