我正在尝试将一个 fragment 添加到我的 Activity 中,并从该 Activity 中调用 fragment 类中的一个方法。 我在没有从 Activity 类调用方法的情况下测试了该 fragment ,并且该 fragment 毫无问题地显示在 Activity 中。但是我无法调用 fragment 类中的方法。
下面是我在 Activity 类中的代码。
使用下面的方法,我调用要在单击按钮时在 Activity 中显示的 fragment 。
public void checkTimes(View view){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
table_fragment tablefragment = new table_fragment();
fragmentTransaction.add(R.id.fragmentContainer, tablefragment);
fragmentTransaction.commit();
}
下面是 fragment 类的代码,填充数据方法是我要调用的方法。
public class table_fragment extends Fragment {
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.table_fragment, container, false);
return view;
}
/**
* Method used to populate dates in the fragment
* @param startDate
* @param endDate
*/
public void populateData(Context context,LocalDate startDate, LocalDate endDate){
ArrayList<LocalDate> dates = Utility.calculateDates(startDate,endDate);
TableLayout table = (TableLayout) view.findViewById(R.id.dateTable); //getting the table layout in the fragment
for(LocalDate date : dates){
TableRow tableRow=new TableRow(context);
tableRow.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
TextView tv=new TextView(context);
tv.setText(date.toString());
tableRow.addView(tv);
table.addView(tableRow);
}
}
}
我想从 Activity 类中调用填充日期方法并显示 fragment 。
我怎样才能做到这一点?
谢谢。
最佳答案
创建一个如下所示的方法,然后使用 tablefragment 调用您的方法。 并从 Activity 中调用此方法。 并使用 xml 文件添加您的 fragment 。
public void setDataAccordingToYourNeed(){
table_fragment tablefragment=getFragmentManager().findFragmentById(your_fragment_id);
tablefragment.yourFragmentMethod();
}
这肯定会解决你的问题,如果你没有得到让我知道
关于java - 使用 Activity 类在 fragment 类中调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46741851/