java - 使用 Activity 类在 fragment 类中调用方法

标签 java android android-fragments android-activity

我正在尝试将一个 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/

相关文章:

java - 读取txt文件内容并存入数组

java - Android:从 Fragment 调用父 Activity

Android fragment ——切换到不同选项卡时调用 OnDestroy,然后返回选项卡时调用 OnCreate?

java - 使用远程桌面连接运行 testng webdriver 测试

android - LocalDateTime 未解析特定设备

java - 无法解决 "Parcelable encountered IOException writing serializable object"

java - fragment 内单选按钮 OnCheckedChangeListener 错误

java - 在 selenium WebDriver 中返回时出现 StaleElementReferenceException

java - Mac 上失败 "play new"

java - 在java中用另一个字符串替换字符串