在列表视图中更新全局变量 (Android)



我有一个问题,我正在尝试解决。我创建了一个包含三个项目的列表,它还允许您按照本教程将图像添加到列表中......

在这里,按顺序,是我所做的。1. 我首先创建了一个名为"Item"的类来充当列表项的模型。

public class Item
{
  public int Id;
  public String IconFile;
  public String Name;
  public Item(int id, String iconFile, String name
  {
     Id = id;
     IconFile = iconFile;
     Name = name;
  }
}

。阿拉伯数字。然后,我创建了一个名为"Model"的类,为我的项目提供 ArrayList。但是,我不是简单地将文本放在列表名称中,而是包含全局变量。

http://www.debugrelease.com/2013/06/24/android-listview-tutorial-with-images-and-text/

public class Model extends Globals
{
    public static ArrayList<Item> Items; 
    public static void LoadModel() 
    {
        Items = new ArrayList<Item>();
        Items.add(new Item(1, "temperature_icon.png", "Temperature/Humidity" + temperature + "°C / " + humidity + "%"));
        Items.add(new Item(2, "gas_icon.png", "LPG" + lpg +" ppm"));
        Items.add(new Item(3, "alcohol_icon.png", "Alcohol" + alcohol + " ppm"));
    }  
    public static Item GetbyId(int id)
    {
        for(Item item : Items) 
        {
            if (item.Id == id) 
            {
                return item;
            }
        }
        return null;
    } 
}
.

3.(额外步骤)我添加了一个全局类来访问全局变量。

public abstract class Globals extends Activity
{
    static int temperature;
    static int humidity;
    static int lpg;
    static int alcohol;
}
.

4.将列表视图小部件添加到主活动布局。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
    <ListView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/listView" />
</LinearLayout>
.

5.添加自定义布局,因为我显示的不仅仅是文本。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center_vertical"
                android:minHeight="64dp">
    <ImageView
            android:id="@+id/imageView"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="9dp"
            android:layout_alignParentTop="true"/>
    <TextView
            android:layout_alignBottom="@+id/imageView"
            android:layout_width="97dp"
            android:layout_height="32dp"
            android:id="@+id/textView"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="66dp"
            android:layout_alignParentRight="true"
            android:gravity="center_vertical"/>
</RelativeLayout>
.

6.创建自定义适配器以显示数据

public class ItemAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final String[] Ids;
    private final int rowResourceId;
    public ItemAdapter(Context context, int textViewResourceId, String[] objects) {
        super(context, textViewResourceId, objects);
        this.context = context;
        this.Ids = objects;
        this.rowResourceId = textViewResourceId;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(rowResourceId, parent, false);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
        TextView textView = (TextView) rowView.findViewById(R.id.textView);
        int id = Integer.parseInt(Ids[position]);
        String imageFile = Model.GetbyId(id).IconFile;
        textView.setText(Model.GetbyId(id).Name);
        // get input stream
        InputStream ims = null;
        try {
            ims = context.getAssets().open(imageFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // load image as Drawable
        Drawable d = Drawable.createFromStream(ims, null);
        // set image to ImageView
        imageView.setImageDrawable(d);
        return rowView;
    }
}
.

7.加载模型,查找列表视图并在主活动中分配适配器。

public class MainActivity extends Globals 
{
    ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Model.LoadModel();
        listView = (ListView) findViewById(R.id.listView);
        String[] ids = new String[Model.Items.size()];
        for (int i= 0; i < ids.length; i++)
        {
            ids[i] = Integer.toString(i+1);
        }
        ItemAdapter adapter = new ItemAdapter(this,R.layout.row, ids);
        listView.setAdapter(adapter);
    }   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

.好的,现在你希望你明白我做了什么,我可以解释这个问题。我想根据我将通过 USB 接收的数据更新列表视图中的全局变量。但是,我似乎无法弄清楚如何做到这一点。我在主活动中尝试了以下代码,但它没有更新数据......

temperature = 5;
adapter.notifyDataSetChanged();

任何帮助将不胜感激。谢谢你的时间。

更新

因此,我创建了一个新的 ArrayList,其中包含要在 ListView 中显示的新数据。然后,我填充列表视图,将列表视图设置为适配器,然后调用 notifyDataSetChanged。但是,我的代码似乎仍然没有更新。非常欢迎任何建议!

public class MainActivity extends Activity 
{
    public static int temperature;
    public static int humidity;
    public static int lpg;
    public static int alcohol;
    ListView listView;
    ListView listView1;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Model.LoadModel();
        listView = (ListView) findViewById(R.id.listView);
        String[] ids = new String[Model.Items.size()];
        for (int i= 0; i < ids.length; i++)
        {
            ids[i] = Integer.toString(i+1);
        } 
        ItemAdapter adapter = new ItemAdapter(this,R.layout.row, ids);
        listView.setAdapter(adapter);

        //Simulate updated data that will come from USB
        temperature = 1; humidity = 60; lpg = 5000; alcohol = 500;
        //Create new ArrayList with updated data
        ArrayList<Item> Items1;
        Items1 = new ArrayList<Item>();
        Items1.add(new Item(1, "temperature_icon.png", "Temperature/Humidity" + temperature + "°C / " + humidity + "%"));
        Items1.add(new Item(2, "gas_icon.png", "LPG" + lpg +" ppm"));
        Items1.add(new Item(3, "alcohol_icon.png", "Alcohol" + alcohol + " ppm"));
        //Populate ListView
        listView1 = (ListView) findViewById(R.id.listView);
        String[] ids1 = new String[Items1.size()];
        for (int i= 0; i < ids1.length; i++)
        {
            ids1[i] = Integer.toString(i+1);
        }
        //Bind new ListView to Adapter
        listView1.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        listView1.invalidateViews();

    }

更新#2

现在,我既创建了一个新的列表视图

来显示更新的数据,又创建了一个可以将列表视图附加到的新适配器。但是,当我调用通知数据集更改();不显示新数据;我仍然看到原始数据。

public class MainActivity extends Activity 
{
    public static int temperature;
    public static int humidity;
    public static int lpg;
    public static int alcohol;
    ListView listView;
    ListView listView_new;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Model.LoadModel();
        listView = (ListView) findViewById(R.id.listView);
        String[] ids = new String[Model.Items.size()];
        for (int i= 0; i < ids.length; i++)
        {
            ids[i] = Integer.toString(i+1);
        } 
        ItemAdapter adapter = new ItemAdapter(this,R.layout.row, ids);
        listView.setAdapter(adapter);

        //--Simulate new data--//
        temperature = 1; humidity = 60; lpg = 5000; alcohol = 500;
        //Create new ArrayList with updated data
        ArrayList<Item> Items_new;
        Items_new = new ArrayList<Item>();
        Items_new.add(new Item(1, "temperature_icon.png", "Temperature/Humidity                  " + temperature + "°C / " + humidity + "%"));
        Items_new.add(new Item(2, "gas_icon.png", "LPG                                                   " + lpg +" ppm"));
        Items_new.add(new Item(3, "alcohol_icon.png", "Alcohol                                             " + alcohol + " ppm"));
        //Populate ListView
        listView_new = (ListView) findViewById(R.id.listView);
        String[] ids_new = new String[Items_new.size()];
        for (int j= 0; j < ids_new.length; j++)
        {
            ids_new[j] = Integer.toString(j+1);
        }
        //Create new adapter
        ItemAdapter adapter_new = new ItemAdapter (this,R.layout.row, ids_new);
        //Bind new ListView to Adapter
        listView_new.setAdapter(adapter_new);
        //listView_new.invalidateViews();
        adapter_new.notifyDataSetChanged();
    }

我认为您的主要活动更新代码不需要那么复杂;我让这个为我工作。它给了我一个包含更新的全局变量值的列表......

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Model.LoadModel();
    listView = (ListView) findViewById(R.id.listView);
    String[] ids = new String[Model.Items.size()];
    for (int i= 0; i < ids.length; i++)
    {
        ids[i] = Integer.toString(i+1);
    }
    ItemAdapter adapter = new ItemAdapter(this,R.layout.row, Model.Items);
    listView.setAdapter(adapter);
    temperature = 1; humidity = 60; lpg = 5000; alcohol = 500;
    Model.LoadModel();
    ItemAdapter adapter2 = new ItemAdapter(this,R.layout.row, Model.Items);
    listView.setAdapter(adapter2);
}

通过适配器将数据从数组馈送到列表视图。要更改列表视图的数据,您需要将新数据设置为适配器,然后在适配器上调用通知数据更改。

像这样:

mAdapter.setListData(mSubMenu1);
mAdapter.notifyDataSetChanged();

更新值后,创建已更新对象的新列表,并使用已更新项的新列表设置新适配器。您必须通过您将创建的"onClick"方法来执行此操作。

更新:

public class MainActivity extends ListActivity {
public static int temperature;
public static int humidity;
public static int lpg;
public static int alcohol;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    temperature = 4;
    humidity = 20;
    String item1 = "Temperature/Humidity" + temperature + "°C / " + humidity + "%";
    List myList = new ArrayList();
    myList.add(item1);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myList);
    setListAdapter(adapter);
}
public void onClick(View v) {
    temperature = 10;
    humidity = 30;
    String item1 = "Temperature/Humidity" + temperature + "°C / " + humidity + "%";
    List myList = new ArrayList();
    myList.add(item1);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myList);
    setListAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
}

将以下内容放入垂直方向的线性布局中...

 <Button 
    android:id="@+id/updateList"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Update List"
    android:onClick="onClick"/>
<ListView 
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

相关内容

  • 没有找到相关文章

最新更新