我有两门课。第一个是活动,第二个是片段,其中有一些EditText。在活动中,我有一个带有async-task的子类,在方法doInBackground中,我得到了一些结果,我保存到变量中。我怎么能把这个变量从子类“我的活动”到这个片段?
当前回答
这个答案可能太迟了。但它对未来的读者是有用的。
我有一些标准。我已经为从意图中选择文件编写了代码。并将选定的文件传递到特定片段进行进一步处理。我有许多片段具有文件选择的功能。当时,每次检查条件,获取片段并传递值都是很恶心的。因此,我决定使用接口传递值。
步骤1:在Main Activity上创建接口。
public interface SelectedBundle {
void onBundleSelect(Bundle bundle);
}
步骤2:在同一个活动上创建selectebundle引用
SelectedBundle selectedBundle;
步骤3:在同一个活动中创建方法
public void setOnBundleSelected(SelectedBundle selectedBundle) {
this.selectedBundle = selectedBundle;
}
步骤4:需要初始化selectebundle引用,这些引用都是片段需要文件选择器功能。你把这段代码放在fragment onCreateView(..)方法上
((MainActivity)getActivity()).setOnBundleSelected(new MainActivity.SelectedBundle() {
@Override
public void onBundleSelect(Bundle bundle) {
updateList(bundle);
}
});
第5步:我的情况下,我需要通过图像Uri从HomeActivity片段。所以,我在onActivityResult方法上使用了这个功能。
来自MainActivity的onActivityResult,使用接口将值传递给片段。
注意:您的情况可能不同。你可以从你的HomeActivity的任何地方调用它。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
selectedBundle.onBundleSelect(bundle);
}
这一切。在FragmentClass上实现你需要的每个片段。你很棒。你做到了。哇……
其他回答
将数据从活动类发送到片段的更好方法是通过setter方法传递。就像
FragmentClass fragmentClass = new FragmentClass();
fragmentClass.setMyList(mylist);
fragmentClass.setMyString(myString);
fragmentClass.setMyMap(myMap);
并且很容易从类中获得这些数据。
Very old post, still I dare to add a little explanation that would had been helpful for me. Technically you can directly set members of any type in a fragment from activity. So why Bundle? The reason is very simple - Bundle provides uniform way to handle:-- creating/opening fragment -- reconfiguration (screen rotation) - just add initial/updated bundle to outState in onSaveInstanceState() -- app restoration after being garbage collected in background (as with reconfiguration). You can (if you like experiments) create a workaround in simple situations but Bundle-approach just doesn't see difference between one fragment and one thousand on a backstack - it stays simple and straightforward. That's why the answer by @Elenasys is the most elegant and universal solution. And that's why the answer given by @Martin has pitfalls
有时你可以在你的活动中接收Intent,你需要将信息传递给你的工作片段。 给出的答案是OK,如果你需要启动片段,但如果它仍在工作,setArguments()不是很有用。 如果传递的信息将导致与UI交互,则会出现另一个问题。在这种情况下,你不能调用像myfragment.passData()这样的东西,因为android会迅速告诉只有创建视图的线程可以与之交互。
所以我的建议是使用接收器。这样,您可以从任何地方发送数据,包括活动,但是工作将在片段的上下文中完成。
在你的片段的onCreate():
protected DataReceiver dataReceiver;
public static final String REC_DATA = "REC_DATA";
@Override
public void onCreate(Bundle savedInstanceState) {
data Receiver = new DataReceiver();
intentFilter = new IntentFilter(REC_DATA);
getActivity().registerReceiver(dataReceiver, intentFilter);
}
private class DataReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int data= intent.getIntExtra("data", -1);
// Do anything including interact with your UI
}
}
在你的活动:
// somewhere
Intent retIntent = new Intent(RE_DATA);
retIntent.putExtra("data", myData);
sendBroadcast(retIntent);
如果一个活动需要一个片段在初始化后执行一个动作,最简单的方法是让这个活动调用片段实例上的一个方法。在这个片段中,添加一个方法:
public class DemoFragment extends Fragment {
public void doSomething(String param) {
// do something in fragment
}
}
然后在活动中,使用片段管理器访问片段并调用方法:
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DemoFragment fragmentDemo = (DemoFragment)
getSupportFragmentManager().findFragmentById(R.id.fragmentDemo);
fragmentDemo.doSomething("some param");
}
}
然后活动可以通过调用此方法直接与片段通信。
在片段和活动之间传递数据的最聪明的方法是创建一个变量,例如:
class StorageUtil {
public static ArrayList<Employee> employees;
}
然后通过onActivityCreated方法将数据从fragment传递给activity:
//a field created in the sending fragment
ArrayList<Employee> employees;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
employees=new ArrayList();
//java 7 and above syntax for arraylist else use employees=new ArrayList<Employee>() for java 6 and below
//Adding first employee
Employee employee=new Employee("1","Andrew","Sam","1984-04-10","Male","Ghanaian");
employees.add(employee);
//Adding second employee
Employee employee=new Employee("1","Akuah","Morrison","1984-02-04","Female","Ghanaian");
employees.add(employee);
StorageUtil.employees=employees;
}
现在您可以获得StorageUtil的值。来自各地的员工。 古德勒克!
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 碎片中的onCreateOptionsMenu
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- DSL元素android.dataBinding。enabled'已过时,已被'android.buildFeatures.dataBinding'取代
- ConstraintLayout:以编程方式更改约束
- PANIC: AVD系统路径损坏。检查ANDROID_SDK_ROOT值
- 如何生成字符串类型的buildConfigField
- Recyclerview不调用onCreateViewHolder
- Android API 21工具栏填充
- Android L中不支持操作栏导航模式
- 如何在TextView中添加一个子弹符号?
- PreferenceManager getDefaultSharedPreferences在Android Q中已弃用
- 在Android Studio中创建aar文件