[英]how to call method of one fragment from another fragment class in android
I want to call a method of FragmentB (Class) from a fragmentA I tried by making a object of fragmentb in fragmentA (class) but it's not working here is the code of fragmentA in this class I have a method through which I will call the method of FragmentB class 我想从fragmentA调用FragmentB(Class)的方法,我尝试通过在fragmentA(class)中创建fragmentb的对象来尝试,但是在这里它不起作用是该类中fragmentA的代码,我有一个方法可以通过它调用FragmentB类的方法
adddata.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isInserted = myDb.addalldata(monthly_income.getText().toString(),
room_rent.getText().toString(),
mess_rent.getText().toString());
if (isInserted = true)
Toast.makeText(getActivity().getBaseContext(), "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(getActivity().getBaseContext(), "Data not Inserted", Toast.LENGTH_LONG).show();
}
}
);
I want to call this method of fragmentB 我想称这个为fragmentB的方法
public void show() {
Cursor res = myDb.getAllData();
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
displayresult.setText( buffer.append( res.getString(1)));
}
}
I tried by writing this code in method of fragmentA but am getting error 我尝试通过fragmentA方法编写此代码,但出现错误
FragmentA fragment=
(FragmentA)getSupportFragmentManager().findFragmentById(R.id.pageview2);
((FragmentA)fragment).show();
Try this solution: 试试这个解决方案:
((FragmentA) getActivity()
.getSupportFragmentManager()
.findFragmentById(R.id.pageview2)
).show();
You can create static varibales like this 您可以像这样创建静态变量
static FragmentB f;
public static FragmentB newInstance(String title) {
FragmentB f = new FragmentB();
Bundle b = new Bundle();
b.putString(ARG_STATION_TITLE, title);
f.setArguments(b);
return f;
}
You can use the getInstance() method to get the instance of fragmentB 您可以使用getInstance()方法获取fragmentB的实例
public static FragmentB getInstance(){
return f;
}
Call like this FragmentB.getInstance().methodinFragmentB();
这样调用FragmentB.getInstance().methodinFragmentB();
In FragmentA class you can do the following code:- 在FragmentA类中,您可以执行以下代码:-
private static FragmentA instance = null;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
}
public static FragmentA getInstance() {
return instance;
}
And in FragmentB class you can call the method as follows: 在FragmentB类中,您可以按以下方式调用方法:
FragmentA.getInstance().show();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.