更新listview中的全局变量(Android)

时间:2013-11-13 01:20:39

标签: android android-listview global-variables android-arrayadapter

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

在这里,按顺序,就是我所做的。 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;
  }
}

0.2。然后我创建了一个名为“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;
    } 
}

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

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

0.4。将listview小部件添加到主要活动布局。

<?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>

0.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>

0.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;

    }

}

0.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中显示的新数据。然后我填充ListView,将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

我现在都创建了一个新的列表视图来显示更新的数据,并创建了一个新的适配器,我可以附加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 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();

    }

3 个答案:

答案 0 :(得分:0)

您可以通过适配器将数据从阵列提供给列表视图。要更改列表视图的数据,您需要将新数据设置为适配器,然后在适配器上调用notifydatachanged。

这样的事情:

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

答案 1 :(得分:0)

更新值后,创建更新对象的新列表,并使用新的更新项列表设置新适配器。您必须通过您将创建的“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;
}

}

将以下内容放入具有垂直方向的LinearLayout ......

 <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"/>

答案 2 :(得分:0)

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

@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);

}