我如何根据来自板载 SQLite 数据库的数据对我的 ListView 使用不同的布局?

How can I use different layouts with my ListView depending on data coming from the on-board SQLite database?

我的 android 应用程序有一个简单的聊天功能。聊天记录存储在板载 SQLite 数据库中。我正在使用带有 SimpleCursorAdapter 的 ListView 来显示聊天。这是我的:

public class Chat extends Fragment {
    private View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        rootView = inflater.inflate(R.layout.chat, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View rootView, Bundle savedInstanceState){
        super.onViewCreated(rootView, savedInstanceState);
        displayChats();
    }

    public void displayChats(){
        DatabaseHelper databaseHelper = new DatabaseHelper(getActivity());
        Cursor chatCursor = databaseHelper.getChatsCursor();
        String[] fromColumns = {"messageInfo","messageText"};
        int toViews{R.id.message_info, R.id.message_text};
        SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.line_of_chat, chatCursor, fromColumns, toViews, 0);
        ListView listView = (ListView) rootView.findViewById(R.id.chat_text_display);
        listView.setAdapter(simpleCursorAdapter);
        databaseHelper.close();
    }
}

我有一个聊天模型,它有一个名为 localFlag 的布尔值作为其字段之一。如果聊天是从设备发送的,localFlag 设置为 true(或 1),如果聊天是从设备外部接收的,localFlag 设置为 false(或 0)。

我的SQL电话:

public static final String GET_ALL_CHATS = "select _id, localFlag, messageText, messageInfo from ChatTable";

public Cursor getChatsCursor(){
    SQLiteDatabase sqliteDB = this.getReadableDatabase();
    return sqliteDB.rawQuery(GET_ALL_CHATS, null);
}

我想做的是如果设置了本地标志,我想用这个:

SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.outgoing_line_of_chat, chatCursor, fromColumns, toViews, 0);

如果没有设置本地标志,我想使用这个:

SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.incoming_line_of_chat, chatCursor, fromColumns, toViews, 0);

注意我想使用 R.layout.outgoing_line_of_chatR.layout.incoming_line_of_chat

我怎样才能完成这个?

使用 getItemViewType() and getViewTypeCount() in your adapter to inform ListView that there are different row types being displayed, so that it can provide the proper view as the convertView argument to getView(). Refer to this answer, and also to a video called The World of ListView 以获得更完整的解释。

编辑

您必须子类化 SimpleCursorAdapter(尽管您可能想要子类化 CursorAdapter)以覆盖这些方法。


旁白:您可能要考虑使用 RecyclerView 而不是 ListView。原理是一样的,但是使用 RecyclerView 适配器你只需要实现 getItemViewType().