java 如何从android中的另一个片段类调用一个片段的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32100338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to call method of one fragment from another fragment class in android
提问by Arslan Ali Awan
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(类)的方法,我尝试通过在 fragmentA(类)中创建一个 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();
回答by Vindhya Pratap Singh
Try this solution:
试试这个解决方案:
((FragmentA) getActivity()
.getSupportFragmentManager()
.findFragmentById(R.id.pageview2)
).show();
回答by sunil sunny
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();
回答by Rakesh Kumar
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();