java – 具有ArrayList和ListView的Android Array Adapter在更改阵列列表时不会更新

我有一个包含ListView的屏幕的 Android应用程序,我正在使用它来显示设备列表.这些设备被保存在一个阵列中.

我试图使用ArrayAdapter在列表中的屏幕上显示数组中的内容.

当我第一次加载SetupActivity类时,它可以工作,但是在addDevice()方法中有一个新的设备添加,这意味着更新保存设备的阵列.

我正在使用notifyDataSetChanged(),它应该更新列表,但似乎不起作用.

public class SetupActivity extends Activity
{   
    private ArrayList<Device> deviceList;

    private ArrayAdapter<Device> arrayAdapter;

    private ListView listView;

    private DevicesAdapter devicesAdapter;

    private Context context;

    public void onCreate(Bundle savedInstanceState)  //Method run when the activity is created
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.setup);  //Set the layout

        context = getApplicationContext();  //Get the screen

        listView = (ListView)findViewById(R.id.listView);

        deviceList = new ArrayList<Device>();

        deviceList = populateDeviceList();  //Get all the devices into the list

        arrayAdapter = new ArrayAdapter<Device>(this,android.R.layout.simple_list_item_1,deviceList);

        listView.setAdapter(arrayAdapter);  
    }

    protected void addDevice()  //Add device Method (Simplified)
    {
        deviceList = createNewDeviceList();    //Add device to the list and returns an updated list

        arrayAdapter.notifyDataSetChanged();    //Update the list
}
}

任何人都可以看到我出错的地方吗?

解决方法

对于ArrayAdapter,notifyDataSetChanged仅在适配器上使用add,insert,remove和clear功能时有效.

>使用清除来清除适配器 – arrayAdapter.clear()
>使用Adapter.add并添加新形成的列表 – arrayAdapter.add(deviceList)
>调用notifyDataSetChanged

备择方案:

>新的设计师成立后重复这一步 – 但这是

arrayAdapter = new ArrayAdapter<Device>(this,deviceList);

>创建您自己的类派生自BaseAdapter和ListAdapter给你更多的灵活性.这是最推荐的.

以上是来客网为你收集整理的java – 具有ArrayList和ListView的Android Array Adapter在更改阵列列表时不会更新全部内容,希望文章能够帮你解决java – 具有ArrayList和ListView的Android Array Adapter在更改阵列列表时不会更新所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。