I am attempting to make a custom view that uses buttons, however, the android:Onclick for the two buttons cause the app to crash. The ClickListeners don't work either.
The error I am getting from running the debug tool is :
java.lang.IllegalStateException: Could not find a method addMenu(View) in the activity class com.android.tools.fd.runtime.BootstrapApplication for onClick handler on view class android.widget.Button with id 'increase'
This is My java code :
public class MenuItems extends LinearLayout{
private View plusButton;
private View negateButton;
private EditText priceBox;
private TextView total;
private TextView name;
private int totalItems;
private double totalPrice;
private double price;
public MenuItems(Context context) {
super(context);
init();
}
public MenuItems(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public void init()
{
LayoutInflater inflater=LayoutInflater.from(getContext());
inflater.inflate(R.layout.menu_item,this);
plusButton=findViewById(R.id.increase);
negateButton=findViewById(R.id.decrease);
total=(TextView)findViewById(R.id.total);
name=(EditText)findViewById(R.id.ItemName);
priceBox=(EditText)findViewById(R.id.Price) ;
total.setText("5");
negateButton.setBackgroundColor(Color.RED);
plusButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
plusButton.setBackgroundColor(Color.RED);
increase();
}
});
negateButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
decrease();
negateButton.setBackgroundColor(Color.RED);
}
});
price=0;
totalItems=0;
upDateTotal();
String pString=priceBox.getText().toString();
price=Double.parseDouble(pString);
}
public void increase(View view)
{
totalItems++;
upDateTotal();
System.out.println("plus");
plusButton.setBackgroundColor(Color.RED);
}
public void decrease(View v)
{
if(totalItems>0)
totalItems--;
upDateTotal();
System.out.println("minus");
}
This is all of my 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:id="#+id/menu_items"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.mohs.joey.seniorproject.MenuItems">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/ItemName"
android:layout_weight="1"
android:textColor="#color/colorAccent"
android:text="name" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/Price"
android:textColor="#color/colorAccent"
android:hint="Price"
android:shadowColor="#color/colorAccent"
android:text="0.00" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:text="-"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:id="#+id/decrease"
android:layout_weight="1"
android:backgroundTint="#color/colorAccent"
android:onClick="increase"/>
<TextView
android:text="Amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/total"
android:layout_weight="1"
android:textColor="#color/colorAccent" />
<Button
android:text="+"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:id="#+id/increase"
android:layout_weight="1"
android:backgroundTint="#color/colorAccent"
android:elevation="0dp"
android:onClick="increase" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
I access MenuItems in this Method in a separate class :
public void addMenu(View view)
{
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.menu_item, null);
v.setId(menu);
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.backLayer);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
menu++;
}
This is my new main activity:
package com.mohs.joey.seniorproject;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
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.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
public class ConcessionMenus extends AppCompatActivity {
int menu=0;
private View plusButton;
private View negateButton;
private EditText priceBox;
private TextView total;
private TextView name;
private int totalItems;
private double totalPrice;
private double price;
PopupWindow popup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_concession_menus);
plusButton=findViewById(R.id.increase);
negateButton=findViewById(R.id.decrease);
total=(TextView)findViewById(R.id.total);
name=(EditText)findViewById(R.id.ItemName);
priceBox=(EditText)findViewById(R.id.Price) ;
// TextView totalPrice=(TextView)findViewById(R.id.totalPrice);
}
public void addMenu(View view)
{
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vw = vi.inflate(R.layout.menu_item, null);
vw.setId(menu);
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.backLayer);
insertPoint.addView(vw, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
menu++;
}
public Intent newIntent()
{
Intent intent=new Intent(this,Menu.class);
return intent;
}
public void increase(View v)
{
totalItems++;
upDateTotal();
System.out.println("plus");
plusButton.setBackgroundColor(Color.RED);
}
public void decrease(View v)
{
if(totalItems>0)
totalItems--;
upDateTotal();
System.out.println("minus");
}
public void upDateTotal()
{
total.setText(""+totalItems);
totalPrice=price*totalItems;
}
public double totalPrice()
{
return totalPrice;
}
}
Any help would be appreciated.
The problem is when the button want to perform the action when you click on it , it should be able to find the method increase() in your MainActivity class , since the method increase() is on an other class , the button will never find the method and they will crash because you set the your layout xml to your main activity not for the class MenuItem , to fix that just move these to methods to your MainActivity class
OR
Pass a reference of your buttons to the class MenuItems and do what you want there
PS : the ids can be found by typing R.id , but you cannot work with these id since you set the content view to your MainActivity
Related
RecyclerView Adapter Class
package com.ajitapp.smartwork.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.ajitapp.smartwork.ChooseAddressActivity;
import com.ajitapp.smartwork.Interfaces.AddressClickListener;
import com.ajitapp.smartwork.Interfaces.CartClickListListener;
import com.ajitapp.smartwork.R;
import com.ajitapp.smartwork.models.AddressModal;
import com.ajitapp.smartwork.models.CartModel;
import java.util.List;
public class AddressListAdapter extends RecyclerView.Adapter<AddressListAdapter.MyViewHolder> {
private List<AddressModal> arrayList;
private Context context;
private AddressClickListener cartClickListListener;
public int mSelectedItem = -1;
private RadioButton lastCheckedRB = null;
public AddressListAdapter(Context applicationContext, List<AddressModal> arrayList, ChooseAddressActivity cartClickListListener) {
this.arrayList = arrayList;
this.context = applicationContext;
this.cartClickListListener = cartClickListListener;
}
#NonNull
#Override
public AddressListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.choose_address_row_item, parent, false);
context = parent.getContext(); //to get the activity context use this line.
final AddressListAdapter.MyViewHolder myViewHolder = new AddressListAdapter.MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(#NonNull AddressListAdapter.MyViewHolder holder, final int position) {
holder.addr1.setText(arrayList.get(position).getAddr1());
holder.addr2.setText(arrayList.get(position).getAddr2());
holder.city.setText(arrayList.get(position).getCity());
holder.state.setText(arrayList.get(position).getCity());
holder.country.setText(arrayList.get(position).getCountry());
holder.postalCode.setText(arrayList.get(position).getPostalCode());
holder.radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mSelectedItem=position;
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView addr1, addr2, city, state, country, postalCode;
private TextView subtask_description_tv;
private TextView subtask_price_tv;
private Button incrementBtn, decrementBtn;
private TextView display_data;
private TextView total_price_tv;
private RadioButton radioButton;
int total_price;
public MyViewHolder(#NonNull final View itemView) {
super(itemView);
addr1 = itemView.findViewById(R.id.addr1);
addr2 = itemView.findViewById(R.id.addr2);
city = itemView.findViewById(R.id.city);
state = itemView.findViewById(R.id.state);
country = itemView.findViewById(R.id.country);
postalCode = itemView.findViewById(R.id.postalCode);
radioButton = itemView.findViewById(R.id.addressRadioButton);
}
}
}
Item Row
<?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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/toolbar_address_list"
android:padding="5dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
app:navigationIcon="#drawable/ic_arrow_back"
android:background="#color/colorPrimary"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose an address"
android:textStyle="bold"
android:textColor="#color/white"
android:textSize="20sp"
/>
</androidx.appcompat.widget.Toolbar>
<ImageView
android:id="#+id/locationImage"
android:layout_width="match_parent"
android:layout_height="150dp"
android:src="#drawable/address"
android:layout_marginTop="20dp"
android:layout_below="#+id/toolbar_address_list"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_add"
android:id="#+id/add_address"
android:text="Add new address"
android:layout_below="#id/locationImage"
android:layout_marginBottom="10dp"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"
android:drawablePadding="5dp"
android:textSize="18sp"
android:textStyle="bold"
/>
<androidx.recyclerview.widget.RecyclerView
android:layout_marginLeft="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_below="#+id/add_address"
android:id="#+id/address_list" />
<Button
android:id="#+id/buy_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="Continue"
android:drawableRight="#drawable/ic_arrow_forward"
android:background="#color/colorPrimary"
android:textColor="#color/white"
android:textSize="20sp"
android:layout_marginBottom="10dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:elevation="10dp"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
I want to click one Radio Button in Recycler View, but I failed to do that. I have tried all the possibilities, but I failed to try from everywhere. I want to click one Radio Button in Recycler View, but I failed to do that. I have tried all the possibilities, but I failed to try from everywhere.
First you need condition like this for your UI in your onBindViewHolder method
if (mSelectedItem == position) {
holder.radioButton.setChecked(true);
} else {
holder.radioButton.setChecked(false);
}
Then change your radio button listener like this
holder.radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mSelectedItem = position;
} else {
mSelectedItem = -1;
}
notifyDataSetChanged();
}
});
try this i hope your problem will solve.
I have a screen that shows my movie names and their pictures which are in my Firebase. It shows them with the pictures.
My database's structure is like this. name is the string which is the name of my movie. profilePic is the string that contains the picture link from Firebase storage.
What I want is, when I click on any picture which are listed, I want to display it on another activity with bigger size (like opening someone's WhatsApp or Facebook profile picture)
These are my classes that works perfectly. How can I do this?
Movies.java
package com.example.XXXX;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Movies extends AppCompatActivity {
DatabaseReference reference;
RecyclerView recyclerView;
ArrayList<Profile> list;
MyAdapter adapter;
private String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview_films);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
reference = FirebaseDatabase.getInstance().getReference().child("Films");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list = new ArrayList<Profile>();
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
Profile p = dataSnapshot1.getValue(Profile.class);
list.add(p);
}
adapter = new MyAdapter(Movies.this,list);
recyclerView.setAdapter(adapter);
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Movies.this,"Ooops... Something is wrong.",Toast.LENGTH_SHORT).show();
}
});
Intent intent = getIntent();
message = intent.getStringExtra("EXTRA_MESSAGE");
ImageButton backButton = (ImageButton) findViewById(R.id.imageButton13);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Movies.this, Menu.class);
i.putExtra("EXTRA_MESSAGE",message);
startActivity(i);
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(Movies.this, Menu.class);
i.putExtra("EXTRA_MESSAGE",message);
startActivity(i);
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
}
}
MyAdapter.java
package com.example.XXXX;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
Context context;
ArrayList<Profile> profiles;
public MyAdapter(Context c, ArrayList<Profile> p){
context = c;
profiles = p;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.cardview,viewGroup, false));
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.name.setText(profiles.get(i).getName());
Picasso.get().load(profiles.get(i).getProfilePic()).into(myViewHolder.profilePic);
}
#Override
public int getItemCount() {
return profiles.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView name;
ImageView profilePic;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.film_name);
profilePic = (ImageView) itemView.findViewById(R.id.filmProfile);
}
}
}
Profile.java
package com.example.XXXX;
public class Profile {
private String name;
private String profilePic;
public Profile() {
}
public Profile(String name, String profilePic) {
this.name = name;
this.profilePic = profilePic;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
}
activity_movies.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".Movies"
android:background="#drawable/background">
<include
android:id="#+id/toolbar_movies"
layout="#layout/toolbar_movies" />
<RelativeLayout
android:id="#+id/loadingPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center" >
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />
</RelativeLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="88dp"
android:layout_marginBottom="10dp">
<LinearLayout
android:id="#+id/layoutoffilms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="1"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview_films"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</ScrollView>
</LinearLayout>
cardview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#drawable/border"
android:layout_marginTop="10dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="#+id/filmProfile"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/film_name"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:layout_gravity="center_vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.08"
android:textSize="20sp"/>
</LinearLayout>
</LinearLayout>
Modify view holder with view as
class MyViewHolder extends RecyclerView.ViewHolder
{
TextView name;
ImageView profilePic;
View mView;
public MyViewHolder(#NonNull View itemView)
{
super(itemView);
mView = itemView;
name = (TextView) itemView.findViewById(R.id.film_name);
profilePic = (ImageView) itemView.findViewById(R.id.filmProfile);
}
}
Implement on click listener of view holder in adapter, then start the activity with image url.
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.name.setText(profiles.get(i).getName());
Picasso.get().load(profiles.get(i).getProfilePic()).into(myViewHolder.profilePic);
mViewHolder.mView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startImageActivity(profiles.get(i).getProfilePic());
}
});
}
3.Create activity and start with image view of required dimension.
void startImageActivity(String imgUrl)
{
Intent intent = new Intent(context,ViewImage.class);
intent.putExtra("profilePic",imgUrl);
context.startActivity(intent);
}
Or to open image in an external application try
void startImageActivity(String imgUrl)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(imgUrl));
context.startActivity(intent);
}
Resize your bitmap:
Bitmap resizedBitmap = Bitmap.createScaledBitmap(
originalBitmap, newWidth, newHeight, false);
You can use this library for the zoom in and zoom out functionality like this is the link Zoom library
You need to add this gradle in your project
implementation 'com.otaliastudios:zoomlayout:1.6.1'
Check this example layout below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dark_grey"
android:orientation="vertical"
android:weightSum="13">
<ImageView
android:id="#+id/iv_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_margin="#dimen/margin_small"
android:padding="#dimen/margin_small"
android:src="#drawable/ic_skip" />
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="6" />
<com.otaliastudios.zoom.ZoomImageView
android:id="#+id/zoom_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:scrollbars="vertical|horizontal"
app:alignment="center"
app:animationDuration="280"
app:flingEnabled="true"
app:horizontalPanEnabled="true"
app:maxZoom="2.5"
app:maxZoomType="zoom"
app:minZoom="0.7"
app:minZoomType="zoom"
app:overPinchable="true"
app:overScrollHorizontal="true"
app:overScrollVertical="true"
app:transformation="centerInside"
app:transformationGravity="auto"
app:verticalPanEnabled="true"
app:zoomEnabled="true" />
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="5" />
</LinearLayout>
And in the JAVA class you need to load the image like below, I am using the Glide for the image loading like below
GlideApp.with(this)
.asBitmap()
.load(YOUR_IMAGE_URL)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
YOUR_IMAGEVIEW.setImageBitmap(resource);
}
});
Check the ZoomActivity.java for the demo purpose like below
public class ZoomActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_zoom);
// ActivityZoomBinding mBinding = DataBindingUtil.setContentView(this, R.layout.activity_zoom);
ImageView zoomImage = findViewById(R.id.zoom_image);
///GETTING INTENT DATA
Intent intent = getIntent();
if (intent.hasExtra("ZOOM_IMAGE")) {
String imageUrl = intent.getStringExtra("ZOOM_IMAGE");
GlideApp.with(this)
.asBitmap()
.load(imageUrl)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
zoomImage.setImageBitmap(resource);
}
});
}
}
}
I need to pass the data from one activity to a ListView inside another activity. Currently I have set a single TextView to see all the details in second activity. But instead I need to view those items in ListView with adapter for each item.
MainActivity.java:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {
String[] place={"Karur","Salem","Namakkal","Trichy","Madurai"};
EditText Name;
EditText Email;
EditText Number;
Button submit;
RadioGroup radioGroup;
RadioButton maleradioButton,femaleradioButton;
CheckBox BEcheckbox,MEcheckbox;
Spinner spin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spin = (Spinner)findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item, place);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
Name = (EditText)findViewById(R.id.Name);
Email = (EditText)findViewById(R.id.Email);
Number = (EditText)findViewById(R.id.Number);
submit = (Button)findViewById(R.id.submit);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
//// maleradioButton = (RadioButton)findViewById(R.id.maleradioButton);
femaleradioButton = (RadioButton)findViewById(R.id.femaleradioButton);
BEcheckbox = (CheckBox)findViewById(R.id.BEcheckBox);
MEcheckbox = (CheckBox)findViewById(R.id.MEcheckbox);
final RadioGroup rgroup = (RadioGroup)findViewById(R.id.radioGroup);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String spinText = spin.getSelectedItem().toString();
String name = Name.getText().toString();
String email = Email.getText().toString();
String number = Number.getText().toString();
String val="";
String radio;
if (BEcheckbox.isChecked()) {
val="BE";
} if(MEcheckbox.isChecked()) {
val="ME";
}
int select=rgroup.getCheckedRadioButtonId();
maleradioButton=(RadioButton)findViewById(select);
radio=maleradioButton.getText().toString();
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("Name",name);
intent.putExtra("Email",email);
intent.putExtra("Number",number);
intent.putExtra("Degree",val);
intent.putExtra("Gender",radio);
intent.putExtra("Place",spinText);
startActivity(intent);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
SecondActivity.java:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SecondActivity extends Activity {
String Name;
String Email;
String Number;
String Degree;
String Gender;
String Place;
TextView result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
result = (TextView)findViewById(R.id.result);
Name = getIntent().getExtras().getString("Name");
Email = getIntent().getExtras().getString("Email");
Number = getIntent().getExtras().getString("Number");
Degree = getIntent().getExtras().getString("Degree");
Gender = getIntent().getExtras().getString("Gender");
Place = getIntent().getExtras().getString("Place");
result.setText("Name:"+""+Name +'\n'+"Email"+" "+Email+'\n'+"Number:"+" "+Number+'\n'+"Degree:"+" "+Degree+'\n'+"Gender:"+" "+Gender+'\n'+"Place:"+" "+Place);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="arun.com.project.MainActivity">
<EditText
android:id="#+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/Email"
android:ems="10"
android:hint="Enter your Name"
android:inputType="textPersonName" />
<EditText
android:id="#+id/Email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Name"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Enter your Email"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/Email"
android:layout_below="#+id/Email"
android:ems="10"
android:hint="Enter your Mobile Number"
android:inputType="phone" />
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/Number"
android:id="#+id/radioGroup">
<CheckBox
android:id="#+id/BEcheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/radioGroup"
android:layout_marginTop="74dp"
android:layout_weight="1"
android:text="BE" />
<CheckBox
android:id="#+id/MEcheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="ME" />
<RadioButton
android:id="#+id/maleradioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Male" />
<RadioButton
android:id="#+id/femaleradioButton"
android:layout_width="442dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Female" />
</RadioGroup>
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="11dp"
android:text="SUBMIT"
android:textColor="#ffffff"
android:background="#color/colorPrimaryDark"/>
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/submit"
android:layout_alignParentStart="true"
android:layout_marginBottom="27dp" />
</RelativeLayout>
activity_second.xml:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="arun.com.project.SecondActivity">
<TextView
android:id="#+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="55dp"
android:layout_marginTop="43dp"
android:text="TextView"
android:textColor="#000000"
android:textSize="16sp"/>
</RelativeLayout>
I've just used single TextView to see the details whatever I have entered in MainActivity.java. But now I need to show the details in ListView with each details (name, email, number, etc...) in a separate adapter.
If you want to display many information inside a row of ListView. Create a custom Adapter for your ListView and custom POJO class to store multiple field of data in single object.
Create Info.java:
class Info {
String name;
String email;
public Info(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() { return name; }
public String getEmail() { return email; }
}
Create row.xml to make custom layout for a single row of your ListView:
<?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="match_parent"
android:orientation="vertical" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/name"
android:text="Name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:id="#+id/email"/>
</LinearLayout>
Define an adapter to create rows and populate data on your rows. Create InfoAdapter.java:
class InfoAdapter extends BaseAdapter {
Context context;
List<Info> data;
private static LayoutInflater inflater = null;
public InfoAdapter(Context context, List<Info> data) {
// TODO Auto-generated constructor stub
this.context = context;
this.data = data;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.length;
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (vi == null)
vi = inflater.inflate(R.layout.row, null);
TextView name = (TextView) vi.findViewById(R.id.name);
TextView email = (TextView) vi.findViewById(R.id.email);
name.setText(data.get(position).getName());
email.setText(data.get(position).getEmail());
return vi;
}
}
Put ListView inside your activity_second.xml and config the layout whatever you want.
<ListView
android:id="#+id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
Inside SecondActivity.java create a ListView instance and array of data:
listView = (ListView) findViewById(R.id.list);
//Getting extras (Name, Email,..)
listInfo.add(new Info(Name, Email,...); //Create Info object base on extras information
Init adapter and set:
InfoAdapter adapter = new InfoAdapter(this, listInfo);
listView.setAdapter(adapter);
I am new to android. I have created material design Grid View. Now what I want to do, when I click on each grid view it should take to me each new activity. When i click on ALPHABETS it will go to ListAlphabet.java. Thank you for help.
My activity_main.xml is :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/android_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:id="#+id/appbar_layout"
android:layout_height="#dimen/app_bar_height"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar_android_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="#dimen/expanded_toolbar_title_margin_start"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="#drawable/code"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:id="#+id/nestedscrollview"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="#+id/grid"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:gravity="center"
android:listSelector="#00000000"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
gridview_custom_layout.xml is :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/android_gridview_custom_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<com.andexert.library.RippleView
android:id="#+id/more"
rv_centered="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:rv_color="#fff"
app:rv_rippleDuration="200">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linearLayout"
android:orientation="vertical">
<ImageView
android:id="#+id/gridview_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/gridview_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/grid_image"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Grid View Item"
android:textColor="#444"
android:textSize="12sp"
android:textStyle="bold" />
</LinearLayout>
</com.andexert.library.RippleView>
</LinearLayout>
MainActivity.java is :
package com.affinityapp.sj.alphabet;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.GridView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayoutAndroid;
CoordinatorLayout rootLayoutAndroid;
GridView gridView;
Context context;
ArrayList arrayList;
public static String[] gridViewStrings = {
"ALPHABETS",
"NUMBERS",
"MONTH",
"DAYS",
"ANIMALS",
"CALL US",
};
public static int[] gridViewImages = {
R.drawable.icon_alphabet,
R.drawable.icon_number,
R.drawable.icon_calendar,
R.drawable.icon_days,
R.drawable.icon_animal,
R.drawable.icon_call
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gridView = (GridView) findViewById(R.id.grid);
gridView.setAdapter(new CustomAndroidGridViewAdapter(this, gridViewStrings, gridViewImages));
initInstances();
}
private void initInstances() {
rootLayoutAndroid = (CoordinatorLayout) findViewById(R.id.android_coordinator_layout);
collapsingToolbarLayoutAndroid = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_android_layout);
collapsingToolbarLayoutAndroid.setTitle("e-Learning");
}
}
CustomAndroidGridViewAdapter.java is :
package com.affinityapp.sj.alphabet;
/**
* Created by SJ on 23-01-2017.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by HP on 5/11/2016.
*/
public class CustomAndroidGridViewAdapter extends BaseAdapter {
private Context mContext;
private final String[] string;
private final int[] Imageid;
public CustomAndroidGridViewAdapter(Context c,String[] string,int[] Imageid ) {
mContext = c;
this.Imageid = Imageid;
this.string = string;
}
#Override
public int getCount() {
return string.length;
}
#Override
public Object getItem(int p) {
return null;
}
#Override
public long getItemId(int p) {
return 0;
}
#Override
public View getView(int p, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.gridview_custom_layout, null);
TextView textView = (TextView) grid.findViewById(R.id.gridview_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.gridview_image);
textView.setText(string[p]);
imageView.setImageResource(Imageid[p]);
} else {
grid = (View) convertView;
}
return grid;
}
}
So, you can use this way to click grid view:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayoutAndroid;
CoordinatorLayout rootLayoutAndroid;
GridView gridView;
Context context;
ArrayList arrayList;
public static String[] gridViewStrings = {
"ALPHABETS",
"NUMBERS",
"MONTH",
"DAYS",
"ANIMALS",
"CALL US",
};
public static int[] gridViewImages = {
R.drawable.icon_alphabet,
R.drawable.icon_number,
R.drawable.icon_calendar,
R.drawable.icon_days,
R.drawable.icon_animal,
R.drawable.icon_call
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gridView = (GridView) findViewById(R.id.grid);
gridView.setAdapter(new CustomAndroidGridViewAdapter(this, gridViewStrings, gridViewImages));
initInstances();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Do whatever you want, like start new Activity or display new view or display dialog box or display just message
Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
private void initInstances() {
rootLayoutAndroid = (CoordinatorLayout) findViewById(R.id.android_coordinator_layout);
collapsingToolbarLayoutAndroid = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_android_layout);
collapsingToolbarLayoutAndroid.setTitle("e-Learning");
}
}
Hope, this will help you.
Implement onItemClickListener method in you activity:
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
final Intent intent;
switch(position)
{
case 0:
intent = new Intent(context, FirstActivity.class);
break;
case 1:
intent = new Intent(context, SecondActivity.class);
break;
...
default:
intent = new Intent(context, DefaultActivity.class);
break;
}
startActivity(intent);
}
});
Possibly duplicate question...
Research thoroughly before posting a question please.
Answer can be found in this thread: How can I give an imageview click effect like a button on Android?
Edit:
In your current activity, you need to create a variable ImageButton.
ImageButton myButton = (ImageButton) findViewById(R.id.the_button_you_created_on_the_layout.xml);
Then you need to set a click listener to this button
myButton.setOnClickListener(new View.OnClickListner(){
// When the button is pressed/clicked, it will run the code below
#Override
public void onClick()
// Intent is what you use to start another activity
Intent myIntent = new Intent(this, YourActivity.class);
startActivity(intent);
}
});
I am fairly new to Java and Android development. I am currently creating a shopping app and was looking at adding a "Remove" button to my Shopping Cart list.
Here is my current code for my list activity for my shopping cart, I am not really sure where to begin and some guidance would be greatly appreciated.
Thanks
package .shopper;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class CartListActivity extends ListActivity {
public class ProductListAdapter extends BaseAdapter {
private final Context context;
private List<Product> itemList;
public List<Product> getItemList() {
return itemList;
}
public void setItemList(List<Product> itemList) {
this.itemList = itemList;
}
public Context getContext() {
return context;
}
public ProductListAdapter(Context c) {
context = c;
}
#Override
public int getCount() {
if(itemList == null) return 0;
else return itemList.size();
}
#Override
public Object getItem(int position) {
if (itemList == null) return null;
else return itemList.get(position);
}
#Override
public long getItemId(int position) {
if (itemList == null) return 0;
else return itemList.get(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View cell = convertView;
if (cell == null) {
// get layout from mobile xml
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
cell = inflater.inflate(R.layout.adapter_product_list, parent, false);
}
Product p = itemList.get(position);
//set value into textview according to position
TextView textView = (TextView) cell.findViewById(R.id.product_title);
textView.setText(p.getProductName());
// add £ symbol
textView = (TextView) cell.findViewById(R.id.product_info);
textView.setText("Price: " + "£"+ p.getPrice());
//set value into imageview according to position
ImageView imgView = (ImageView) cell.findViewById(R.id.product_image);
// clear the image
imgView.setImageDrawable(null);
//and load from the network
p.loadImage(imgView, 54, 54);
return cell;
}
}
public static final Integer[] productIcons = {
0, // index 0 is empty
R.drawable.books,
R.drawable.films,
R.drawable.music,
R.drawable.games,
};
private int categoryId;
private ProductListAdapter adapter;
private ListViewLoader loader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the category from the intent
Intent intent = getIntent();
categoryId = intent.getIntExtra(MainActivity.SELECTED_CATEGORY, 0);
adapter = new ProductListAdapter(this);
setListAdapter(adapter);
// Show the Up button in the action bar.
setupActionBar();
loader = new ListViewLoader(adapter, categoryId);
loader.execute(String.format(MainActivity.WEBSERVER_GETLIST, categoryId));
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.product_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.show_cart:
//create the intent for the cart activity
Intent intent = new Intent(getApplicationContext(), CartActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
//create an intent
Intent intent = new Intent(this, ProductActivity.class);
Product p = (Product)adapter.getItem(position);
//specify the extra parameters we want to pass
intent.putExtra(MainActivity.SELECTED_CATEGORY, p.getCategoryId());
intent.putExtra(MainActivity.SELECTED_PRODUCTID, p.getProductId());
intent.putExtra(MainActivity.SELECTED_PRODUCTNAME, p.getProductName());
intent.putExtra(MainActivity.SELECTED_PRODUCTPRICE, p.getPrice());
intent.putExtra(MainActivity.SELECTED_SUITABLEFORKIDS, p.getSuitableForKids());
startActivity(intent);
}
}
EDIT:
XML for adapter_product_list
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<ImageView
android:id="#+id/product_image"
android:layout_width="54dp"
android:layout_height="54dp"
android:padding="5dp"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/product_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_alignTop="#+id/product_image"
android:textColor="#446688"
android:textSize="20sp" />
<TextView
android:id="#+id/product_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_below="#+id/product_title"
android:textColor="#777777"
android:textSize="16sp"
android:textStyle="italic" />
</RelativeLayout>
Change your xml like following
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp" >
<ImageView
android:id="#+id/product_image"
android:layout_width="54dp"
android:layout_height="54dp"
android:layout_alignParentLeft="true"
android:padding="5dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/product_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/product_image"
android:layout_toRightOf="#+id/product_image"
android:text="adjkajdjk"
android:textColor="#446688"
android:textSize="20sp" />
<TextView
android:id="#+id/product_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_title"
android:layout_toRightOf="#+id/product_image"
android:text="adjkajdjk"
android:textColor="#777777"
android:textSize="16sp"
android:textStyle="italic" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Delete" />
</RelativeLayout>
And in your adapter inside getView() function add this
Button deleteBtn = (Button) findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
itemList.remove(position);
notifyDataSetChanged();
}
});
1) hope p.loadImage(imgView, 54, 54); is running in a asyncTask
2) if you want to click on a button in a row of a ListView than you shoudl add the button to your row layout and implent onClickListenr of that button in your getView method of adapter.in onClick method yous hould have:
if(position<itemList.size()){
//TO REMOVE TEM FROM ARRAY LIST
itemList.remove(position);
//TO Update the ListView
notifyDataSetChanged();
}
you can implement a multy line delete,by adding a checkbox in your listRow and adding the positon of the item to be deleted to an arrayList of Integers and after click-ing the delete button you should delete all the items from the imteList and after that call notifyDataSetChanged()
EDIT
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<ImageView
android:id="#+id/product_image"
android:layout_width="54dp"
android:layout_height="54dp"
android:padding="5dp"
android:layout_alignParentLeft="true" />
<TextView
android:id="#+id/product_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_alignTop="#+id/product_image"
android:textColor="#446688"
android:textSize="20sp" />
<TextView
android:id="#+id/product_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_image"
android:layout_below="#+id/product_title"
android:textColor="#777777"
android:textSize="16sp"
android:textStyle="italic" />
<Button
android:id="#+id/deleteBtn"
android:layout_width="wrap_content
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/product_info"
</RelativeLayout>
you should add this button to your layout, and in getView method of adapter add
Button delete=v.findViewById(R.id.deleteBtn);
delete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//THE PART I WROTE ABOVE
}
})