How to reset the whole View by clicking the delete Button - android

I have made a custom View which contains an ImageView, a TextView and a delete Button.
I want to reset the particular View when I click the delete Button associated with it.
Please tell how to implement this.
Here is my MainActivity.java
package com.khurana.nikhil.list1;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ListView lv;
TextView tv1, tv2;
View v1;
public String[] s = {"nikhil", "mukul", "kunal"};
public int[] img = {R.drawable.rty, R.drawable.sf, R.drawable.rty};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.listView);
CustomAdapter cad = new CustomAdapter(MainActivity.this, s, img);
lv.setAdapter(cad);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,View v,int position,long id)
{
Toast.makeText(MainActivity.this,"You clicked "+s[position],Toast.LENGTH_SHORT).show();
}
});
}
}
Here is CustomAdapter.java
package com.khurana.nikhil.list1;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter<String>{
Context c1;
String s1[];
int s2[];
CustomAdapter(Context c,String s[],int s3[])
{
super(c,R.layout.tcustom,s);
this.c1=c;
this.s1=s;
this.s2=s3;
}
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
tv.setText(s1[position]);
im.setImageResource(s2[position]);
Button bt=(Button)v.findViewById(R.id.button);
return v;
}
}

((LinearLayout)yourView.getParent()).removeView(yourView);
or you can call from the layout directly
yourRelativeLayout.removeView(yourView)

I would recommend to use an ArrayList instead of a String[] in your Adapter class. It makes it a lot easier to delete or edit a View and the associated data behind it. I used this post to convert your String[] to an ArrayList, delete the item and convert back to String[].
This should work on button click:
In your Adapter class:
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
tv.setText(s1[position]);
im.setImageResource(s2[position]);
Button bt=(Button)v.findViewById(R.id.button);
bt.setTag(position); //important so we know which item to delete on button click
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
int positionToRemove = v.getTag(); //get the position of the view to delete stored in the tag
removeItem(positionToRemove); //remove the item
}
});
return v;
}
public void removeItem(int position){
//convert array to ArrayList, delete item and convert back to array
ArrayList<String> a = new ArrayList<>(Arrays.asList(s1));
a.remove(i);
strings = new String[a.size()];
s1= a.toArray(strings);
notifyDataSetChanged(); //refresh your listview based on new data
}
#Override
public int getCount() {
return s1.length;
}
#Override
public String getItem(int position) {
return s1[position];
}

View visibility to GONE will not delete your view from memory as well. Please be specific, do you want to retain your view for future?

If you are working in a listview you should call notifyDataSetChanged() the adapter. your getView() method can be like:
action on button can be like this
Button bt=(Button)v.findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s1 = ArrayUtils.remove(s1, position);
s2 = ArrayUtils.remove(s2, position);
notifyDataSetChanged();
}
});

If you want the view to disappear:
yourView.setVisibility(View.GONE);
EDIT: To get the parent view of the button: Android: Making changes to a button's parent view

Related

Set Id and get it to the items of ListView in Android

New android programmer is here.
First : I dont know many things about list view and as I found out , its complicated to work with it.
So , I want to put my database data (Contains Id , Name) to a listview and get the Id of the item is clicked.
I have searched many but i just found this :
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class test extends Activity {
String[] wordlist = new String[] { "a", "b", "c" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
wordlist[2] = "abds";
ListView list = new ListView(this);
list.setAdapter((ListAdapter) new MyAdapter(test.this, wordlist));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Object entry= parent.getItemAtPosition(position);
Toast.makeText(test.this, entry.toString(), Toast.LENGTH_SHORT).show();
}
});
setContentView(list);
}
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, String[] strings) {
super(context, -1, -1, strings);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout listLayout = new LinearLayout(test.this);
listLayout.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.WRAP_CONTENT,
AbsListView.LayoutParams.WRAP_CONTENT));
listLayout.setId(5000);
TextView listText = new TextView(test.this);
listText.setId(5001);
listLayout.addView(listText);
listText.setText(super.getItem(position));
return listLayout;
}
}
}
Just i can show strings , not Id.
Use SimpleCursorAdapter to populate ListView with data from database, for example - https://thinkandroid.wordpress.com/2010/01/09/simplecursoradapters-and-listviews/ (first link from google).
How to get the item id in an onItemClick handler
Read more about ListView and Adapters, your code is awful )

custom list view with check Box does not work

I have a problem my custom List view.I have data in hash map and add into array list which is shown in below code.what is my problem is in my hash map contain 20 values and i try set into the list view but first data only display other or not.Thanks advance
This is my CustomAdapter
package com.example.node10.databasetesting;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.example.node10.databasetesting.DataBase.*;
public class ListViewEmployee extends AppCompatActivity implements View.OnClickListener {
private SimpleCursorAdapter dataAdapter;
private Button btn_view;
private Button btn_submit;
ArrayList<HashMap<Integer,String>> emp;
HashMap<Integer,String> map;
Set<Integer> keyValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_employee);
DataBase dataBase=new DataBase(this);
map=new HashMap<>();
map=dataBase.getValueEmpTable();
emp=new ArrayList<HashMap<Integer, String>>();
keyValue=map.keySet();
emp.add(map);
btn_view= (Button) findViewById(R.id.id_btn_emp_view);
btn_view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.id_btn_emp_view){
displayList();
// selectItem();
}
}
private void displayList() {
//create the Arrayt adapter
ListView listview= (ListView) findViewById(R.id.id_listview);
final MyAdapter adapter=new MyAdapter(this,R.layout.custom_listview,emp);
listview.setAdapter(adapter);
}
public class MyAdapter extends ArrayAdapter<HashMap<Integer,String>>{
boolean[] checkBoxState;
ViewHolder viewholder;
public MyAdapter(Context context, int resource,ArrayList<HashMap<Integer,String>> map) {
super(context, resource, map);
// create the boolean array for check box selection
checkBoxState= new boolean[map.size()];
}
// create the class for caching the view
class ViewHolder{
TextView txtView;
CheckBox checkBox;
}
#Override
public View getView( final int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater objlayout= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=objlayout.inflate(R.layout.custom_listview,null);
viewholder=new ViewHolder();
viewholder.txtView= (TextView) convertView.findViewById(R.id.id_checkbox_textview);
viewholder.checkBox= (CheckBox) convertView.findViewById(R.id.id_checkbox);
convertView.setTag(viewholder);
}else{
viewholder = (ViewHolder) convertView.getTag();}
// viewholder.txtView.setText(emp.get(position).toString());
viewholder.txtView.setText(emp.get(position).get(position+1).toString());
viewholder.checkBox.setChecked(checkBoxState[position]);
viewholder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
} else {
checkBoxState[position] = false;
}
}
});
return convertView;
}
}
}
Now you put to your adapter ArrayList of HashMap. I don't know why are you doing that, but now your ArrayList emp contains ony one element - that was added in line
emp.add(map);
So, ArrayAdapter for array with size = 1 will show 1 elemet.
If you want to show in list all elements from your map. I suggest to use
ArrayList emp and comvert map to list by using map.values()
ArrayList<String> emp = (ArrayList<String>)map.values();
Then change your adapter to
public class MyAdapter extends ArrayAdapter<String>

Modifying element of a listView how to get access to it

I learned that in order to modify row in a listView I need to gain access eg via adapter.getItem(position) but I have no idea how to work this around. Should I post any code please let me know.
Here is my EditListItemDialog file:
package com.example.classorganizer;
import java.util.ArrayList;
import java.util.List;
import com.example.classorganizer.Monday.DiaryAdapter;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
class EditListItemDialog extends Dialog implements View.OnClickListener {
private View editText;
private DiaryAdapter adapter;
// public EditListItemDialog(Context context, List<String> fragment_monday) { //first constructor
// super(context);
// this.fragment_monday = fragment_monday;
// }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
}
private List<String> fragment_monday;
public EditListItemDialog(Context context, DiaryAdapter adapter) {
super(context);
this.fragment_monday = new ArrayList<String>();
this.adapter = adapter;
}
#Override
public void onClick(View v) {
fragment_monday.add(((TextView) v).getText().toString());//here is your updated(or not updated) text
adapter.notifyDataSetChanged();
dismiss();
}
}
You will have to implement an OnItemClickListener which will be able to tell you what item has been clicked. For example:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Position is the number of the item clicked
//You can use your adapter to modify the item
adapter.getItem(position); //Will return the clicked item
}
See the official Android documentation for more information.
package com.example.classorganizer;
import java.util.ArrayList;
import java.util.List;
import com.example.classorganizer.Monday.DiaryAdapter;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class EditListItemDialog extends Activity {
ListView listView ;
private View editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
listView = (ListView) findViewById(R.id.list)
String[] values = new String[] { "Automotive", "Banking", "Consumer Electronics",
"Education", "HealthCare and Life Sciences","Industrial Automation","Printing and
Imaging","Manufacturing","Media and
Entertainment","Networking","Retail","Telecom"
};
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
}
}
Use This code for simple Listview..

Android ListView Items open Activity

I have this problem i can't access to another layout or activity form List view , im trying to call Intent but I always get "confirm perspective switch" , the source not found .
here is the code
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class HomeTab extends Activity {
private List<home_items> myItems= new ArrayList<home_items>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
populateHomeIteams();
populateListView();
registerClickCallback();
}
private void registerClickCallback() {
ListView list=(ListView)findViewById(R.id.listView1);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
long id) {
//Toast.makeText(HomeTab.this, "positiom is"+position, Toast.LENGTH_LONG).show();
if(position==0)
{
Intent intt=new Intent(HomeTab.this, Beauty_Tab.class);
startActivity(intt);
}
}
});
}
private void populateHomeIteams() {
myItems.add(new home_items("Beauty", R.drawable.bg_list_view));
myItems.add(new home_items("Healthy food", R.drawable.bg_list_view));
myItems.add(new home_items("Family Health", R.drawable.bg_list_view));
myItems.add(new home_items("Moda", R.drawable.bg_list_view));
}
private void populateListView() {
ArrayAdapter<home_items> adapter= new MyListAdapter();
ListView list= (ListView) findViewById(R.id.listView1);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<home_items> {
public MyListAdapter(){
super(HomeTab.this,R.layout.iteam_view,myItems);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if(itemView == null){
itemView=getLayoutInflater().inflate(R.layout.iteam_view,parent ,false);
}
home_items currentitem=myItems.get(position);
ImageView imageview=(ImageView)itemView.findViewById(R.id.iteam_icon);
imageview.setImageResource(currentitem.get_iconID());
TextView maketxt=(TextView)itemView.findViewById(R.id.iteam_txt);
maketxt.setText(currentitem.get_iteam_name());
return itemView;
}
}
}
the problem is in the function registerclickCallnack()
the toast is working will but the intent not working
private void registerClickCallback() {
ListView list=(ListView)findViewById(R.id.listView1);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
long id) {
//Toast.makeText(HomeTab.this, "positiom is"+position, Toast.LENGTH_LONG).show();
if(position==0)
{
Intent intt=new Intent(HomeTab.this, Beauty_Tab.class);
startActivity(intt);
}
}
});
}
as far as i remember in onItemClick() method position starts from 1
Your problem is that you instantiate 2 listView objects, one in populateListView and the other in registerClickCallback; You instantiate one listView but add the click callback on the other, make sure you use one single listView object all over.

how to use a custom button in a list to redirect the user to another activity

I've written a big code and I've used a list view within one of my task layouts :
I want to know how I can make a listener for each update button in this case in order to move to another activity , I know how to use more than one activity and moves between them But I want to know how to make a listener only .
The custom adapter code :
package com.example.task_9;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class TempLyaout extends ArrayAdapter<String> {
Context context;
ArrayList<String> sa;
public TempLyaout(Context context , ArrayList<String> sa) {
super(context,R.layout.temp,sa);
this.context=context;
this.sa = sa;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater l = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View rowView = l.inflate(R.layout.temp, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.textView1);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView1);
Button update = (Button) rowView.findViewById(R.id.button1);
// myDb.open();
// Cursor cursor= myDb.getRowByName(sa.get(position));
// myDb.updateRowByName(cursor.getInt(DBAdapter.COL_ROWID), sa.get(position), cursor.getString(DBAdapter.COL_PASSWD), cursor.getInt(DBAdapter.COL_AGE), isAdmin);
// myDb.close();
textView.setText(sa.get(position));
return rowView;
}
}
This is the related class :
package com.example.task_9;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class UsersActivity extends Activity {
Intent redirect;
ListView list;
ArrayList<String> sa;
DBAdapter myDb;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onStart() {
super.onStart();
setContentView(R.layout.users);
list= (ListView) findViewById(R.id.usersList);
redirect = getIntent();
openDB();
/*********************************************/
Cursor cursor = myDb.getAllRows();
cursor.moveToFirst();
ArrayList<String> ha = new ArrayList<String>();
while(cursor.moveToNext()) {
ha.add(cursor.getString(DBAdapter.COL_NAME));
}
cursor.close();
#SuppressWarnings("rawtypes")
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,ha);
list.setAdapter(new TempLyaout(UsersActivity.this,ha));
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
} // end onStart method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
} // end openDB method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void closeDB() {
myDb.close();
} // end closeDB method
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
}// end main class
In your getView
Button update = (Button) rowView.findViewById(R.id.button1);
update.setOnClickListener(mClickListener);
Then
private OnClickListener mClickListener = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ListActivtiy.this,SecondActivity.class);
startActivity(intent);
}
};
Also use a viewholder for smooth scrolling and performance
http://developer.android.com/training/improving-layouts/smooth-scrolling.html

Categories

Resources