如何在其他活动中向ListView添加值?

时间:2017-04-06 14:23:45

标签: java android listview

在我的应用中,我有一个,其中包含一个名为“添加到收藏夹”的按钮,当我点击该按钮时,我想将值发送到另一个活动中的,值我正在尝试添加从中检索,有人可以帮忙吗?

这就是我所拥有的:

.setNegativeButton("Favoritos",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){

        int position=(int)marker.getTag();
        final ListView listReprFav=(ListView)findViewById(R.id.listaFavRepresentantes);
            ListAdapter adapterReprFav=new SimpleAdapter(
            (MapsActivity.this),
            listaRepresentantes,
            R.layout.list_item_representantes_fav,
            new String[]{listaOportunidades.get(position).get("Designacao"),listaOportunidades.get(position).get("Morada")},
            new int[]{R.id.DesignacaoReprFav,R.id.Cidade});

        listReprFav.setAdapter(adapterReprFav);
        }
}

1 个答案:

答案 0 :(得分:0)

首先创建一个Global类,它将保持ListView活动的上下文。

public class Global extends Application {
    Context context;
}

然后,您需要在包含ListView的活动中创建一个公共方法:

public class ListViewActivity extends Activity {

    public List<String> listItems;
    public ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ....

        Global.context = this; //Set context in Global.

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

        adapter = new ArrayAdapter<String>
        (this, android.R.layout.simple_list_item_1, android.R.id.text1, 
        listItems);


        listView.setAdapter(adapter);
    }

    //This method will add a new String to listItems array and 
    //notifies adapter for changes.
    public void addItemAndRefreshListView(String[] newItems){
        for(int i = 0; i<newItems.length; i++){
            listItems.add(newItem);
        }
        adapter.notifyDataSetChanged();
    }

}

之后,在onClick of Dialog按钮中:

.setNegativeButton("Favoritos",new DialogInterface.OnClickListener(){
    public void onClick(DialogInterface dialog,int which){
        if(Global.context != null){
            ((ListViewActivity) Global.context).addItemAndRefreshListView(values);
        }
    }
}