简体   繁体   English

如何在按钮单击事件上将项目添加到列表视图?

[英]How to add an item to a listview on a button click event?

I am coding in Android Studio and having some trouble. 我在Android Studio中进行编码,遇到了一些麻烦。 I have a button and a listview. 我有一个按钮和一个列表视图。 When the button is clicked it should add a hardcoded String to the arraylist. 单击该按钮时,应将一个硬编码的字符串添加到arraylist中。

List participants;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initParticipants();

    ListAdapter listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, participants);
    ListView participantList = findViewById(R.id.participantList);
    participantList.setAdapter(listAdapter);

}

public void changeJoinState(View view) {

    boolean checked = ((ToggleButton) view).isChecked();

    if(checked) {

        participants.add("example");

        Toast.makeText(MainActivity.this, "Joined event", Toast.LENGTH_SHORT)
                .show();

    } else {

        Toast.makeText(MainActivity.this, "Left event", Toast.LENGTH_SHORT)
                .show();

    }

}

void initParticipants() {
    participants = new ArrayList<String>();
    participants.add("Creator");
}

After updating the list you should call notifyDataSetChanged to see the updated UI. 更新列表后,您应该调用notifyDataSetChanged来查看更新的UI。 Make the ListView variable at class level. 在类级别上使ListView变量。 Also call notifyDataSetChanged after adding string to list. 在将字符串添加到列表后,还要调用notifyDataSetChanged。

participants.add("example");
listAdapter.notifyDataSetChanged();

Use notifyDataSetChanged() 使用notifyDataSetChanged()

void initParticipants() {
   participants = new ArrayList<String>();
   participants.add("Creator");
   participants.notifyDataSetChanged();
}

You need to change if conditional block code with below code 您需要使用以下代码更改条件块代码

 if(checked) {

    participants.add("example");
     participantList.notifyDataSetChanged();
    Toast.makeText(MainActivity.this, "Joined event", Toast.LENGTH_SHORT)
            .show();

} 

Whenever there is a change in a list, adapter needs to be notified via notifyDataSetChanged() method 每当列表中有更改时,就需要通过notifyDataSetChanged()方法通知适配器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM