User input a name for every image in android gridview - android

I've been searching for an answer to this question for how many days but I couldn't find the right answer so I tried creating my own question.
I have created a gridview that contains an image and every image must have an specific name. When an image was clicked a dialog box will be prompted and ask for an image name specified for the image clicked.
What are the possible things to do this? Please help. I have included a code from the net for gridview:
Grid.java
public class Grid extends Activity{
public static Integer[] homeIC = {
R.drawable.ic_launcher, R.drawable.ic_launcher,R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher, R.drawable.ic_launcher
};
// I've used blank strings so that I could change it to the name desired by the user
public static String[] menuName = {
" ", " ", " ", " ", " ", " ", " ", " "
};
GridView gridV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
gridV = (GridView) findViewById(R.id.gridview);
gridV.setAdapter(new ImageAdapter(this, menuName, homeIC));
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
String[] homeText;
Integer[] imageID;
private LayoutInflater inflater=null;
public ImageAdapter (Grid mainactivity, String[] name, Integer[] image)
{
context = mainactivity;
homeText = name;
imageID = image;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//--returns the number of images
public int getCount()
{
return homeIC.length;
}
//returns the ID of an item--
public Object getItem(int position)
{
return position;
}
//returns the ID of an item
public long getItemId(int position)
{
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
final Holder holder=new Holder();
View gridV;
gridV = inflater.inflate(R.layout.grid_content, null);
holder.tv=(TextView) gridV.findViewById(R.id.homeText);
holder.img=(ImageView) gridV.findViewById(R.id.homeImage);
holder.img.setImageResource(imageID[position]);
holder.tv.setText(homeText[position]);
gridV.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//show dialog box and ask for a name for an image
}
});
return gridV;
}
}
}
activity_grid.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#bbbbbb"
android:layout_weight="1"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_marginBottom="10dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_marginTop="5dp"
android:layout_weight="0.05"
android:columnWidth="80dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" >
</GridView>
</LinearLayout>
grid_content.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="#+id/homeImage"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:src="#drawable/ic_launcher" >
</ImageView>
<TextView
android:id="#+id/homeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:gravity="center"
android:textSize="15sp" >
</TextView>
and this is xml file for the dialog box that will be used by the user in adding name for the image
add_name.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/TextView01"
android:ems="10" />
<Button
android:id="#+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="66dp"
android:text="ADD" />
<Button
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/ok"
android:layout_alignBottom="#+id/ok"
android:layout_toRightOf="#+id/ok"
android:text="CANCEL" />
</RelativeLayout>
Thanks for any response. That will be a great help.

Use it like this inside onClick
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Enter image name");
alert.setMessage("Please enter the image name below");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText();
//Get the text view and set its value
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();

Related

ImageView inside ListView doesn't show up after Main Layout changed from Constraint to Relative

as the title said. I have a ListView inside the Main Activity layout. At the beginning it was a ConstraintLayout but I decided to make it a RelativeLayout and after that, my ImageView inside of the row_item disappeared and I can't put it back, I tried a lot of answers but none could help me.
Here is the ListAdapter code:
public class ListAdapter extends ArrayAdapter<Product> {
private int resourceLayout;
private Context mContext;
private List<Product> items;
private AlertDialog.Builder alert;
EditText edittext;
public ListAdapter(Context context, int resource, List<Product> items) {
super(context, resource, items);
this.items = items;
this.resourceLayout = resource;
this.mContext = context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
alert = new AlertDialog.Builder(mContext);
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(mContext);
v = vi.inflate(resourceLayout, null);
}
final Product p = getItem(position);
ImageView deleteImage = (ImageView) v.findViewById(R.id.delete_image);
deleteImage.setVisibility(View.VISIBLE);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edittext = new EditText(mContext);
edittext.setPaddingRelative(5,10,10,5);
edittext.setHint("New Quantity");
Log.d("DATABASE", " "+ position);
new AlertDialog.Builder(mContext)
.setTitle("Are you sure?")
.setView(edittext)
.setMessage("Do you want to change the quantity of product " + p.getName())
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String editedValue = edittext.getText().toString();
if (TextUtils.isEmpty(edittext.getText())){
Toast.makeText(mContext, "You need to specify a quantity", LENGTH_SHORT).show();
} else {
if (Integer.parseInt(editedValue) == 0 && Integer.parseInt(editedValue) > 100){
Toast.makeText(mContext, "Quantity should be greater than 0 and less than 100", LENGTH_SHORT).show();
}else {
p.setQuantity(Integer.parseInt(editedValue)); /// Ceva nu merge bine aici, schimba valoarea desi e 0
notifyDataSetChanged();
}
}
}
})
.setNegativeButton("No", null)
.show();
}
});
deleteImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(mContext)
.setIcon(R.drawable.del_button)
.setTitle("Are you sure?")
.setMessage("Do you want to delete the product " + p.getName() + " from you shopping cart ?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
items.remove(position);
notifyDataSetChanged();
}
})
.setNegativeButton("No", null)
.show();
}
});
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.product_name);
TextView tt2 = (TextView) v.findViewById(R.id.product_quantity);
TextView tt3 = (TextView) v.findViewById(R.id.product_price);
if (tt1 != null) {
tt1.setText(p.getName());
}
if (tt2 != null) {
tt2.setText(String.valueOf(p.getQuantity()));
}
if (tt3 != null) {
tt3.setText(String.valueOf(p.getPrice()*p.getQuantity()));
}
}
return v;
}
Here is my Layout for the row_item
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:andorid="http://schemas.android.com/tools"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/product_name"
android:textSize="25dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Product Name"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#android:color/black" />
<TextView
android:id="#+id/product_quantity"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/product_name"
android:text="Quantity:"
android:textColor="#android:color/black" />
<TextView
android:id="#+id/product_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/product_name"
android:layout_marginLeft="45dp"
android:layout_centerInParent="true"
android:src="#android:drawable/ic_dialog_info"
android:text="Price"
android:textSize="26dp" />
<ImageView
android:id="#+id/delete_image"
android:layout_width="42dp"
android:layout_height="42dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="25dp"
android:clickable="true"
android:focusable="true"
andorid:src="#drawable/del_button" />
</RelativeLayout>
And here is the main layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
android:padding="15dp">
<Button
android:id="#+id/btn_scan"
android:layout_width="105dp"
android:layout_height="67dp"
android:layout_alignParentRight="true"
android:layout_marginRight="30dp"
android:text="SCAN"
android:textAlignment="center"
android:textColor="#color/colorPrimary"
android:textSize="26dp"
/>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="570dp"
android:layout_marginStart="1dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="1dp"
android:layout_below="#id/btn_scan" />
</RelativeLayout>
As I said, before changing my Main Layout from Constraint to Relative, all worked fine. Not sure what's the problem, also, the ImageView had a onClick method which deleted the row on click after showing an AlertDialog. Which worked fine. Not sure what the problem can be, I searched for answers but none helped me. Also, here is my folder with the photo:
Most probably, the problem is in the android:src attribute as it wouldn't support vector drawables which can only be loaded via app:srcCompat
So, please replace the android:src with app:srcCompat; hence the ImageView in your list item layout will be:
<ImageView
android:id="#+id/delete_image"
android:layout_width="42dp"
android:layout_height="42dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="25dp"
android:clickable="true"
android:focusable="true"
app:srcCompat="#drawable/del_button" />
and in this case, it might raise a warning that requires you to add below snippet into gradle file, module level under android {...}
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}

Dynamically inserting list items to listview in android

Friends i'm new to android and learning on my own. I was creating invoice manager app for learning. Here products are added by the admin and that is working fine. User has only permission to create invoice. When user arrives into create_invoice activity he has set of frame layouts in which one is for adding items. When user presses the frame layout he is made to see another activity where he can find all set of list items along with the product price in List view which admin has added. Now when user presses an item he is again brought back to create_invoice activity and a alert box appears which asks the qty required. When user enters the qty and clicks OK button, for the first the list item is displayed properly as i require. But when i add second item, 1st item gets replaced. So now my problem is how can i resolve this problem.. Guys please help me. Codes you people find may be very silly but i'm still learning. Thanks in advance.
Create_invoice activity
//data from activity invoice add_item
product_name = intent.getStringExtra("product_name");
product_price = intent.getDoubleExtra("product_price",0);
//product_qty = intent.getIntExtra("product_qty",0);
product_code = intent.getIntExtra("product_code",0);
if(product_name!= null && product_price!= 0 && product_code!= 0)
{
try {
builder = new AlertDialog.Builder(this);
builder.setTitle("Product Qty");
layoutInflater = LayoutInflater.from(Create_invoice.this);
view = layoutInflater.inflate(R.layout.dialoglayout_invoice,null);
builder.setView(view);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
EditText etxt_dialog_qty=(EditText)view.findViewById(R.id.
etxt_dialog_qty);
int qty = Integer. parseInt (etxt_dialog_qty.getText().
toString().trim());
invoice_product_list products = new invoice_product_list
(product_name, product_price, qty, product_code);
//arraylist
ArrayList<invoice_product_list> productList = new ArrayList<>();
//customAdapter
customAdapterInvoice = new custom_adapter_invoice
(Create_invoice.this, productList);
customAdapterInvoice.add(products);
customAdapterInvoice.notifyDataSetChanged();
//listview in create_invoice activity
listView_additem = (ListView)
findViewById(R.id.listview_additem);
listView_additem.setAdapter(customAdapterInvoice);
alertDialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
}
catch (Exception e)
{
System.out.print(e);
}
}
customAdapter
public class custom_adapter_invoice extends ArrayAdapter
<invoice_product_list> {
public custom_adapter_invoice(Context context,
ArrayList<invoice_product_list> product_details) {
super(context, R.layout.custom_row_invoice_item, product_details);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View view =
layoutInflater.inflate(R.layout.custom_row_invoice_item,parent,false);
invoice_product_list products = getItem(position);
TextView txt_product_name =
(TextView)view.findViewById(R.id.txt_product_name);
TextView txt_product_price =
(TextView)view.findViewById(R.id.txt_product_price);
TextView txt_product_qty =
(TextView)view.findViewById(R.id.txt_product_qty);
TextView txt_product_code =
(TextView)view.findViewById(R.id.txt_product_code);
txt_product_name.setText(products.getProduct_name());
txt_product_price.setText(String.valueOf(products.getProduct_price()));
txt_product_qty.setText(String.valueOf(products.getProduct_qty()));
txt_product_code.setText(String.valueOf(products.getProduct_code()));
return view;
}
create invoice activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.tournonstop.m.invoicemanager.Create_invoice"
tools:showIn="#layout/activity_create_invoice">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/darker_gray">
<include layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="85dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_company">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/company_name"
android:id="#+id/txt_company_name"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/invoice_date"
android:id="#+id/txt_invoice_date"
android:layout_gravity="right"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/invoice_no"
android:id="#+id/textView3"
android:layout_marginLeft="15dp"
android:layout_marginTop="45dp"/>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_client"
android:clickable="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/to"
android:id="#+id/txt_to"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/txt_client_address"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:hint="#string/client_hint"/>
</FrameLayout>
----listview to add items-----
<FrameLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_add_item"
android:clickable="true">
<ListView
android:layout_width="match_parent"
android:layout_height="150dp"
android:id="#+id/listview_additem"
android:divider="#040404" />
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="2dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/white"
android:id="#+id/invoice_frame_sub_total">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/total_label"
android:id="#+id/txt_sub_total_label"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:textStyle="bold"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/total"
android:id="#+id/txt_sub_total"
android:layout_gravity="right"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:textStyle="bold"
android:hint="#string/total_hint" />
</FrameLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="40dp"
android:text="#string/invoice_btn"
android:textStyle="bold"
android:background="#color/colorPrimaryDark"
android:textColor="#android:color/white"
android:clickable="true"
android:id="#+id/btn_invoice_save" />
</LinearLayout>
< /android.support.v4.widget.DrawerLayout>
invoice product list(getters and setters)
package com.tournonstop.m.invoicemanager;
public class invoice_product_list {
private String product_name;
private double product_price;
private int product_qty;
private int product_code;
public invoice_product_list(){
}
public invoice_product_list(String product_name,double
product_price,int product_qty,int product_code){
this.product_name = product_name;
this.product_price = product_price;
this.product_qty = product_qty;
this.product_code = product_code;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_code() {
return product_code;
}
public void setProduct_code(int product_code) {
this.product_code = product_code;
}
public double getProduct_price() {
return product_price;
}
public void setProduct_price(double product_price) {
this.product_price = product_price;
}
public int getProduct_qty() {
return product_qty;
}
public void setProduct_qty(int product_qty) {
this.product_qty = product_qty;
}
}
Add item to your list that you're using in adapter and (after verifying adapter is not null ) call method notifyDataSetChanged () on adapter object.
create_invoice activity
//arraylist
ArrayList<invoice_product_list> productList = new ArrayList<>();
//customAdapter
customAdapterInvoice = new custom_adapter_invoice
(Create_invoice.this, productList);
customAdapterInvoice.addProduct(products)
custom Adapter
public class custom_adapter_invoice extends ArrayAdapter <invoice_product_list>
{
ArrayList<invoice_product_list> productList = new ArrayList<>();
public custom_adapter_invoice(Context context,
ArrayList<invoice_product_list> product_details) {
super(context, R.layout.custom_row_invoice_item, product_details);
this.productList =product_details
}
public void addProduct(Product products
productList.add(products);
notifyDataSetChanged();
}
......
}
No,it does not change anything. If you want the latest method of working then I would prefer RecyclerView to custom list adapter. this link is very good for recyclerview
recyclerview demo series link

android setting onclicklistener on button in listview

Updated!
I've created a custom listview and so far i've tried implementing listeners on a button but it doesnt work
here's my main activity
public class homepage extends Activity {
ListView list;
String[] Name = {
"Lovelle Ong",
"Ryan Lopez",
"Melissa Gan"
} ;
String[] Location = {
"Botanical Gardens",
"Cape Town",
"Gardens By the Bay"
} ;
Integer[] imageId = {
R.drawable.lovelle,
R.drawable.ryanlopez,
R.drawable.melissa
};
Integer[] mainId = {
R.drawable.likedpage1,
R.drawable.commentpage,
R.drawable.melissap
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
CustomList adapter = new
CustomList(homepage.this, Name, Location, imageId, mainId);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setClickable(true);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + Name [position], Toast.LENGTH_LONG)
.show(); //this doesn't work too
}
});
ImageButton back = (ImageButton) findViewById(R.id.imageButton1);
back.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), MainPage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
}
}
my adapter class
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] Name, Location;
private final Integer[] imageId, mainId;
public CustomList(Activity context,
String[] Name, String[] Location, Integer[] imageId, Integer[] mainId) {
super(context, R.layout.list_single, Name);
this.context = context;
this.Name = Name;
this.imageId = imageId;
this.Location = Location;
this.mainId = mainId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView name = (TextView) rowView.findViewById(R.id.textView1);
TextView location = (TextView) rowView.findViewById(R.id.textView2);
ImageView profileView = (ImageView) rowView.findViewById(R.id.imageView1);
Button mainImage = (Button) rowView.findViewById(R.id.profilepagelist1);
Button comment = (Button) rowView.findViewById(R.id.buttonComment);
final Button emptyheart = (Button) rowView.findViewById(R.id.imageView3);
final Button filledheart = (Button) rowView.findViewById(R.id.ImageViewRight);
emptyheart.setOnClickListener(new View.OnClickListener() //thisworks
{
#Override
public void onClick(View v) {
emptyheart.setVisibility(View.INVISIBLE);
filledheart.setVisibility(View.VISIBLE);
}
});
filledheart.setOnClickListener(new View.OnClickListener() //thisworks
{
#Override
public void onClick(View v) {
emptyheart.setVisibility(View.VISIBLE);
filledheart.setVisibility(View.INVISIBLE);
}
});
comment.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
Log.d("fail", null, null);
// this.startActivity(new Intent(getBaseContext().this, commentpage.class)); <---- errors here
}
});
name.setText(Name[position]);
location.setText(Location[position]);
profileView.setImageResource(imageId[position]);
mainImage.setBackgroundResource(mainId[position]);
return rowView;
}
}
my list_single.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.muc2.MainActivity"
tools:ignore="MergeRootFrame" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/mega1">
<LinearLayout
android:layout_width="match_parent"
android:paddingLeft="2dp"
android:paddingTop="2dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="5dp"
>
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/nameholders"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:paddingLeft="5dp"
android:text="Lovelle Ong"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/buttonComment"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_toLeftOf="#+id/imageView3"
android:background="#drawable/comment" />
<ImageView
android:id="#+id/imageView3"
android:layout_alignParentRight="true"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="#drawable/like" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_alignParentLeft="true"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView2"
android:layout_width="23dp"
android:layout_height="23dp"
android:src="#drawable/geoicon" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="2dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="5dp"
android:paddingLeft="2dp"
android:paddingTop="2dp" >
<Button
android:id="#+id/profilepagelist1"
android:layout_width="fill_parent"
android:layout_height="310dp"
android:layout_centerInParent="true"
android:paddingBottom="5dp"
android:paddingLeft="2dp"
android:paddingRight="2dp" />
</RelativeLayout>
</LinearLayout>
and lastly the xml file that contains the list view
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
tools:context="com.example.muc2.MainActivity$PlaceholderFragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
android:orientation="vertical"
>
<RelativeLayout
android:background="#000000"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#drawable/exit"
android:maxHeight="35dp"
android:maxWidth="35dp"
android:paddingBottom="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="2dp"
android:layout_alignParentRight="false"
/>
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="35dp"
android:layout_height="35dp"
android:background="#drawable/momentlogowhite"
android:maxHeight="35dp"
android:maxWidth="35dp"
android:paddingBottom="2dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="2dp"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Is there a way for me to implement a listener on a button and upon clicking it, it leads me to the next activity?
thanks and sorry for the long post!
i was able to see upon clicking it but when i put an intent for it to
switch from one activity to another it came with errors. i only used
the log.d to find out whether the button work
startActivity is a method of Activity class. So you need Activity Context. You already have
this.context = context;
So Use
context.startActivity(new Intent(context, commentpage.class));

Shortcuts for removing and editing in a listview in android

I have a listview that is a list of events. For each event, I want to have shortcut icons right next to its title for editing and removing. If I tab one of those, it should bring me to another Intent for editing/removing events. How do I achieve this?
My xml has a listview like this:
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
and for each text view:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
Thank you!
What you need to do is to create a custom Adapter and override the getView method like so:
private class MySecondAdapter extends ArrayAdapter<MiniTask>
{
private ArrayList<MiniTask> list;
public MySecondAdapter(Context context, int textViewResourceId, ArrayList<MiniTask> miniTaskList)
{
super(context, textViewResourceId, miniTaskList);
this.list = new ArrayList<MiniTask>();
this.list.addAll(miniTaskList);
}
public View getView(final int position, View convertView, ViewGroup parent)
{
miniTask = miniTaskList.get(position);
ViewHolder holder = new ViewHolder();
{
LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.check_list_item_new, null);
holder.title = (TextView) convertView.findViewById(R.id.tvItemTitle);
holder.commentsPicturesButton = (ImageView) convertView.findViewById(R.id.iAddCommetOrPicture);
holder.commentsPicturesButton.setTag(position);
holder.commentsPicturesButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(getApplicationContext(), PicturesAndCommentsActivity.class);
intent.putExtra(TasksListActivity.KEY_ID, task.getId());
intent.putExtra("mini_task_text", miniTask.getTitle());
startActivity(intent);
}
});
holder.selected = (CheckBox) convertView.findViewById(R.id.cbCheckListItem);
holder.selected.setTag(position);
holder.selected.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
{
Log.d(TAG, "pressed the checkbox: " + v.getId() + " in position: " + position + " tag: " +v.getTag() +" and item from array: " + miniTaskList.get(position) );
CheckBox checkbox = (CheckBox) v;
miniTaskList.get(position).setSelected(checkbox.isChecked());
numOfCheckedMiniTasks = 0;
for(int i=0;i<miniTaskList.size();i++)
{
miniTask = miniTaskList.get(i);
if(miniTask.isSelected())
{
numOfCheckedMiniTasks ++;
}
}
int percent = (int)(numOfCheckedMiniTasks * 100.0f) / miniTaskList.size();
Log.d(TAG, "the percentage is: " +percent);
tasksRepository.get(tasksRepository.indexOf(task)).setMiniTasksPercentageComplete(percent);
}
}
});
}
holder.title.setText(miniTask.getTitle());
holder.selected.setChecked(miniTask.isSelected());
return convertView;
}
}
In this case I have a checkbox for every row as well, you can ignore it, and the holder is:
static class ViewHolder
{
TextView title;
CheckBox selected;
ImageView commentsPicturesButton;
}
While the XML layout for every row is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/try2"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cbCheckListItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/checkbox_checklist_selector"
android:button="#drawable/checkbox_checklist_selector" />
<TextView
android:id="#+id/tvItemTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="10dp"
android:paddingTop="13dp"
android:text="#string/checklist_item_string"
android:textColor="#color/my_darker_gray" />
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:paddingTop="6.5dp" >
<ImageView
android:id="#+id/iAddCommetOrPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:contentDescription="#drawable/comment_or_photo_icon"
android:src="#drawable/comment_or_photo_icon" />
</RelativeLayout>
UPDATE:
holder.iParameterWidget.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
currentParameterPosition = position;
}
}
for this you have to create your custom row separately. There are plenty of example you can find. You can see following links to start
http://androidzoo.wordpress.com/2011/10/28/working-with-listview-in-android-customize-listview-add-item-via-a-button-click-and-also-clickable-each-button-in-each-row/
http://www.geekmind.net/2009/11/android-custom-list-item-with-nested.html

How to add/remove item from listview in android when click button in item listview

I'm a newbie android.I have some problem about my mini app.
You can see figure below:
http://i481.photobucket.com/albums/rr175/viethungit/android.png
Firstly,row 1(layout 1) appear listview when click button add in row 1, row 2(layout 2) appear, and continue...click button add in row 1 ,layout 2 appear in listview....
I try search from Mr.Google but i don't find...
Anybody could help me!
This is layout, and activity I don't know how to implement
add_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#EEEEEE"
android:orientation="horizontal"
android:padding="5dip">
<!-- Image Item-->
<ImageButton
android:id="#+id/imgItem"
android:layout_width="40dip"
android:layout_height="40dip"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="2dp"
android:contentDescription="#string/imgView" />
<!-- Name item -->
<EditText
android:id="#+id/edtItem"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/imgItem"
android:background="#drawable/bg"
android:hint="#string/txtTitle"
android:textSize="20dip" />
<!-- Button add -->
<Button
android:id="#+id/btnAdd"
android:background="#drawable/add"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"/>
<!-- item -->
<TextView
android:id="#+id/txtSubtitle"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_toLeftOf="#+id/btnAdd"
android:gravity="right|center_vertical"
android:layout_centerVertical="true"
android:textSize="20dip"
android:text="#string/txtSubtitle" />
</RelativeLayout>
plus_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#EEEEEE"
android:orientation="horizontal"
android:padding="5dip" >
<!-- Image Item -->
<ImageView
android:id="#+id/imgItem"
android:src="#drawable/chomsao"
android:layout_width="40dip"
android:layout_height="40dip"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="2dp"
android:contentDescription="#string/imgView" />
<!-- Name Item -->
<TextView
android:id="#+id/edtItem"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/imgItem"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:text="#string/txtTitle"
android:textSize="20dip" />
<!-- Quantity Item -->
<TextView
android:id="#+id/txtQtyItem"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_toRightOf="#id/edtItem"
android:layout_marginLeft="20dp"
android:gravity="center_vertical"
android:textSize="20dip"
android:text="#string/QuantityItem"/>
<!-- Button plus -->
<Button
android:id="#+id/btnPlus"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#drawable/plus" />
<!-- Button minus -->
<Button
android:id="#+id/btnMinus"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_alignBaseline="#id/btnPlus"
android:layout_toLeftOf="#+id/btnPlus"
android:background="#drawable/minus" />
<!-- Price Item -->
<TextView
android:id="#+id/txtSubtitle"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/btnMinus"
android:gravity="right|center_vertical"
android:text="#string/txtSubtitle"
android:textSize="20dip" />
</RelativeLayout>
activity_main.xml
<RelativeLayout
android:id="#+id/relative1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/relative"
android:layout_above="#id/relative2"
android:background="#EEEEEE"
android:layout_marginLeft="1.5dp"
android:layout_marginRight="1.5dp"
android:layout_marginTop="1.5dp">
<ListView
android:id="#+id/listSale"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
public class AndroidCustomListViewActivity extends Activity {
private ListView myList;
private MyAdapter myAdapter;
private ImageView myImage;
public static String upload= " ";
public static String GalleryImage;
public ArrayList<ListItem> myItems = new ArrayList<ListItem>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listandimage);
myList = (ListView) findViewById(R.id.MyList);
myImage= (ImageView)findViewById(R.id.image1);
myList.setItemsCanFocus(true);
myAdapter = new MyAdapter();
ListItem listItem = new ListItem();
listItem.textdata="#";
listItem.caption = "";
myItems.add(listItem);
myList.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
}
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return myItems.size();
}
public ListItem getItem(int position) {
return myItems.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item, null);
holder.text=(TextView )convertView.findViewById(R.id.textView1);
holder.captionEditText = (EditText) convertView.findViewById(R.id.ItemCaption);
holder.addOrDeleteButton = (Button) convertView.findViewById(R.id.buttonAdd);
holder.captionEditText.setFocusable(true);
holder.captionEditText.requestFocus();
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Fill EditText with the value you have in data source
// holder.captionEditText.setId(position);
holder.text.setTag(position);
holder.captionEditText.setTag(position);
holder.captionEditText.setText(getItem(position).caption);
holder.addOrDeleteButton.setTag(position);
// / this updates tag of
// the button view as we
// scroll ///
holder.addOrDeleteButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
int tag = (Integer) view.getTag();
if (tag != (myItems.size() - 1)) {
myItems.remove(tag);
Log.d("GCM", "Item removed from " + tag);
myAdapter.notifyDataSetChanged();
} else {
ListItem listItem = new ListItem();
listItem.textdata="#";
listItem.caption = "";
myItems.add(listItem);
/*
* Log.d("GCM", holder.captionEditText.getText()
* .toString()); myItems.get((Integer)
* view.getTag()).caption = holder.captionEditText
* .getText().toString();
*/
myAdapter.notifyDataSetChanged();
myList.setSelection(myAdapter.getCount() - 1);
// holder.captionEditText.setFocusable(true);
// holder.captionEditText.requestFocus();
}
}
});
holder.captionEditText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
// if(position < myItems.size())
// getItem(position).caption = s.toString();
myItems.get((Integer) holder.captionEditText.getTag()).caption = holder.captionEditText
.getText().toString();
}
});
if (position != (myItems.size() - 1)) {
holder.addOrDeleteButton.setBackgroundResource(R.drawable.fruttarecloseicon);
} else {
holder.addOrDeleteButton.setBackgroundResource(R.drawable.fruttareaddicon);
holder.text.setFocusable(true);
holder.captionEditText.setFocusable(true);
holder.text.requestFocus();
holder.captionEditText.requestFocus();
}
return convertView;
}
}
class ViewHolder {
TextView text;
EditText captionEditText;
Button addOrDeleteButton;
}
class ListItem {
String textdata;
String caption;
}
}
use this code edit it according to your need.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
>
<TextView
android:id="#+id/textView1"
android:layout_width="15dp"
android:layout_height="50dp"
android:text=" #"
/>
<EditText
android:id="#+id/ItemCaption"
android:layout_width="270dp"
android:layout_height="50dp"
android:layout_margin="3dip"
android:imeOptions="actionDone|flagNoExtractUi"
android:inputType="textNoSuggestions"
android:singleLine="true" >
</EditText>
<Button
android:id="#+id/buttonAdd"
android:layout_width="75dp"
android:layout_height="50dp"
android:layout_margin="3dip"
/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff"
android:orientation="horizontal" >
<ListView
android:id="#+id/MyList"
android:layout_width="370dp"
android:layout_height="160dp"
android:layout_gravity="center|top"
android:layout_marginLeft="150dp"
android:descendantFocusability="beforeDescendants"
>
</ListView>
<ImageView
android:id="#+id/image1"
android:layout_width="80dp"
android:layout_height="80dp"
/>
</LinearLayout>
mark the answer right if it was useful!!
You can create Elements (like Buttons, Views, and so on) and add them to an existing View like:
myListView.addChild(CreatedButton);

Categories

Resources