我正在开发一个需要在片段之间进行数据传输的应用程序,并偶然发现了两个版本 以下是实现侦听器的非常相似的版本。您认为哪一个更适合片段之间的通信?或者其他一些实现?另一个问题是:是否需要另一个接口来将第二个片段中的数据通过MainAvtivity发送回第一个片段,或者是否有更简单的方法可以做到这一点?
谢谢
首先:
#include <stdio.h>
#include <math.h>
int
main(void)
{
float search;
float current;
float found;
float difference;
FILE *file;
file = fopen("StandardResistance.txt", "r");
if (file == NULL)
return -1;
search = 1.4;
found = 0.0;
difference = FLT_MAX;
while (fscanf(file, "%f", ¤t) == 1)
{
if (fabs(search - current) < difference)
{
found = current;
difference = fabs(search - current);
}
}
fclose(file);
fprintf(stderr, "found: %f\n", found);
return 0;
}
或者第二个:
class FragOne extends ListFragment
{
ListenerInterface listener;
public void onAttach(Content content)
{
try{
listener = (ListenerInterface).content;
}catch ClassCastException..
super.onAttach(content);
}
...
public void OnListItemClick(ListView, View,position,id)
{
listener.doSmth(someData);
}
public interface ListenerInterface
{
public void doSmth(someData);
}
}
class MainActivity extends Activity implements FragOne.ListInterface
{
....
public void doSmth(someData)
{
//sending data to second fragment
}
}
答案 0 :(得分:0)
我个人会因为onAttach中的代码而推荐第一个。创建一个函数只是为了调用那个部分看起来很荒谬,很容易忘记你必须在使用界面之前调用该函数(特别是对于新手)。你会得到NullPointerException。
第一种方法很好,只有当FragOne是唯一使用该接口的方法时。否则,在java类中创建一个单独的接口,其他片段也可以以类似的方式使用。
您可以在一个界面中定义多个方法,多个片段可以使用界面中的部分或全部方法。但请记住,一次只能访问一个接口。一个片段可以访问多个接口。