Add views within the OnClick - android

I have a EditText box which is used to input names. Once the names are inputed and the add button is clicked I need the name to be saved into a Array that can be used in the next Activity and to also clear the EditText box. I think I have this working but not to sure if it is correct you can see the code below.
My actuall question is a little different when the add button is clicked I also need it to show the name that was just added next to the add button with its own remove button and if more are added they need to appear below like a kind of list view. If the remove button is clicked it needs to then remove the name and remove button from screen and the name out of the array.
Code has been updated I am trying to populate the ListView from a Adapter but with no sucsess so far
I am thinking something like adding a TextView and Button within the onClick method. And when the button Remove is clicked I would need to remove the TextView string from the playerList. I think I would also have to remove the View so it can no longer be seen.
Can any help me out on the code side of this can't seem to figure it out.
public class AddRemove extends Activity {
ArrayList<String> playerList = new ArrayList<String>();
String playerlist[];
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addremove);
ListView listView = (ListView)findViewById(R.id.namelistview);
listview.setAdapter(new myAdapter(getApplicationContext(), R.layout.listview_content, list));
Button confirm = (Button) findViewById(R.id.add);
confirm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText playername = (EditText) findViewById(R.id.userinput);
String name = playername.getText().toString();
playerList.add(name);
playername.setText("");
}});
Button play = (Button) findViewById(R.id.playnow);
play.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent( demo.AddRemove.this, demo.PasswActivity.class);
Bundle extras = new Bundle();
extras.putSerializable( "com.example.playerList", playerList );
i.putExtras( extras );
startActivity( i );
}});
}
class myAdapter extends ArrayAdapter{
List<String> users;
public myAdapter(Context context, int textViewResourceId, List<String> list) {
super(context, textViewResourceId);
// assign list
users = list;
// TODO Auto-generated constructor stub
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return super.getView(position, convertView, parent);
}
}
}
listview_content XML
<TextView
android:id="#+id/playername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remove" />

You should be using a ListView to display your list of people. Within this List, you would have a layout with 2 components in each row. These would include one TextView and one Button, the name of the person and the button to remove the component. When the button is clicked, remove the item from the Adapter and notify the ListView that it has changed.
When you are configuring your ListView your adapter will need to have a custom Adapter that will be used to configure each row of your ListView.
Update
Sample Code:
http://android.vexedlogic.com/2011/04/02/android-lists-listactivity-and-listview-ii-%E2%80%93-custom-adapter-and-list-item-view/

First of all, you need to initialize each TextView with a reference to the context. So, in your onClick, given that it is in ViewOnClick.java:
public class ViewOnClick extends Activity {
LinearLayout.LayoutParams layoutParams;
LinearLayout ll;
static int i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button)findViewById(R.id.Button01);
ll = (LinearLayout)findViewById(R.id.ll);
layoutParams = new LinearLayout.LayoutParams
(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
TextView view = new TextView(ViewOnClick.this);
view.setText(++i+" view");
ll.addView(view, layoutParams);
}});
}
}
Second, given that you have a call to setContentView in onCreate which also adds your linearlayout to the view, you do not need to call setContentView(linearLayout) each time the button is clicked.

Related

Listview not updating after arraylist is updated?

I've seen many other posts in this context, but none helped. Problem is when i click on the addField button, the listview inside dialog adds new view just once. But at other clicks it doesn't get updated though The adapter works correctly (I mean the getView is called and also the arrayList in the adapter is changed in size).
I've used notifyDataSetChanged() in the adapter class. No result! I used an instance of adpater class in activity and called myAdapter.notifyDataSetChanged(). No result!
here is my code:
public class MainActivity extends Activity {
ListView lvfid;
FieldAdapter fAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some code
showFid();
}
private void showFiD(){
final ArrayList <HashMap<String,String>> al = new ArrayList<HashMap<String,String>>();
final Dialog dialog = new Dialog(MainActivity.this , R.style.DialogTheme);
dialog.setContentView(R.layout.field_dialog);
dialog.setCancelable(true);
dialog.show();
Button addField = (Button) dialog.findViewById(R.id.btnfidField);
lvfid = (ListView) dialog.findViewById(R.id.lvfid);
//Another plan i have tested, but no result:
//fAdapter = new FieldAdapter(dialog.getContext(),al);
//lvfid.setAdapter(fAdapter);
addField.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
HashMap<String,String> h = new HashMap<String,String>();
h.put("name", "");
h.put("value", "");
al.add(h);
lvfid.setAdapter(new FieldAdapter(dialog.getContext(), al));
//fAdapter.notifyDataSetChanged();
}
});
}
public class FieldAdapter extends BaseAdapter{
private ArrayList <HashMap <String,String>> arrayList;
private LayoutInflater inflater;
public FieldAdapter(Context context, ArrayList<HashMap <String,String>> arrayList) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#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 arg2) {
View view = null;
if (convertView == null)
view = inflater.inflate(R.layout.field_inflater, null);
else
view = convertView;
Holder holder = new Holder();
holder.edName = (EditText) view.findViewById(R.id.edfidName);
holder.edValue = (EditText) view.findViewById(R.id.edfidValue);
//holder.edName.setText(arrayList.get(position).get("name"));
//holder.edValue.setText(arrayList.get(position).get("value"));
return view;
}
private class Holder {
private EditText edName;
private EditText edValue;
}
}
}
UPDATE:
I'm sorry i took everybody's time. The stupid problem was that my listview was inside a scrollview where it must not be! I hope this helps others who have the same issue!
Use the notifyDataSetChanged() every time the list is updated.
I had the same problem. I was facing with this problem when I wanted to update the listView after onDateChanged(). I resolved it with an extra ArrayList variable and an extra custom adapter in your case FieldAdapter variable.
Update your listView with a refresh adapter and array list variables after any operations. For example after button clicks.
1. Define a counter.
2. Check when the button is clicked, increase counter by one
3. Every time check the counter, if counter is greater than 1 it means the button is clicked more than once so update the list view with new variables (arrayList, FeildAdapter)
I recommend you to define the variables as a private class fields and name them such as refreshedArrayList and refreshedAdapter
Option
Try to use the ArrayAdapter. And don't create a new adapter every
time you click on the button.
only call the add(T o) function from the ArrayAdapter.
Other Option:
add a add function to your FieldAdapter in the add field adapter add the object to your arraylist and call notifiyDataSetChanged(the adapter has aslo one and the adapter notifies all his observers)
also don't create a new adapter every time you click the button.
public class MainActivity extends Activity {
ListView lvfid;
FieldAdapter fAdapter;
ArrayList <HashMap<String,String>> al ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some code
al = new ArrayList<HashMap<String,String>>();
lvfid.setAdapter(new FieldAdapter(MainActivity.this , al));
showFid();
}
private void showFiD(){
final Dialog dialog = new Dialog(MainActivity.this , R.style.DialogTheme);
dialog.setContentView(R.layout.field_dialog);
dialog.setCancelable(true);
dialog.show();
Button addField = (Button) dialog.findViewById(R.id.btnfidField);
lvfid = (ListView) dialog.findViewById(R.id.lvfid);
//Another plan i have tested, but no result:
//fAdapter = new FieldAdapter(dialog.getContext(),al);
//lvfid.setAdapter(fAdapter);
addField.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
HashMap<String,String> h = new HashMap<String,String>();
h.put("name", "");
h.put("value", "");
al.add(h);
fAdapter.notifyDataSetChanged();
}
});
}
I'm sorry i took everybody's time! The stupid problem was just my listview was inside a scrollview where it must not be! after getting the listview out of scrollview the problem got solved.

Loading camera every first time on click of listview item unchecks all the checkboxes from the listview

Here is my custom list adapter class where I populate the list items which contain one checkbox and an imageview. On check of the checkbox, an imageview appears on the same row of listview and on click of that imageview, a camera loads. However every first time I load the camera and capture a picture or press back without capturing images, all the checks from the checkboxes disappear, but after the first time everything works normally. Can anyone tell me why this is happening
public class CustomListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] itemname;
private static final int CAMERA_REQUEST = 1888;
public CustomListAdapter(Activity context, String[] itemname) {
super(context, R.layout.merch_items, itemname);
// TODO Auto-generated constructor stub
this.context=context;
this.itemname=itemname;
}
public View getView(final int position,View view, ViewGroup parent){
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.merch_items,null,true);
final ImageView imageView = (ImageView) rowView.findViewById(R.id.merchimageView);
final TextView merchText = (TextView) rowView.findViewById(R.id.merchimagetext);
final CheckBox checkBox = (CheckBox) rowView.findViewById(R.id.checkBox);
imageView.setTag("empty");
checkBox.setText(itemname[position]);
checkBox.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(checkBox.isChecked()){
imageView.setImageResource(R.drawable.camera);
imageView.setTag("available");
}
else{
imageView.setImageDrawable(null);
imageView.setTag("empty");
}
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(imageView.getTag().toString().equals("available")) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
((Activity)context).startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
});
return rowView;
}
}
On Data change notification to the adapter, recreates your list. In that case, even your second time work perfect does not stand.
The way the getView method is written is not entirely correct. Because, there is no recycling process for the list items, They are getting created entirely all the time.
One way to handle this is to keep a list of booleans where index represent the position and the boolean value represent weather the the box is checked or not and using that value you can set the check-box to be be checked or not!

Get item selected in the custom adapter listview android

My every list view item has its own linearlayout component.The list view is in the activity with onItemClick on itself.
In my custom adapter file, I have the onclick on this linearlayout,
private ArrayList<Book> bookArray; // this is the data source
.........
LinearLayout imgLayout = (LinearLayout) rowView.findViewById(R.id.imageLayout);
imgLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { // fire user Like
//*** how can I get which item is selected here?
But how can I get the item index whose linearlayout is clicked?
Regards
Hammer
Use setTag() and getTag() to remember positon and use it on click of LinerLayout.
in getView
LinearLayout imgLayout = (LinearLayout) rowView.findViewById(R.id.imageLayout);
imgLayout .setTag(position);
and into onclick of LinerLayout take it as
imgLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer)v.getTag();
//....
}
}
You can set the tag for your linear layout and inside your onClick you can get the tag which will return the position for which clickEvent get Trigger.
See below code:
private ArrayList<Book> bookArray; // this is the data source
.........
LinearLayout imgLayout = (LinearLayout) rowView.findViewById(R.id.imageLayout);
imgLayout.setTag(position);
imgLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { // fire user Like
//*** how can I get which item is selected here?
Log.d(TAG,"Clicked Pos of Row"+v.getTag().toString();

ListView (button not running)

Practicing on the ListView, I thought of adding buttons as well to it, rather than showing only content. But in my implementation, the button does not do anything at all.
Plus I was confused whether I could get the position of the button clicked. For now I am just sending the toSend declared inside the OnItemClick in an intent.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
final int toSend = position;
TextView refId = (TextView)view.findViewById(R.id.list_id);
TextView refName = (TextView)view.findViewById(R.id.list_name);
TextView refAdd = (TextView)view.findViewById(R.id.list_address);
Button edit = (Button)view.findViewById(R.id.edit);
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent i = new Intent(ListActivity.this, EditLayout.class);
i.putExtra("position", toSend);
startActivity(i);
}
});
String sd_id = refId.getText().toString();
String sd_name = refName.getText().toString();
String sd_add = refAdd.getText().toString();
buildAlert(sd_id, sd_name, sd_add);
}
});
You're pretty close. The "inside" setOnClickListener needs to happen when you create the list row view (the view containing id, name, address, edit).
You can do that during getView(). But where to send the clicks? Instead of creating a new onClickListener, use "this" (your activity). Put an onClick() handler in the activity.
Then, when you get a click, the onClick method will execute. Next problem: how do you know which row clicked? The easiest way that comes to mind is to give the button a different id for e ach row - use the row index (you might need to start at 1 rather than 0 - be warned).
Finally, given the row id, it's easy to start your "nested" activity.
Hope this helps.
(added later)
I do it like this; you'll need to define a layout for your row view:
class MyActivity extends Activity implements View.OnClickListener
{
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.my_page);
ListView list = (ListView)findViewById (android.R.id.list);
MyArrayAdapter adapter = new MyArrayAdapter (this, <your array of data>);
list.setAdapter (adapter);
}
#Override
public void onClick(View v)
{
int buttonId = v.getId();
if (buttonId is within range)
... do what you need to do with the click ...
}
private class MyArrayAdapter extends ArrayAdapter<MyData>
{
private Activity act;
//-----------------------------------------------------------------------------
public MyArrayAdapter (Activity act, MyData array)
{
super (act, R.layout.list_row, array);
this.act = act;
}
//-----------------------------------------------------------------------------
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
ViewGroup rowView = (ViewGroup)convertView;
if (rowView == null)
{
LayoutInflater inflater = act.getLayoutInflater();
rowView = (ViewGroup) inflater.inflate (R.layout.list_row,
parent, false);
}
Button button = (Button)rowView.findViewById (R.id.is_member);
button.setId (position+1); // add one to avoid 0 as an id.
button.setOnClickListener (act);
// set field values here -- not shown
return rowView;
}
}
}

Save Array Within Activity

I have an Activity which lets the user input names and the save them. Once the add Button is clicked the name gets added to the Array and also shown in a ListView with an option to remove a name.
My question is I am trying to get to the point where if the user leaves the Activity then comes back to the Activity the Array and ListView will have been saved so there is no need to input all the names again. At the moment once the Activity is left and then come back to the Array and ListView are empty.
As you can see at the bottom I have tried to use onSaveInstanceState and onRestoreInstanceState but can't get them to work can anyone expand on this code?
ArrayList<String> playerList = new ArrayList<String>();
ListView employeeList;
ArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addremove);
final MyAdapter adapter = new MyAdapter(this, R.layout.listview_content, playerList);
ListView employeeList = (ListView) findViewById(R.id.namelistview);
employeeList.setAdapter(adapter);
Button confirm = (Button) findViewById(R.id.add);
confirm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText playername = (EditText) findViewById(R.id.userinput);
playerList.add(playername.getText().toString());
adapter.notifyDataSetChanged();
playername.setText("");
}});
Button play = (Button) findViewById(R.id.playnow);
play.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent( demo.AddRemove.this, demo.PasswActivity.class);
intent.putStringArrayListExtra("KEY", playerList);
startActivity(intent);
}});
}
class MyAdapter extends ArrayAdapter<String>{
private OnClickListener listener;
public MyAdapter(Context context, int textViewResourceId, ArrayList<String> objects) {
super(context, textViewResourceId, objects);
listener = new OnClickListener(){
public void onClick(View v){
playerList.remove(v.getTag());
notifyDataSetChanged();
};
};
}
public View getView(int position, View convertView, ViewGroup parent) {
if( convertView== null ) convertView = getLayoutInflater().inflate(R.layout.listview_content, null);
TextView myTextView1 = (TextView)convertView.findViewById(R.id.playername);
myTextView1.setText(getItem(position));
Button remove = (Button)convertView.findViewById(R.id.remove);
remove.setTag(getItem(position));
remove.setOnClickListener(listener);
return convertView;
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
outState.putStringArrayList("Playlist", playerList );
super.onSaveInstanceState(outState); }
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
playerList = savedInstanceState.getStringArrayList("Playlist");
}
}
Have you try making your playerList as
static
it will solve your purpose

Categories

Resources