[英]Passing an arraylist from an activity to a java class in Android
我在MainActivity中有一個arraylist,我有一個java類,它不是一個活動 。 我如何將這個arraylist傳遞給這個班級? 我的arraylist:
public List<String> types = new ArrayList<String>();
我填寫了MainAcitivity。 然后我必須在一個名為ExpandableListAdapter的java類中使用。 這是java類的一部分,我必須在其中進行更改,我嘗試創建新的活動對象,但它不起作用。
public class ExpandableListAdapter extends BaseExpandableListAdapter {
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
MainActivity m=new MainActivity();
Integer[] mIcons = {R.drawable.car_1,R.drawable.car_2,R.drawable.car_3,R.drawable.car_4,R.drawable.car_5,R.drawable.car_6,R.drawable.car_7,R.drawable.car_8,R.drawable.car_9,R.drawable.car_10}
Integer[] mIcons_2 = new Integer [m.types.size()];
for(int i=0; i<m.types.size(); i++){
mIcons_2[i]= mIcons[ Integer.parseInt(m.types.get(i))];
}
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView iconn =(ImageView)convertView.findViewById(R.id.thumbNail);
iconn.setImageResource(mIcons_2[childPosition]);
TextView txtListChild = (TextView) convertView
.findViewById(R.id.textView);
txtListChild.setTextColor(Color.BLUE);
txtListChild.setText(childText);
return convertView;
}
我創建了一個帶有可擴展列表視圖的導航抽屜,我也嘗試在每個項目上放置不同的圖標。 這個ExpandableListAdapter類就是這個,但我的問題是如何將MainList中的ArrayList類型傳遞給ExpandableListAdapter java類? 我知道使用intent時將一個活動的值傳遞給其他活動但我不知道將一個活動傳遞給java類。
使用構造函數傳遞它,如下所示:
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private final List<String> typesList;
public ExpandableListAdapter(List<String> typesList) {
this.typesList = typesList;
}
...
...
}
或者,您也可以使用如下設置器:
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private List<String> typesList;
public void setTypesList(List<String> typesList) {
this.typesList = typesList;
}
...
...
}
然后你可以通過調用adapter.setTypesList()
隨時設置types
在適配器類中聲明一個List
// Declaration :
public List<String> list = new ArrayList<String>();
構造函數將幫助您將arraylist作為params傳遞。
ExpandableListAdapter(List<String> types){
this.list = types
}
您可以按如下方式傳遞arraylist:
new ExpandableListAdapter(types);
我建議你調用非活動類的構造函數,將數組List作為參數讓我假設我的非活動類是B類
B obj=new B(Activity context,types);
並且不要忘記在B類中聲明相同的構造函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.