here i call the customdialog through my parent activity.. where as the dialog is in another activity contains listview...from that dialog i transfer a selected content from listview.. but fail to achieve my target.. and tried so many way.. can any one assist me to achieve it.
Note: i got error in on listitemclick listener...
customdialog.class
public class CustomizeDialog extends Dialog {
org.me.dailogfrmchildact.MainActivity ma;
Button cancelButton;
ListView list;
int item_pos;
public CustomizeDialog(Context context) {
super(context);
Context cs = context;
/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog);
ma=new MainActivity();
list = (ListView) findViewById(R.id.list);
cancelButton = (Button) findViewById(R.id.OkButton);
ListviewContent.add("item1");
ListviewCount.add("20");
ListviewContent.add("item2");
ListviewCount.add("30");
list.setAdapter(new ListViewAdapter(cs));
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
item_pos = pos;
System.out.println("===========item_pos" + pos);
ma.txt.setText(ListviewContent.get(pos).toString());
dismiss();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
dismiss();
}
});
}
private static ArrayList<String> ListviewContent = new ArrayList<String>();
private static ArrayList<String> ListviewCount = new ArrayList<String>();
private static class ListViewAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ListViewAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return ListviewContent.size();
}
public Object getItem(int position) {
return position;
}
public String getCount(int position) {
return ListviewCount.get(position);
}
public String[] getSizeType(int position) {
String[] str = new String[2];
str[0] = ListviewContent.get(position);
str[1] = ListviewCount.get(position);
return str;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ListContent holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listviewinflate, null);
holder = new ListContent();
holder.text = (TextView) convertView.findViewById(R.id.TextView01);
holder.text.setCompoundDrawables(null, null, null, null);
holder.count = (TextView) convertView.findViewById(R.id.TextView02);
holder.count.setCompoundDrawables(null, null, null, null);
convertView.setTag(holder);
} else {
holder = (ListContent) convertView.getTag();
}
holder.text.setText(ListviewContent.get(position));
holder.count.setText(ListviewCount.get(position));
return convertView;
}
static class ListContent {
TextView text;
TextView count;
}
}
}
mainactivity.class:
public class MainActivity extends Activity {
org.me.dailogfrmchildact.CustomizeDialog cd;
Button btn;
EditText txt;
CustomizeDialog customizeDialog;
boolean click = false;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
cd = new CustomizeDialog(this);
btn = (Button) findViewById(R.id.btn1);
txt = (EditText) findViewById(R.id.txt1);
/** Display Custom Dialog */
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
customizeDialog = new CustomizeDialog(MainActivity.this);
customizeDialog.show();
}
});
}
}
The problem is you're creating a new MainActivity in your CustomizeDialog when you should be using the one that created the CustomizeDialog in the first place.
Have CustomizeDialog take in a MainActivity instead of Context and set ma equal to that.
Edit:
Change CustomizeDialog's constructor to:
public CustomizeDialog(MainActivity mainActivity) {
super(mainActivity);
ma = mainActivity; // Instead of ma = new MainActivity()
// everything else is the same
}
Related
I'm trying to crate something that creates a new ListView item on button press, I thing I have somewhere some bug, but as I'm new to this topic I don't know where.
I've tried rewriting the code several times, I've tried to use notifyDataSetChanged(); - it does nothing
tried googling looking on other topics here...
Here is my MainActivity.java:
public Button btn;
private ListView lv;
private CustomeAdapter customeAdapter;
public ArrayList<EditModel> editModelArrayList;
int populateListMaxNum =3;
int listNumber = populateListMaxNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView);
btn = (Button) findViewById(R.id.btn);
editModelArrayList = populateList();
customeAdapter = new CustomeAdapter(this,editModelArrayList);
lv.setAdapter(customeAdapter);
/* TODO activate button */
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addToList();
Toast.makeText(getApplicationContext(), "button", Toast.LENGTH_LONG).show();
}
});
}
private ArrayList<EditModel> populateList(){ //this part works perfectly
ArrayList<EditModel> list = new ArrayList<>();
for(int i = 0; i < populateListMaxNum; i++){
EditModel editModel = new EditModel();
//editModel.setEditTextValue(String.valueOf(i));
list.add(editModel);
}
return list;
}
/*TODO make it work = expand */
private void addToList(){ // this part doesn't work nor it doesn't fail
EditModel editModel = new EditModel();
editModelArrayList.add(editModel);
customeAdapter.notifyDataSetChanged();
}
}
Here is my CustomeAdapter.java class:
public class CustomeAdapter extends BaseAdapter {
private Context context;
public static ArrayList<EditModel> editModelArrayList;
public CustomeAdapter(Context context, ArrayList<EditModel> editModelArrayList) {
this.context = context;
CustomeAdapter.editModelArrayList = editModelArrayList;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return editModelArrayList.size();
}
#Override
public Object getItem(int position) {
return editModelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lv_item, null, true);
holder.editText = convertView.findViewById(R.id.editid);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
holder.editText.setText(editModelArrayList.get(position).getEditTextValue());
holder.editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
editModelArrayList.get(position).setEditTextValue(holder.editText.getText().toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return convertView;
}
private class ViewHolder {
protected EditText editText;
}
}
I expect to create a new list item (EditText + TextView) but nothing happens (except the Toast message)
(After some tweaks the app crashes due to arrayindexoutofboundsexception length=3 index=3 error, but not in this setting)
here are up to all files nessessary: https://gist.github.com/Atingas/52778a247a78131e5b8cb0239fa30965
Main linear layout in lv_item.xml has match_parent height. Try change it to wrap_content. It seems like one row is just taking whole screen.
I have a question about passing clicked cardview data to activity, and here the full story :
I have an Activity called "Details", which contains 2 TextViews in it's layout, Title & Description .
I have setup a fragment ( tab_1 ) which contain the recyclerview codes and the the items data, each item of those contain : title & description .
What i want :
When the user click the item, it will open the Details Activity, and change Details layout title, with clicked item title, and the same for description .
I've manged to create the other activity as an example, and made intent to start it, plus adding "addOnTouchlistener" thanks to Stackoverflow, i've found the way to make it .
So, how to make this alive? I've tried many ways of the available answers on Stackoverflow, but all of them not working, or not related to my request .
Here are my files :
itemsdata.java :
public class itemsdata {
int CatPic;
String title;
String Descr;
int Exapnd;
int expand_no;
tab_1.java ( fragment )
public class tab_1 extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView mRecyclerView;
public RecyclingViewAdapter adapter;
private Activity context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.tab_1, container, false);
mRecyclerView = (RecyclerView)layout.findViewById(R.id.recycler_view);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener
(getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(view.getContext(), DetailsActivity.class);
view.getContext().startActivity(i);
}
}));
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new RecyclingViewAdapter(getActivity(),Listed());
mRecyclerView.setAdapter(adapter);
return layout;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String query) {
final List<itemsdata> filteredModelList = filter(Listed(), query);
adapter.animateTo(filteredModelList);
mRecyclerView.scrollToPosition(0);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return true;
}
private List<itemsdata> filter(List<itemsdata> models, String query) {
query = query.toLowerCase();
final List<itemsdata> filteredModelList = new ArrayList<>();
for (itemsdata model : models) {
final String text = model.title.toLowerCase();
if (text.contains(query)) {
filteredModelList.add(model);
}
}
return filteredModelList;
}
public List<itemsdata> Listed()
{
//Titles Strings
String sys_title1 = getString(R.string.system_item_title_1);
String sys_title2 = getString(R.string.system_item_title_2);
String sys_title3 = getString(R.string.system_item_title_3);
//Description Strings
String sys_descr1 = getString(R.string.system_item_desc_1);
String sys_descr2 = getString(R.string.system_item_desc_2);
String sys_descr3 = getString(R.string.system_item_desc_3);
//Adding New Cards
List<itemsdata> data = new ArrayList<>();
//Categories Icons New Items ** Make It The Same
int[] icons = {
R.drawable.facebook_icon ,
R.drawable.twitter_icon ,
R.drawable.twitter_icon
};
//Expand Button New Items
int[] expandbutton = {
R.drawable.expanded ,
R.drawable.expanded ,
R.drawable.expanded
};
//UnExpand Button New Items
int[] unexpandbutton = {
R.drawable.ca_expand ,
R.drawable.ca_expand ,
R.drawable.ca_expand
};
//Titles New Items
String[] titles = {
sys_title1 ,
sys_title2 ,
sys_title3
};
//Description New Items
String[] Description = {
sys_descr1 ,
sys_descr2 ,
sys_descr3
};
for(int i = 0;i<titles.length && i < icons.length && i < Description.length && i < unexpandbutton.length && i < expandbutton.length ; i++)
{
itemsdata current = new itemsdata();
current.CatPic = icons[i];
current.title = titles[i];
current.Descr = Description[i];
current.expand_no = unexpandbutton[i];
current.Exapnd = expandbutton[i];
data.add(current);
}
return data;
}
}
Details Activity :
public class DetailsActivity extends AppCompatActivity{
TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
title = (TextView)findViewById(R.id.details_title);
}
EDIT : I've made it, i have added a button which open the fragment, and passed the data, in the Adapter, but i want it via tab_1.java, not the Adapter, i mean i want to click on the item to open the fragment, not on a button, here a snap from my Adapter code ( i've added it in OnBindViewHolder )
I've setup a OnClick and implemented the Vew.setOnClick ..etc, but when i click the item, nothing happen.
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(),DetailsActivity.class);
v.getContext().startActivity(i);
}
});
//Referencing Data
final itemsdata currentobject = mdata.get(position);
//Referencing Items
holder.ProbTitle.setText(currentobject.title);
holder.ProbDescr.setText(currentobject.Descr);
holder.CategoryPic.setImageResource(currentobject.CatPic);
holder.ExpandButton.setImageResource(currentobject.Exapnd);
holder.ExpandNoButton.setImageResource(currentobject.expand_no);
//What Happen When You Click Expand Button .
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",holder.ProbTitle.getText().toString());
v.getContext().startActivity(i);
}
}
);
public static class MyRecycleViewHolder extends RecyclerView.ViewHolder
{
SwipeLayout swipeLayout;
//Defining Items .
TextView ProbTitle;
ImageButton ExpandButton;
TextView ProbDescr;
ImageButton ExpandNoButton;
ImageView CategoryPic;
/*
TextView Card_Star;
TextView Card_UnStar;
*/
TextView Card_Share;
//Referencing Resources
public MyRecycleViewHolder(final View itemView) {
super(itemView);
ProbTitle = (TextView) itemView.findViewById(R.id.prob_title);
CategoryPic = (ImageView) itemView.findViewById(R.id.cat_pic);
ProbDescr = (TextView) itemView.findViewById(R.id.prob_descr);
ExpandButton = (ImageButton) itemView.findViewById(R.id.expand_button);
ExpandNoButton = (ImageButton) itemView.findViewById(R.id.expand_no_button);
/*
Card_Star = (TextView) itemView.findViewById(R.id.card_star);
Card_UnStar = (TextView) itemView.findViewById(R.id.card_unstar);
*/
Card_Share = (TextView) itemView.findViewById(R.id.card_share);
swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
}
create an Interface inside your adapter containing methods. And while implementing your Adapter, those methods will be implemented in your activity and you can perform whatever action you want.
public class Adapter extends RecyclerView.Adapter<MyRecycleViewHolder> {
public interface Callbacks {
public void onButtonClicked(String titleKey);
}
private Callbacks mCallbacks;
public Adapter() {
}
#Override
public MyRecycleViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_details, null);
return new MyRecycleViewHolder(v);
}
#Override
public void onBindViewHolder(final MyRecycleViewHolder holder, final int i) {
holder.ExpandButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallbacks != null) {
mCallbacks.onButtonClicked(holder.ProbTitle.getText().toString());
}
}
});
}
#Override
public int getItemCount() {
return;
}
public void setCallbacks(Callbacks callbacks) {
this.mCallbacks = callbacks;
}
}
you may try do this on your onItemClick()
Intent i = new Intent(view.getContext(), DetailsActivity.class);
i.putExtra("title", yourTitle);
i.putExtra("description", yourDescription);
view.getContext().startActivity(i);
and when oncreate in your DetailActivity,do this
String title = getIntent().getStringExtra("title");
String description = getIntent().getStringExtra("description");
so you can pass title and description to DetailActivity
IMO, you implement setOnClickListener inside Adapter of RecyclerView. You can refer to my following sample code, then apply its logic to your code. Hope it helps!
public class MyRVAdapter extends RecyclerView.Adapter<MyRVAdapter.ViewHolder> {
Context mContext;
List<String> mStringList;
public MyRVAdapter(Context mContext, List<String> mStringList) {
this.mContext = mContext;
this.mStringList = mStringList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView1 = (TextView) v.findViewById(R.id.textView1);
TextView textView2 = (TextView) v.findViewById(R.id.textView2);
Bundle bundle = new Bundle();
bundle.putString("key1", textView1.getText().toString());
bundle.putString("key2", textView2.getText().toString());
passToAnotherActivity(bundle);
}
});
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// do something...
}
#Override
public int getItemCount() {
if (mStringList != null) {
return mStringList.size();
}
return 0;
}
private void passToAnotherActivity(Bundle bundle) {
if (mContext == null)
return;
if (mContext instanceof MainActivity) {
MainActivity activity = (MainActivity) mContext;
activity.passToAnotherActivity(bundle); // this method must be implemented inside `MainActivity`
}
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ViewHolder(View itemView) {
super(itemView);
// do something...
}
#Override
public void onClick(View v) {
}
}
}
First of all make your "itemsdata" object to implement Parcelable. You can check it here . In your onItemClick method you pass the object to your Details activity using intent.putExtra("key",listOfDataItems.get(position));
In your DetailsActivity you can get your custom object with getParcelable("key")
All above methods worked, but kinda long, so this one worked for me :
Cardview cardview;
cardView = (CardView)itemView.findViewById(R.id.cv);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent (view.getContext(), DetailsActivity.class);
i.putExtra("TitleKey",ProbTitle.getText().toString());
i.putExtra("DescrKey",ProbDescr.getText().toString());
view.getContext().startActivity(i);
}
});
And in Details.java :
TextView title;
TextView Descr;
title = (TextView)findViewById(R.id.details_title);
Descr = (TextView)findViewById(R.id.details_descr);
String titleresult = result.getExtras().getString("TitleKey");
String Descrresult = result.getExtras().getString("DescrKey");
title.setText(titleresult);
Descr.setText(Descrresult);
I have a simple task that is to take string input from Dialog then add it to listview with checkbox .
What happening is that , I entered test through dialog but it is not displaying after adding and also code doesn't have any error during runtime .
MainActivity.java
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
ListView list;
MyCustomAdapter dataAdapter ;
List<SubTasksModel> subTasksModelArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.heading);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
subTasksModelArrayList = new ArrayList<SubTasksModel>();
list = (ListView) findViewById(R.id.list);
dataAdapter = new MyCustomAdapter(this , R.layout.child_row_add_subtask , subTasksModelArrayList);
list.setAdapter(dataAdapter);
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.add_subtask_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.et_task);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Add Subtask", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
/*subTasksModelArrayList = new ArrayList<SubTasksModel>();*/
fillData(editText.getText().toString() , false);
Utility.setListViewHeightBasedOnChildren(list);
}
})
.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void fillData(String s, boolean b) {
final SubTasksModel model = new SubTasksModel();
model.setTask(s);
model.setSelected(b);
subTasksModelArrayList.add(model);
}
}
MyCustomAdapter.java
public class MyCustomAdapter extends BaseAdapter {
public List<SubTasksModel> subTasksModelList;
Context context;
private LayoutInflater mInflater;
public MyCustomAdapter(Context context, int resource, List<SubTasksModel> objects) {
this.context=context;
this.subTasksModelList=objects;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
static class ViewHolder {
LinearLayout linearLayout;
TextView task;
CheckBox cb;
}
#Override
public int getCount() {
return 0;
}
#Override
public SubTasksModel getItem(int position) {
return subTasksModelList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder ;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.child_row_add_subtask, null);
holder.task = (TextView) convertView.findViewById(R.id.tv_subtask);
holder.cb = (CheckBox) convertView.findViewById(R.id.cb_subtask);
holder.linearLayout = (LinearLayout) convertView.findViewById(R.id.LinearLayout01);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
final int pos = position;
holder.task.setText(subTasksModelList.get(position).getTask());
holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
subTasksModelList.get(pos).setSelected(isChecked);
}
});
/*Log.d("ArrayList"," : "+ subTasksModelList);
SubTasksModel subTasksModel = subTasksModelList.get(position);
holder.task.setText(subTasksModel.getTask());
holder.cb.setChecked(subTasksModel.isSelected());
holder.cb.setTag(subTasksModel);*/
return convertView;
}
}
SubTaskModel.java
public class SubTasksModel {
String task = "";
boolean selected = false;
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
// Utility class is just to set height of listview inside scrollview.
public class Utility {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
Log.d("Params are : " , " : "+ params);
listView.requestLayout();
}
}
#Override
public int getCount() {
return 0;
}
replace it with
#Override
public int getCount() {
return subTasksModelList.size();
}
I have a ListActivity and a custom adapter that extends BaseAdapter.
On each row of the ListView, there is a button and a few more views. onClickListener is declared in the adapter.
How can I refresh list view after button is clicked ?
Here is the code
List Activity:
.........
super.onCreate(savedInstanceState);
here im reading content from a file and then creating adapter with that content
adapter = new UvArrayAdapter(this, strarray3, strarray2, intarray);
setListAdapter(adapter);
..........
Adapter:
.......
public class UvArrayAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater linflater;
private TextView txt_1, txt_2, txt_3;
private ProgressBar pr1;
private String[] str1;
private String[] str2;
private String[] str3;
private Integer[] int1;
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
#Override
public void onClick(View arg0) {
Log.v("TAG", "onItemClick at position" + mPosition);
}
}
public UvArrayAdapter(Context context, String[] s1, String[] s2, Integer[] i1) {
mContext = context;
str1 = s1;
str2 = s2;
int1 = i1;
linflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return str1.length;
}
#Override
public Object getItem(int arg0) {
return str1[arg0];
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = linflater.inflate(R.layout.uv_rowlayout, null);
}
convertView.setOnClickListener(new OnItemClickListener(position));
txt_1 = (TextView) convertView.findViewById(R.id.textView1);
pr1 = (ProgressBar) convertView.findViewById(R.id.progressBar1);
pr1.setProgress(int1[position]);
txt_1.setText(str1[position]);
txt_2 = (TextView) convertView.findViewById(R.id.textView2);
txt_2.setText(str2[position]+"mV");
Button btn = (Button) convertView.findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Log.v("onClickListener", "button - clicked at position " position);
do some changes in mentioned file and after that i need to update the list view with new data
}});
return convertView;
}
}
adapter.notifyDataSetChanged(); // to notify the adapter that your data has been updated
Note: If you get any errors with the above line, you could try the following code (where mListView is the name of my ListView object)
((BaseAdapter) mListView.getAdapter()).notifyDataSetChanged();
Another way would be to invalidate the List so that it is redrawn form the updated data set once again.
mListView=(ListView) findViewById(R.id.MyListView);
mListView.invalidate();
Use notifyDataSetChanged()
adapter = new UvArrayAdapter(this, strarray3, strarray2, intarray);
setListAdapter(adapter);
UvArrayAdapter.notifyDataSetChanged();
// To make the adapter aware of the changes
I want to add a new row on clicking add button in a list view in android.
Can someone help me out?
Here is the code I have so far:
public class prsnlhstry<EventArgs> extends Activity implements OnItemClickListener {
public static ArrayList<String> arr_sort_textview1= null;
public static ArrayList<String> arr_sort_textview2=null;
public static ArrayList<String> arr_sort_textview3=null;
public Resources ApptResources= null;
private ContextWrapper mycontext;
tododata todo;
int clickcounter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv= (ListView)findViewById(R.id.listview);
todo = new tododata(this);
List<listObject> List = new ArrayList<listObject>();
for(int i = 0; i <= 5; i++){
listObject lo = new listObject();
lo.grade = Integer.toString(i);
lo.reason = Integer.toString(i);
lo.school = Integer.toString(i);
List.add(lo);
}
CustomAdapter ca = new CustomAdapter(this);
lv = (ListView)findViewById(R.id.listview);
lv.setAdapter(ca);
lv.setOnItemClickListener(this);
ca.notifyDataSetChanged();
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Toast.makeText(prsnlhstry.this, "Row Added Successfully", Toast.LENGTH_SHORT).show();
}
});
}
private class listObject {
String grade;
String school;
String reason;
}
public class CustomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return todo.getLength();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
String temp = null;
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.grid_item, null);
// Creates a ViewHolder and store references to the views
// we want to bind data to.
holder = new ViewHolder();
holder.textview1 = (TextView) convertView.findViewById(R.id.item2);
holder.textview2 = (TextView) convertView.findViewById(R.id.item3);
holder.textview3 = (TextView) convertView.findViewById(R.id.item4);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textview1.setText(todo.getgrade(position));
holder.textview2.setText(todo.getschool(position));
holder.textview3.setText(todo.getreason(position));
return convertView;
}
}
static class ViewHolder {
TextView textview1;
TextView textview2;
TextView textview3;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
}
Just add the item to your list and refresh the adapter, nothing special.
You need to increment your "tododata" data structure on button click and then call to notifyDataSetChanged() method:
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
todo.addNewRow();
ca.notifyDataSetChanged();
Toast.makeText(prsnlhstry.this, "Row Added Successfully", Toast.LENGTH_SHORT).show();
}
});
To compile the above code you will need to define "ca" variable as the final one, or make it class member.
I hope it helps.