如何确保在访问适配器之前创建片段?

时间:2016-12-29 02:27:09

标签: android listview android-fragments

我仍在尝试为我的应用程序找到正确的设计,以防止在我的应用程序的tab host中以两个单独的片段调用适配器列表视图。

我到目前为止访问listviews的适配器时,只能在null为空时访问该值,我假设因为片段尚未完全设置且适配器没有&#虽然我不确定,但是已经创造了。如何在调用pubnub访问它之前确保适配器已设置?

我找到的唯一答案是使用处理程序来延迟事件,直到片段设置完毕,但这对我没有用。适配器仍为空。

片段1:

public class GroupChatFragment extends Fragment{

public ArrayAdapter<String> adapter;
private Context context;

public GroupChatFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_group_chat, container, false);
    ListView chatListView = (ListView) rootView.findViewById(R.id.chatList);
    adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1);
    chatListView.setAdapter(adapter);
    return rootView;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.context = context;
}

@Override
public void onDetach() {
    super.onDetach();
}
}

片段2:

public class GroupTasksFragment extends Fragment {

public ArrayAdapter<String> adapter;
private Context context;

public GroupTasksFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_group_tasks, container, false);
    ListView taskListView = (ListView) rootView.findViewById(R.id.tasksList);
    adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1);
    taskListView.setAdapter(adapter);
    return rootView;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.context = context;
}

@Override
public void onDetach() {
    super.onDetach();
}
}

引用片段的类(为了清楚起见,已经注释了访问适配器的行):

public class GroupContentActivity extends AppCompatActivity {

private GroupChatFragment chatFrag;
private GroupTasksFragment taskFrag;
private PubNub connection;
private String groupName;
private String nickName;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_group_content);
    FragmentTabHost tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
    tabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

    tabHost.addTab(tabHost.newTabSpec("tasks").setIndicator("Tasks"),
            GroupTasksFragment.class, null);

    tabHost.addTab(tabHost.newTabSpec("chat")
            .setIndicator("Chat"), GroupChatFragment.class, null);

    groupName = getIntent().getStringExtra("groupName");
    nickName = getIntent().getStringExtra("nickName");
    PNConfiguration config = new PNConfiguration();
    config.setPublishKey("pub-c-d8414fbe-6925-4511-9bda-8fa682138fb1");
    config.setSubscribeKey("sub-c-50acdc56-c1a3-11e6-b07a-0619f8945a4f");
    connection = new PubNub(config);

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            chatFrag = (GroupChatFragment) getSupportFragmentManager().findFragmentByTag("chat");
            taskFrag = (GroupTasksFragment) getSupportFragmentManager().findFragmentByTag("tasks");
            connection.history()
                    .channel(groupName)
                    .count(50)
                    .async(new PNCallback<PNHistoryResult>() {
                        @Override
                        public void onResponse(PNHistoryResult result, PNStatus status) {
                            for (PNHistoryItemResult item : result.getMessages()) {
                                String[] sForm = item.getEntry().getAsString().split(">>>>");
                                String m = "";
                                if (sForm.length > 2) {
                                    for (int x = 1; x < sForm.length; x++) {
                                        m += sForm[x];
                                    }
                                } else {
                                    m = sForm[1];
                                }

                                switch (sForm[0]) {
                                    case "chat":
                                        //chatFrag.adapter.add(m);
                                        break;
                                    case "addTask":
                                        if (taskFrag.adapter.getPosition(m) < 0) {
                                            //taskFrag.adapter.add(m);
                                        }
                                        break;
                                    case "deleteTask":
                                        if (taskFrag.adapter.getPosition(m) >= 0) {
                                            //taskFrag.adapter.remove(m);
                                        }
                                        break;
                                    case "groupCreated":
                                        //taskFrag.adapter.clear();
                                        //chatFrag.adapter.clear();
                                        break;
                                }
                            }
                        }
                    });
            connection.addListener(new SubscribeCallback() {
                @Override
                public void status(PubNub pubnub, PNStatus status) {
                    if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
                        Toast.makeText(getApplicationContext(), "You were disconnected!", Toast.LENGTH_SHORT).show();
                    } else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
                        if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
                            pubnub.publish().channel(groupName).message("chat>>>><ADMIN> User '" + nickName + "' Connected").async(new PNCallback<PNPublishResult>() {
                                @Override
                                public void onResponse(PNPublishResult result, PNStatus status) {
                                }
                            });
                        }
                    } else if (status.getCategory() == PNStatusCategory.PNReconnectedCategory) {
                        Toast.makeText(getApplicationContext(), "You were reconnected!", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void message(PubNub pubnub, PNMessageResult message) {
                    String[] sForm = message.getMessage().getAsString().split(">>>>");
                    String m = "";
                    if (sForm.length > 2) {
                        for (int x = 1; x < sForm.length; x++) {
                            m += sForm[x];
                        }
                    } else {
                        m = sForm[1];
                    }

                    switch (sForm[0]) {
                        case "chat":
                            //chatFrag.adapter.add(m);
                            break;
                        case "addTask":
                            //taskFrag.adapter.add(m);
                            connection.publish().channel(groupName).message("chat>>>><ADMIN> Task '" + m + "' added.").async(new PNCallback<PNPublishResult>() {
                                @Override
                                public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
                                }
                            });
                            break;
                        case "deleteTask":
                            //taskFrag.adapter.remove(m);
                            connection.publish().channel(groupName).message("chat>>>><ADMIN> Task '" + m + "' deleted.").async(new PNCallback<PNPublishResult>() {
                                @Override
                                public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
                                }
                            });
                            break;
                    }
                }

                @Override
                public void presence(PubNub pubnub, PNPresenceEventResult presence) {
                }
            });
            connection.subscribe().channels(java.util.Collections.singletonList(groupName)).execute();
        }
    }, 100);
}

public void goHome(View v) {
    Intent i = new Intent(getApplicationContext(), MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(i);
}

public void sendMessage(View v) {
    String message = ((EditText) findViewById(R.id.messageToSend)).getText().toString();
    connection.publish().channel(groupName).message("chat>>>><" + nickName + "> " + message).async(new PNCallback<PNPublishResult>() {
        @Override
        public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
        }
    });
}

public void deleteTask(View v) {
    final EditText input = new EditText(getApplicationContext());
    input.setTextColor(Color.BLACK);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    input.setLayoutParams(lp);
    new AlertDialog.Builder(this)
            .setTitle("Delete Task")
            .setMessage("What task would you like to delete?")
            .setView(input)
            .setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (taskFrag.adapter.getPosition(input.getText().toString()) < 0) {
                        connection.publish().channel(groupName).message("deleteTask>>>>" + input.getText().toString()).async(new PNCallback<PNPublishResult>() {
                            @Override
                            public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
                            }
                        });
                        dialog.cancel();
                    } else {
                        Toast.makeText(getApplicationContext(), "This task doesn't exist", Toast.LENGTH_SHORT).show();
                        dialog.cancel();
                    }
                }
            })
            .setNegativeButton(R.string.CANCEL, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            })
            .show();
}

public void addTask(View v) {
    final EditText input = new EditText(getApplicationContext());
    input.setTextColor(Color.BLACK);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    input.setLayoutParams(lp);
    new AlertDialog.Builder(this)
            .setTitle("Create New Task")
            .setView(input)
            .setMessage("What task would you like to create?")
            .setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (taskFrag.adapter.getPosition(input.getText().toString()) >= 0) {
                        connection.publish().channel(groupName).message("addTask>>>>" + input.getText().toString()).async(new PNCallback<PNPublishResult>() {
                            @Override
                            public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
                            }
                        });
                        dialog.cancel();
                    } else {
                        Toast.makeText(getApplicationContext(), "This task already exists", Toast.LENGTH_SHORT).show();
                        dialog.cancel();
                    }
                }
            })
            .setNegativeButton(R.string.CANCEL, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            })
            .show();
    }
}

我也考虑过使用静态变量等,但我不知道如何使用静态变量作为设置状态,仍然在方法中使用代码,因为方法和变量必须是静态的,PubNub调用不可能。

我也不能公开变量并做类似的事情,因为没有实例可以传递给片段,因为它们的设置方式。

有没有办法用片段到活动通信接口来做这件事呢?

编辑:从片段的第一个答案添加了代码,仍然导致空的适配器。

1 个答案:

答案 0 :(得分:1)

您的代码存在两个问题:

  1. 当您使用其他视图初始化子视图时,您将向Fragment返回另一个视图:

    View rootView = inflater.inflate(R.layout.fragment_group_tasks, container, false);
    

    是您应该返回的视图,而不是:

    return inflater.inflate(R.layout.fragment_group_chat, container, false);
    

    这样做:

    return rootView;
    
  2. 您没有使用已在Fragment类中重写的onAttach()方法。这样做:

    private Context context;
    

    并在您的onAttach方法中

    @Override
    public void onAttach(Context context) {
       super.onAttach(context);
       this.context = context; //when fragment is created, context will be initialised.
    }
    

    现在,使用您的适配器,而不是传递getContext(),传递初始化的context

    String[] items = {"item1", "item2"}
    adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, items);
    chatListView.setAdapter(adapter);