【问题标题】:List Adapter Only Adding 1 Item to List View列表适配器仅将 1 项添加到列表视图
【发布时间】:2016-03-01 22:00:18
【问题描述】:

我正在为应用程序创建一个 cmets 部分,每次单击“评论”按钮时,我都想将评论添加到我的 ListView。

不幸的是,我的代码只允许我向我的 ListView 添加 1 条评论。每次我键入并单击添加评论按钮时,ListView 都保持静态为 1 项。

我认为我必须修改客户适配器中的 getCount() 方法,但我想寻求帮助

下面是我的代码:

public class Discussion_Activity extends AppCompatActivity {

private EditText mUserComment;
private String mUserID;
private ImageView mUserAvatar;
private ListView mPollComments;
private ArrayAdapter<Comments> mCommentAdapter;
private Firebase mBaseRef;
private int mCommentCounter;

private static final String FIREBASE_URL = "https://fan-polls.firebaseio.com/";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_discussion);
    Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);

    mBaseRef = new Firebase(FIREBASE_URL);

    mUserComment = (EditText) findViewById(R.id.user_comment);
    mUserAvatar = (ImageView) findViewById(R.id.profile_image_avatar);
    mPollComments = (ListView) findViewById(R.id.poll_comments_list);
    final ArrayList<Comments> pollComments = new ArrayList<Comments>();
    mCommentAdapter = new ListAdapter(getApplicationContext(),R.layout.individual_comment, pollComments);
    mPollComments.setAdapter(mCommentAdapter);
    mCommentCounter = 0;
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);


    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_comment_button);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pollComments.add(mCommentCounter, new Comments(mUserAvatar, mBaseRef.getAuth().getUid(), mUserComment.getText().toString() ));
            mCommentAdapter.notifyDataSetChanged();
            mCommentCounter++;
            hideKeyboard(view);
            mUserComment.setText("");
        }
    });
}

public void hideKeyboard(View view) {
    InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

public class ListAdapter extends ArrayAdapter<Comments> {

    public ListAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    public ListAdapter(Context context, int resource, List<Comments> items) {
        super(context, resource, items);
    }

    @Override
    public int getCount() {
        return mCommentCounter;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;

        if (v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            v = vi.inflate(R.layout.individual_comment, null);
        }

        Comments p = getItem(position);

        if (p != null) {
            TextView userID = (TextView) v.findViewById(R.id.user_ID);
            TextView userComment = (TextView) v.findViewById(R.id.user_comment);

            if (userID != null) {
                userID.setText(p.getUserID());
            }

            if (userComment != null) {
                userComment.setText(p.getUserComment());
            }
        }


        return v;
    }

  }

}

XML

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/toolbar" />

    <ImageView
        android:id="@+id/poll_image"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".475"
        android:background="@drawable/heyward"
        android:scaleType="fitXY" />

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".2"
        android:orientation="horizontal">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:layout_margin="10dp"
            android:background="@drawable/textlines">

            <de.hdodenhof.circleimageview.CircleImageView
                android:id="@+id/profile_image_avatar"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="8dp"
                android:src="@drawable/empty_avatar_256x256"
                app:civ_border_color="#FF000000"
                app:civ_border_width="2dp" />

            <EditText
                android:id="@+id/user_comment"
                android:layout_width="match_parent"
                android:layout_height="60dp"
                android:layout_gravity="bottom"
                android:layout_marginEnd="60dp"
                android:layout_marginLeft="65dp"
                android:layout_marginRight="60dp"
                android:layout_marginStart="65dp"
                android:hint="Enter a comment....."
                android:inputType="textCapSentences|textMultiLine"
                android:scrollHorizontally="false"
                android:textSize="16sp" />

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/add_comment_button"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_gravity="end|center_vertical"
                android:layout_marginEnd="4dp"
                android:layout_marginRight="4dp"
                android:clickable="true" />


        </FrameLayout>

    </LinearLayout>

    <ScrollView
        android:layout_marginStart="30dp"
        android:layout_marginLeft="30dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.40">

        <ListView
            android:id="@+id/poll_comments_list"
            android:divider="@drawable/list_divide"
            android:dividerHeight="1px"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">


        </ListView>


    </ScrollView>

</LinearLayout>

【问题讨论】:

    标签: android listview scrollview


    【解决方案1】:

    您在增加计数之前调用notifyDataSetChanged()。增加notifyDataSetChanged()前的计数器应该会生效

    mCommentCounter++;
    mCommentAdapter.notifyDataSetChanged();
    

    你也可以使用适配器add 方法,这样你就不需要重写getCount 并拥有一个计数器,也不需要添加索引。 Adapter add 方法已经添加了item并调用notifyDataSetChanged

    adapter.add(new Comments(....));
    

    还有下面提到的滚动视图/列表视图问题

    【讨论】:

    • 其实我觉得答案是这个和下面答案的结合,谢谢!
    【解决方案2】:

    问题是您将项目直接添加到ListView。您应该管理Comments 的全局列表并与您的ListAdapter 共享它。

    请注意,这种方式根本不需要mCommentCounter 变量。

    然后,将新的 cmets 添加到此列表并通知您的适配器。下面我为您提供了更新的代码。让我知道它是否适合你。

    public class Discussion_Activity extends AppCompatActivity {
    
        private EditText mUserComment;
        private String mUserID;
        private ImageView mUserAvatar;
        private ListView mPollComments;
        private List<Comments> mComments;
        private ArrayAdapter<Comments> mCommentAdapter;
        private Firebase mBaseRef;
    
        private static final String FIREBASE_URL = "https://fan-polls.firebaseio.com/";
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_discussion);
            Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
            setSupportActionBar(toolbar);
    
            private List<Comments> mComments = new ArrayList<Comments>;
            mBaseRef = new Firebase(FIREBASE_URL);
    
            mUserComment = (EditText) findViewById(R.id.user_comment);
            mUserAvatar = (ImageView) findViewById(R.id.profile_image_avatar);
            mPollComments = (ListView) findViewById(R.id.poll_comments_list);
            mCommentAdapter = new ListAdapter(getApplicationContext(),R.layout.individual_comment, mComments);
            mPollComments.setAdapter(mCommentAdapter);
            mCommentCounter = 0;
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    
    
            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_comment_button);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mComments.add(new Comments(mUserAvatar, mBaseRef.getAuth().getUid(), mUserComment.getText().toString()));
                    mCommentAdapter.notifyDataSetChanged();
                    hideKeyboard(view);
                    mUserComment.setText("");
                }
            });
        }
    
        public void hideKeyboard(View view) {
            InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    
        public class ListAdapter extends ArrayAdapter<Comments> {
    
            public ListAdapter(Context context, int textViewResourceId) {
                super(context, textViewResourceId);
            }
    
            public ListAdapter(Context context, int resource, List<Comments> items) {
                super(context, resource, items);
            }
    
            @Override
            public int getCount() {
                return mComments.size();
            }
    
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
    
                View v = convertView;
    
                if (v == null) {
                    LayoutInflater vi;
                    vi = LayoutInflater.from(getContext());
                    v = vi.inflate(R.layout.individual_comment, null);
                }
    
                Comments p = getItem(position);
    
                if (p != null) {
                    TextView userID = (TextView) v.findViewById(R.id.user_ID);
                    TextView userComment = (TextView) v.findViewById(R.id.user_comment);
    
                    if (userID != null) {
                        userID.setText(p.getUserID());
                    }
    
                    if (userComment != null) {
                        userComment.setText(p.getUserComment());
                    }
                }
    
                return v;
            }
    
        }
    
    }
    

    我注意到现在评论ScrollView / ListView。这也是一个问题。您只能保留ListView

    【讨论】:

    • 在主类中有一个客户适配器类是否总是常规的?我原本打算在模型文件夹中创建一个单独的类,但意识到我可能需要一些变量,因此发现组合这些类是合适的
    • @tccpg288 你也可以使用单独的类。如果您需要在不同的布局之间共享相同的适配器(例如,在活动和对话框中显示 cmets),使用分离的类尤其有用。重要的是您的 Activity 和 Adapter 保持对相同项目列表的引用,这样如果您在 Activity 中修改它,您也会在适配器中应用更改。
    • 感谢您及时、乐于助人的回复。我不确定我是否会共享适配器,但现在我明白了封装适配器以备将来使用的目的。
    • @tccpg288 很高兴我能帮助您了解更多内容 :)
    【解决方案3】:

    将一个可滚动元素添加到另一个可滚动元素是一种不好的做法。如果没有肮脏的黑客,你就无法让它工作。

    所以删除你的ScrollView 和你的ListView 将按预期工作

    【讨论】:

    • 这可行,但现在我在适配器中的新项目与我屏幕上的其他视图重叠
    • @tccpg288,只需将其他视图设置为您的 ListView 的 HEADER。所以你的布局必须只包含带有标题的 ListView。
    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多