I am building a dynamic view in a non-activity class, which is called by my activity class to populate a section of my main view. My problem occurs within this “sub view”
I have an onclicklistener which adds items to a listview, but I cannot call notifydatasetchanged on the adapter from the onclicklistener, because the adapter object needs to be declared final, which won’t work.
What am I doing wrong?
Here’s my code: (I would like to notifydatasetchanged right after newComment(o) )
public RelativeLayout getCommentsView(final Object o) {
RelativeLayout view = new RelativeLayout(mContext);
ImageView background = new ImageView(mContext);
background.setImageResource(R.drawable.background);
background.setScaleType(ScaleType.FIT_START);
LinearLayout comments = new LinearLayout(mContext);
comments.setOrientation(LinearLayout.VERTICAL);
comments.setPadding(8,20,8,0);
LinearLayout titleBar = new LinearLayout(mContext);
ImageView addButton = new ImageView(mContext);
addButton.setImageResource(R.drawable.ic_menu_add);
titleBar.setClickable(true);
titleBar.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View view) {
newComment(o);
}
});
TextView title = new TextView(mContext);
title.setText(mContext.getString(R.string.comments));
title.setPadding(10,5,0,0);
title.setTextSize(18);
title.setTextColor(Color.WHITE);
if (mContext instanceof LocationActivity) {
title.setTextColor(Color.parseColor("#33b5e5"));
} else if (mContext instanceof TrailActivity) {
title.setTextColor(Color.parseColor("#AA66CC"));
}
LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
titleBar.addView(title,layout);
layout = new LinearLayout.LayoutParams(48,48);
titleBar.addView(addButton,layout);
TextView divider = new TextView(mContext);
divider.setBackgroundResource(R.drawable.divider);
ListView commentsList = new ListView(mContext);
commentsList.setBackgroundColor(Color.TRANSPARENT);
commentsList.setCacheColorHint(Color.TRANSPARENT);
commentsList.addHeaderView(titleBar);
commentsList.addFooterView(divider);
CommentsListAdapter commentsListAdapter = new CommentsListAdapter(mContext,R.layout.comments_list_item,getCommentsFor(o));
commentsList.setAdapter(commentsListAdapter);
comments.addView(commentsList);
view.addView(background);
view.addView(comments);
return view;
}
make your non activity class constructor receive the adapter reference and save it on instance variable in your non activity class.
Then it can be used everywhere within your class without declaring it final