使用Activity类调用片段类中的方法
问题描述:
我正在尝试向我的活动添加一个片段,并调用活动中片段类中的方法。 我在没有调用活动类中的方法的情况下测试了片段,并且该片段在活动中显示时没有任何问题。但是我无法调用片段类中的方法。使用Activity类调用片段类中的方法
下面是我在activity类中的代码。
使用下面的方法,当点击一个按钮时,我调用要显示在我的活动中的片段。
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();
}
下面是片段类和填充数据方法的代码是我想要调用的方法。
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);
}
}
}
我想从活动类中调用填充日期方法并显示片段。
我该如何做到这一点?
谢谢。
答
使下面的一个方法,然后使用tablefragment调用你的方法。 并从活动中调用此方法。 并使用xml文件添加您的片段。
public void setDataAccordingToYourNeed(){
table_fragment tablefragment=getFragmentManager().findFragmentById(your_fragment_id);
tablefragment.yourFragmentMethod();
}
这必将解决您的问题,如果你没有得到让我知道