我是否正确使用了findFragmentByTag

时间:2015-06-14 00:13:13

标签: android android-fragments

我的活动动态创建片段,并且不会在开始时创建它们(隐藏)。所以我需要基本上能够识别我的片段,以便我可以从我的活动中向他们发送数据。当我尝试从我的主活动中调用片段的函数(addAthleteToList)时,我一直得到一个空对象引用。说我的运动员对象是null我是否正确识别(创建)我的片段引用?感谢

如果没有,我如何为我的片段创建标签?

将数据发送到片段B(AthletesList)的主要活动功能:

 // Interface function
 // Sends athlete information to athlete list

@Override
public void send(Athlete athlete) {
    Log.e("", "Main Activity: " + athlete.getFirstName());
    AthletesList athletesList = (AthletesList) getSupportFragmentManager().findFragmentByTag("athleteList");

    ArrayList<String> athleteEvents = new ArrayList<String>();
    athleteEvents = athlete.getEvents();

    for(int i = 0; i < athleteEvents.size(); i++) {
        Log.e("", "Athlete Event: " + athleteEvents.get(i).toString());
        switch (athleteEvents.get(i).toString()){
            case "4 x 400":
                athletesList.addAthleteToList(athlete, 1);
                break;
            case "1-Mile":
                break;
            case "100-Meter":
                break;
        }
    }
}

片段A:

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    btnAddAthlete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Athlete athlete = new Athlete();
            athlete.setFirstName(editFirstName.getText().toString());
            athlete.setLastName(editLastName.getText().toString());
            athlete.setAge(Integer.parseInt(editAge.getText().toString()));
            athlete.setEvents(athleteEvents);
            athlete.setGrade(editGrade.getText().toString());
            athlete.setTier(Integer.parseInt(editTier.getText().toString()));

            Log.e("", "Athlete Name: " + athlete.getFirstName() + " " + athlete.getLastName());

            AthletesList athletesList = new AthletesList();
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.frameLayout, athletesList, "athletesList").commit();
            // interface sends athlete to main activity
            communicator.send(athlete);
        }
    });
}

1 个答案:

答案 0 :(得分:1)

您的npm install memwatch-next 值不同

设置标记显示“athletesList”

FragmentTag

获取标记显示“athleteList”

transaction.replace(R.id.frameLayout, athletesList, "athletesList").commit();    

AthletesList athletesList = (AthletesList) getSupportFragmentManager().findFragmentByTag("athleteList"); ,因此您的athletesList!=athleteList会返回findFragmentByTag

要获得更好的解决方案,请创建一个可用于标记片段的公共字段常量,例如:

null

然后将其用作public static final String TAG_FRAGMENT_ATHLETELIST = "tag_athletelist";

设置

fragmentTag

获取

transaction.replace(R.id.frameLayout, athletesList, TAG_FRAGMENT_ATHLETELIST).commit();