Adding a remove button in my item list - java

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
}
})

Related

Refresh/update listview current tab

I have three tabs with an unique fragment. How by images:
3 tab and a fragment
First problem is that when I click on "I watch it" on a movie and swipe on Watched's tab, this tab isn't updated.
https://i.imgur.com/AnnN3Zq.png?1
https://i.imgur.com/DsLGn3r.png
After if I swipe/tap on Notify's tab and comeback on Watched's tab, the tab has been updated. Why? Where am I wrong?
CoreActivity.java
package com.example.msnma.movienotifier;
import android.annotation.TargetApi;
import android.app.FragmentTransaction;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.example.msnma.movienotifier.MoviesFragment;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.Toast;
import com.example.msnma.movienotifier.adapter.MoviesAdapter;
import com.example.msnma.movienotifier.notify.NotificationReceiver;
import com.example.msnma.movienotifier.event.TwoPaneEvent;
import org.greenrobot.eventbus.EventBus;
import butterknife.BindView;
import static android.support.v4.view.PagerAdapter.POSITION_NONE;
import static com.google.common.reflect.Reflection.initialize;
import static java.security.AccessController.getContext;
public class CoreActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
SectionsPageAdapter mSectionsPageAdapter;
#BindView(R.id.movies)
ViewPager mViewPager;
#BindView(R.id.tabs)
TabLayout tabLayout;
boolean twoPane;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_core);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
if (findViewById(R.id.movie_detail) != null) {
twoPane = true;
}
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager(), twoPane);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setOffscreenPageLimit(1);
mViewPager.setAdapter(mSectionsPageAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
final int numTab = tab.getPosition();
//Toast.makeText(getApplicationContext(),tab.getText(), Toast.LENGTH_LONG).show();
switch (tab.getPosition()) {
case 0: {
MoviesAdapter.setTipo(String.valueOf(MoviesFragment.Type.NOTIFY));
break;
}
case 1: {
MoviesAdapter.setTipo(String.valueOf(MoviesFragment.Type.SUGGESTED));
break;
}
case 2: {
MoviesAdapter.setTipo(String.valueOf(MoviesFragment.Type.WATCHED));
break;
}
}
}
});
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//mViewPager.setCurrentItem(position);
// ci sono vicinissimo alla soluzione.
if(position == 0 || position == 2) {
Fragment getFragment = getSupportFragmentManager().getFragments().get(position);
if (getFragment instanceof MoviesFragment) {
MoviesFragment thisFragment = (MoviesFragment) getFragment;
thisFragment.onRefresh();
Log.i("REFRESH","Dovrebbe essere refreshato");
}
Log.i("PAGINASELEZIONATA", "Esegue onResume " + position);
}
//Toast.makeText(CoreActivity.this,"Tab "+position,Toast.LENGTH_LONG).show();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
EventBus.getDefault().postSticky(new TwoPaneEvent(twoPane));
}
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_second, menu);
//MenuItem item = menu.findItem(R.id.search);
//searchView.setMenuItem(item);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
public void pressAccountButton(MenuItem item)
{
Intent intent = new Intent(this, AccountActivity.class);
startActivity(intent);
}
//nuovo codice
#Override
protected void onResume()
{
super.onResume();
if (!(mSectionsPageAdapter == null)) {
mSectionsPageAdapter.notifyDataSetChanged();
Log.i("INFOonResume", "Metodo onResume eseguito");
}
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
//Log.i("INFOTAB", "La tabella selezionata è "+tab.getTag());
onResume();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Tap Notify's tap (believe also could tap on Suggested) and tap again Watched's tap
Second problem
In Watched's tab the textView are cut, why? How can I solve this?
MoviesAdapter.java
package com.example.msnma.movienotifier.adapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.example.msnma.movienotifier.MainActivity;
import com.example.msnma.movienotifier.MoviesFragment;
import com.example.msnma.movienotifier.R;
import com.example.msnma.movienotifier.database.MovieDatabase;
import com.example.msnma.movienotifier.databaseModel.MovieDBModel;
import com.example.msnma.movienotifier.model.Movie;
import java.util.Calendar;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Optional;
import static android.app.PendingIntent.getActivity;
import static com.example.msnma.movienotifier.MoviesFragment.*;
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.ViewHolder>{
private Context context;
private List<Movie> movies;
private View itemView;
private RecyclerView rv;
//per la data
private EditText fromDateEtxt;
private boolean active = false;
//private Context context;
private static String tipo = "NOTIFY";
public MoviesAdapter(Context context, List<Movie> movies) {
this.context = context;
this.movies = movies;
}
#Override
public MoviesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView;
/*if(getTipo().equals("Suggested"))
{
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(itemView);
}
else if(getTipo().equals("Watched"))
{
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie_watched, parent, false);
return new ViewHolder(itemView);
}
else if(getTipo().equals("Notify"))
{*/
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(itemView);
//}
//return null;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
Movie movie = movies.get(position);
Glide.with(context)
.load(movie.getPosterUrl())
.placeholder(R.drawable.poster_placeholder)
.into(holder.posterView);
holder.title_movie.setText(movie.getTitle());
// prende solo la data + anno
String yourString = String.valueOf(movie.getReleaseDate());
String date = yourString.substring(0, 10);
String year = yourString.substring(yourString.length()-5,yourString.length());
holder.release_date.setText(date+year);
if(getTipo().equals("NOTIFY"))
{
Toast.makeText(context,"Notify", Toast.LENGTH_LONG).show();
holder.notifyButton.setVisibility(View.GONE);
holder.watchedButton.setVisibility(View.GONE);
holder.removeButton.setVisibility(View.VISIBLE);
}
//solo se è di tipo suggested
if(getTipo().equals("SUGGESTED"))
{
//disabilitare bottone remove
holder.removeButton.setVisibility(View.GONE);
holder.notifyButton.setVisibility(View.VISIBLE);
holder.watchedButton.setVisibility(View.VISIBLE);
Toast.makeText(context,"Suggested", Toast.LENGTH_LONG).show();
holder.notifyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*String testo = movies.get(position).getTitle().toString();
Toast tostato = Toast.makeText(context,testo,Toast.LENGTH_SHORT);
tostato.show();*/
alertFormElements(position);
}
});
holder.watchedButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*String testo = movies.get(position).getTitle()+ "\n" + "I WATCH IT";
Toast tostato = Toast.makeText(context,testo,Toast.LENGTH_SHORT);
tostato.show();*/
// public MovieDBModel(int id, String title, String overview, String posterUrl, String backdropUrl, String trailerUrl,
// Date releaseDate, float rating, boolean adult){
MovieDBModel mdm = new MovieDBModel(movies.get(position).getId(), movies.get(position).getTitle(), movies.get(position).getOverview(),
movies.get(position).getPosterUrl(), movies.get(position).getBackdropUrl(), movies.get(position).getTrailerUrl(),
movies.get(position).getReleaseDate(), movies.get(position).getRating(), movies.get(position).isAdult());
MovieDatabase.insertMovie(mdm, 2, MainActivity.getMovieDatabase());
String testo = "Added " + movies.get(position).getTitle() + "\n" + "in tab watched";
Toast tostato = Toast.makeText(context, testo, Toast.LENGTH_SHORT);
tostato.show();
}
});
}
if (getTipo().equals("WATCHED"))
{
holder.notifyButton.setVisibility(View.GONE);
holder.watchedButton.setVisibility(View.GONE);
holder.removeButton.setVisibility(View.VISIBLE);
holder.removeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
//da implementare
}
});
Toast.makeText(context,"WATCHED", Toast.LENGTH_LONG).show();
}
}
//nuovo codice riguardo l'alerDialog
public final void alertFormElements(final int position)
{
/*
* Inflate the XML view. activity_main is in
* res/layout/form_elements.xml
*/
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.form_elements,
null, false);
// You have to list down your form elements
/*final CheckBox myCheckBox = (CheckBox) formElementsView
.findViewById(R.id.myCheckBox);*/
final RadioGroup genderRadioGroup = (RadioGroup) formElementsView
.findViewById(R.id.NotifyAlertRadioGroup);
//nuovo codice
genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
switch (checkedId)
{
case R.id.OneDayRadioButton:
actv(false);
break;
case R.id.ReleaseDayRadioButton:
actv(false);
break;
case R.id.OnRadioButton:
actv(true);
break;
}
}
});
//questo sarà sostituito con un calendario.
/*final EditText nameEditText = (EditText) formElementsView
.findViewById(R.id.nameEditText);*/
//parte data
fromDateEtxt = (EditText) formElementsView.findViewById(R.id.nameEditText);
fromDateEtxt.setEnabled(active);
fromDateEtxt.setClickable(active);
fromDateEtxt.setInputType(InputType.TYPE_NULL);
fromDateEtxt.requestFocus();
//metodo data
//setDateTimeField();
//fromDatePickerDialog.show();
fromDateEtxt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
DatePickerDialog dpd = new DatePickerDialog( context ,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
fromDateEtxt.setText(dayOfMonth + "-"
+ (monthOfYear + 1) + "-" + year);
}
},
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
dpd.show();
}
});
// the alert dialog
new AlertDialog.Builder(context).setView(formElementsView)
.setTitle(movies.get(position).getTitle()+" Notify")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#TargetApi(11)
public void onClick(DialogInterface dialog, int id) {
//fromDateEtxt.setText(dateFormatter.format(newDate.getTime()));
String toastString = "";
String titleMovie = movies.get(position).getTitle();
String releaseDate = String.valueOf(movies.get(position).getReleaseDate());
String date = releaseDate.substring(0, 10);
String year = releaseDate.substring(releaseDate.length()-5,releaseDate.length());
releaseDate = date+year;
toastString = toastString + titleMovie + "\n" + releaseDate +"\n";
/*
* Detecting whether the checkbox is checked or not.
*/
/*if (myCheckBox.isChecked()) {
toastString += "Happy is checked!\n";
} else {
toastString += "Happy IS NOT checked.\n";
}*/
/*
* Getting the value of selected RadioButton.
*/
// get selected radio button from radioGroup
int selectedId = genderRadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
RadioButton selectedRadioButton = (RadioButton) formElementsView
.findViewById(selectedId);
if(selectedRadioButton.getId() == R.id.OnRadioButton)
{
toastString += "Selected radio button is: " + fromDateEtxt.getText();
}
else {
toastString += "Selected radio button is: "
+ selectedRadioButton.getText() + "!\n";
}
/*
* Getting the value of an EditText.
*/
/*toastString += "Name is: " + nameEditText.getText()
+ "!\n";*/
Toast toast = Toast.makeText(context, toastString, Toast.LENGTH_LONG);
toast.show();
dialog.cancel();
}
}).show();
}
//nuovo codice
/*#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_movie, null);
holder = new ViewHolder();
holder.title_movie = (TextView) convertView.findViewById(R.id.movie_title);
holder.release_date = (TextView) convertView
.findViewById(R.id.movie_release_date);
Movie row_pos = movies.get(position);
//holder.profile_pic.setImageResource(row_pos.getProfile_pic_id());
holder.title_movie.setText(row_pos.getTitle());
holder.release_date.setText((CharSequence) row_pos.getReleaseDate());
//holder.contactType.setText(row_pos.getContactType());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}*/
#Override
public void onViewRecycled(ViewHolder holder) {
super.onViewRecycled(holder);
Glide.clear(holder.posterView);
}
#Override
public int getItemCount() {
return movies.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.poster)
public ImageView posterView;
#BindView(R.id.movie_title)
public TextView title_movie;
#BindView(R.id.movie_release_date)
public TextView release_date;
#BindView(R.id.editNotify)
public Button notifyButton;
#BindView(R.id.iWatchItMovie)
public Button watchedButton;
#BindView(R.id.remove)
public Button removeButton;
public ViewHolder(View v) {
super(v);
ButterKnife.bind(this, v);
}
}
//parte per attivare/disattivare l'editText
private void actv(final boolean active)
{
fromDateEtxt.setEnabled(active);
if (active)
{
fromDateEtxt.requestFocus();
}
}
public static void setTipo(String tipo) {
MoviesAdapter.tipo = tipo;
}
public static String getTipo() {
return tipo;
}
}
For first, you can try adding similar logic to onPageScrolled
Fragment getFragment = getSupportFragmentManager().getFragments().get(position);
if (getFragment instanceof MoviesFragment) {
MoviesFragment thisFragment = (MoviesFragment) getFragment;
if ((position == 0 || position == 2) && positionOffset == 0.0 && positionOffsetPixels == 0)
thisFragment.onRefresh();
}
OK, #user47845 for (This is my list_item_movie.xml) you can try changed to this and tell us how are you doing.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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="350px">
<android.support.constraint.ConstraintLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/card_background">
<ImageView
android:id="#+id/poster"
android:layout_width="120dp"
android:layout_height="139dp"
android:layout_marginEnd="10dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="10dp"
android:layout_marginStart="2dp"
android:contentDescription="TODO"
android:scaleType="centerCrop"
android:src="#drawable/poster_placeholder"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/movie_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textSize="20dip"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/poster"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/movie_release_date"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="20dip"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/poster"
app:layout_constraintTop_toBottomOf="#+id/movie_title" />
<Button
android:id="#+id/editNotify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:onClick="pressEditNotifyButton"
android:text="Notify"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="#+id/poster" />
<Button
android:id="#+id/iWatchItMovie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="I watch it"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold"
app:layout_constraintEnd_toStartOf="#+id/remove"
app:layout_constraintStart_toEndOf="#+id/movie_title"
app:layout_constraintBottom_toBottomOf="parent" />
<Button
android:id="#+id/remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="21dp"
android:layout_marginRight="21dp"
android:background="#android:color/transparent"
android:text="Remove"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/iWatchItMovie" />
</android.support.constraint.ConstraintLayout>
</FrameLayout>
This is my list_item_movie.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="350px">
<!--android:layout_height="?android:attr/listPreferredItemHeight">-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:background="#drawable/card_background">
<ImageView
android:id="#+id/poster"
android:layout_width="185px"
android:layout_height="277px"
android:src="#drawable/poster_placeholder"
android:scaleType="centerCrop"
android:contentDescription="TODO" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_vertical">
<TextView
android:id="#+id/movie_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold"
android:layout_gravity="left|center_vertical"
android:textSize="20dip"
android:layout_marginLeft="10dip"
/>
<TextView
android:id="#+id/movie_release_date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical"
android:textSize="20dip"
android:layout_marginLeft="10dip"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="bottom"
android:orientation="horizontal">
<Button
android:id="#+id/editNotify"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:onClick="pressEditNotifyButton"
android:text="Notify"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
<Button
android:id="#+id/iWatchItMovie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="I watch it"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
<Button
android:id="#+id/remove"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="Remove"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</FrameLayout>
EDIT:
I have solved so:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="350px">
<!--android:layout_height="?android:attr/listPreferredItemHeight">-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="2dp"
android:layout_marginTop="4dp"
android:layout_marginRight="2dp"
android:layout_marginBottom="4dp"
android:orientation="horizontal"
android:background="#drawable/card_background">
<ImageView
android:id="#+id/poster"
android:layout_width="185px"
android:layout_height="277px"
android:contentDescription="TODO"
android:scaleType="centerCrop"
android:src="#drawable/poster_placeholder" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/movie_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dip"
android:layout_weight="1"
android:textSize="20dip"
android:textStyle="bold" />
<TextView
android:id="#+id/movie_release_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dip"
android:layout_weight="1"
android:textSize="20dip" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="bottom"
android:orientation="horizontal">
<Button
android:id="#+id/editNotify"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:onClick="pressEditNotifyButton"
android:text="Notify"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
<Button
android:id="#+id/iWatchItMovie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="I watch it"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
<Button
android:id="#+id/remove"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:text="Remove"
android:textColor="#android:color/holo_blue_dark"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</FrameLayout>

I want to open new activity on on-click for gridview

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);
}
});

runtime error in customAdapter

I'm trying to create a list of Card view using a custom adapter. I have defined the layout of a single row of list, consisting a card view and imageview/textviews in it, in a separate .xml file. I'm using a custom srrsy adapter. My app crashes when I try to open the activity having list view , giving only an Runtime-exception error.
Error:
AndroidRuntime(2583): at graph.prathya.com.nextstepz.CustomAdapters.PostArrayAdapter.getView(PostArrayAdapter.java:44)
This error is at the line
LayoutInflater li =(LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
in custom adapter.
Here is single_card_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/ll1">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:id="#+id/ll2">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:id="#+id/imgIcon"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/ll3"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SampleTitle1"
android:layout_marginTop="10dp"
android:background="#00b5ad"
android:textSize="20dp"
android:gravity="center"
android:padding="5dp"
android:id="#+id/title"
android:textColor="#ffffff"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sampledisription1"
android:layout_marginTop="10dp"
android:background="#ffffff"
android:textSize="10dp"
android:gravity="center"
android:padding="5dp"
android:id="#+id/desciption"
/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Here is PostArrayAdapter.java
package graph.prathya.com.nextstepz.CustomAdapters;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import graph.prathya.com.nextstepz.R;
/**
* Created by Prathya on 5/23/2015.
*/
public class PostArrayAdapter extends ArrayAdapter<Post>{
Context context;
Post data[] =null;
int layoutid;
public PostArrayAdapter(Context context, int layoutid, Post data[]) {
super(context,layoutid);
this.data=data;
this.layoutid=layoutid;
}
private class PostHolder{
ImageView imgIcon;
TextView title,description;
}
#Override
public int getCount(){
return data.length;
}
#Override
public View getView(int Position, View convertView, ViewGroup parent){
PostHolder holder;
View v = convertView;
if(v==null){
LayoutInflater li = LayoutInflater.from(context);/* RunTimeExceptio error at this line of code */
v= li.inflate(layoutid,parent,false);
holder = new PostHolder();
holder.imgIcon = (ImageView)v.findViewById(R.id.imgIcon);
holder.title = (TextView)v.findViewById(R.id.title);
holder.description= (TextView)v.findViewById(R.id.desciption);
v.setTag(holder);
}
else {
holder = (PostHolder)v.getTag();
}
Post post = data[Position];
holder.imgIcon.setImageResource(post.imgIcon);
holder.title.setText(post.title);
holder.description.setText(post.description);
return v;
}
}
Here is activity in which listView lies: HomeScreenAvtivity.java
package graph.prathya.com.nextstepz;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ListView;
import graph.prathya.com.nextstepz.Communicator.Communicater1;
import graph.prathya.com.nextstepz.CustomAdapters.Post;
import graph.prathya.com.nextstepz.CustomAdapters.PostArrayAdapter;
public class HomeScreenActivity extends ActionBarActivity {
ImageButton passionbtn, eventbtn, projectbtn, groupstudybtn;
Dialog dg;
ListView listView = null;
Post post[] =new Post[] {
new Post(R.drawable.img1,"Cats and Children","Cats can be a fascinating experience for children, but young minds can sometimes confuse a pet for a toy. Teach children how to respect and properly handle your cat for best results."),
new Post(R.drawable.img2,"Android:The Best OS","Android powers hundreds of millions of mobile devices in more than 190 countries around the world.Android’s openness has made it a favorite for consumers."),
new Post(R.drawable.img3,"Beautiful","Monica is an Italian actor and model who started her modelling career at the age of 13 by posing for a local photo enthusiast."),
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
listView = (ListView)findViewById(R.id.homelist);
listView.setAdapter(new PostArrayAdapter(getApplicationContext(),R.layout.single_card_view,post));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (item.getItemId() == R.id.nxtsignupitem) {
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
if (item.getItemId() == R.id.eventitem1) {
Intent in = new Intent(getApplicationContext(), PostDetailActivity.class);
startActivity(in);
}
if (item.getItemId() == R.id.postitem11) {
dg = new Dialog(HomeScreenActivity.this);
dg.requestWindowFeature(Window.FEATURE_NO_TITLE);
dg.setContentView(R.layout.fragment_new_post_dialogue);
dg.setTitle("Please choose One option");
dg.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dg.show();
passionbtn = (ImageButton) dg.findViewById(R.id.imageButton1st);
eventbtn = (ImageButton) dg.findViewById(R.id.imageButton2);
projectbtn = (ImageButton) dg.findViewById(R.id.imageButton3);
groupstudybtn = (ImageButton) dg.findViewById(R.id.imageButton4);
passionbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(1);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
eventbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(2);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
projectbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(3);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
groupstudybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(4);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
}
return super.onOptionsItemSelected(item);}
#Override
public boolean onCreateOptionsMenu(Menu menu){
// TODO Auto-generated method stub
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.menu_home_screen, menu);
return super.onCreateOptionsMenu(menu);
} }
XML layout file of HomeScreenActivity
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/lord"
android:layout_marginBottom="20dp"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/homelist">
</ListView>
</LinearLayout>
</ScrollView>
Post.java used in Adapter
package graph.prathya.com.nextstepz.CustomAdapters;
/**
* Created by Prathya on 5/23/2015.
*/
public class Post {
int imgIcon;
String title,description;
public Post(int imgIcon,String title, String description){
this.imgIcon=imgIcon;
this.title=title;
this.description=description;
}
}
you never assign context in your constructor.
add
this.context = context;
to your constructor

How to insert checkbox on custom listview

I am trying to add a checkbox in a customized listview but don't know how.
I have the following codes:
ListObject.java
package br.com.eduvm.xurrascalc;
public class ListObject {
private String texto;
private int iconeRid;
public ListObject() {
}
public ListObject(String texto, int iconeRid) {
this.texto = texto;
this.iconeRid = iconeRid;
}
public int getIconeRid() {
return iconeRid;
}
public void setIconeRid(int iconeRid) {
this.iconeRid = iconeRid;
}
public String getTexto() {
return texto;
}
public void setTexto(String texto) {
this.texto = texto;
}
}
ListAdapter.java
package br.com.eduvm.xurrascalc;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<ListObject> itens;
public ListAdapter(Context context, ArrayList<ListObject> itens) {
// Itens que preencheram o listview
this.itens = itens;
// responsavel por pegar o Layout do item.
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return itens.size();
}
public ListObject getItem(int position) {
return itens.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
ListObject item = itens.get(position);
view = mInflater.inflate(R.layout.itens_lista, null);
((TextView) view.findViewById(R.id.text)).setText(item.getTexto());
((ImageView) view.findViewById(R.id.imagemview)).setImageResource(item.getIconeRid());
return view;
}
}
List.xml
<?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="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5sp" >
<ImageView
android:id="#+id/imagemview"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="5sp"
android:gravity="center_vertical"
android:textColor="#FFF" />
</LinearLayout>
</LinearLayout>
How could I do to insert a checkbox in the items in this list?
This would be the layout for each individual row in your list
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/lstChkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lstText"
android:textSize="30px"
android:layout_weight="1" />
<ImageView
android:id="#+id/listImage"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
You main list activity layout will look something like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
android:choiceMode="multipleChoice"
/>
Your class which extends BaseAdapter getView method will somethings like this:
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vHolder = null;
if (convertView != null)
vHolder = (ViewHolder) convertView.getTag(); // convertView is been recycled
else {
convertView = (View) mInflater.inflate(R.layout.list_item, null); // Set content of new View with list_item.xml
vHolder = new ViewHolder();
vHolder.checkBox = ((CheckBox) convertView.findViewById(R.id.lstChkbox)); // Getting pointers
vHolder.textView = ((TextView) convertView.findViewById(R.id.lstText));
vHolder.imageView = ((ImageView) convertView.findViewById(R.id.listImage));
vHolder.checkBox.setOnCheckedChangeListener(this); // Setting Listeners
convertView.setTag(vHolder);
}
vHolder.checkBox.setId(position); // This is part of the Adapter APi
vHolder.textView.setId(position); // Do not delete !!!
vHolder.imageView.setId(position);
if (mItems.get(position).getChecked()) { // Setting parameters for the View from our mItems list
vHolder.checkBox.setChecked(true);
} else {
vHolder.checkBox.setChecked(false);
}
vHolder.textView.setText(mItems.get(position).getText());
vHolder.imageView.setImageDrawable(mItems.get(position).getmImage());
return convertView;
}
public static class ViewHolder {
CheckBox checkBox;
TextView textView;
ImageView imageView;
}
/*
* Ok for this test but Toast are going to show every time the row comes into View
*/
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG, "Checked");
int position = buttonView.getId();
if (isChecked) {
mItems.get(position).setChecked(true);
Toast.makeText(context, mItems.get(position).getText(), Toast.LENGTH_LONG).show();
} else {
mItems.get(buttonView.getId()).setChecked(false);
}
}
Just add a checkbox to the layout itens_lista.xml.
Just adding a checkbox is easy. Do you want to do anything more to ti.
Add a CheckBox View to your custom row layout.

Button OnclickEvent in Custom Row View ListView in android

I am new to android. i was created custome_row_view.xml file for row view.
using list i display two row. now i added one button in custome_row_view.
how to write code for that button onclick
Main. XML
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
custom_row_view.xml
<?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:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/buton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
CustomeViewActivity.java
package naresh.custom.view;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.ListActivity;
public class CustomeViewActivity extends ListActivity implements OnItemClickListener{
static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list.removeAll(list);
ListView lista=(ListView)findViewById(android.R.id.list);
int count = lista.getChildCount();
SimpleAdapter adapter = new SimpleAdapter(
this,
list,
R.layout.custom_row_view,
new String[] {"title","description"},
new int[] {R.id.textView1,R.id.textView2}
);
if(count<5){
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("title","On/Off");
temp.put("description", "Alert to be On or Off");
list.add(temp);
HashMap<String,String> temp1 = new HashMap<String,String>();
temp1.put("title","Select tone");
temp1.put("description", "Select tone for alerting");
list.add(temp1);
HashMap<String,String> temp2 = new HashMap<String,String>();
temp2.put("title","Alert Time");
temp2.put("description", "Select Time for alerting Before/After");
list.add(temp2);
HashMap<String,String> temp3 = new HashMap<String,String>();
temp3.put("title","Change Password");
temp3.put("description", "Can cahnge password any time");
list.add(temp3);
setListAdapter(null);
setListAdapter(adapter);
}
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(this,"ITem clicked", Toast.LENGTH_LONG).show();
}
}
I think you are using CustomAdapter to populate the listview..
If So then in getView() include the the button action:
public View getView(final int position, View convertView, ViewGroup parent)
{
View row=convertView;
FetchHolder holder=null;
if (row==null)
{
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.grid, parent, false);
holder=new FetchHolder(row);
row.setTag(holder);
}
else
{
holder=(FetchHolder)row.getTag();
}
holder.button.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
}
});
return row;
}
}
static class FetchHolder
{
private Button time=null;
FetchHolder(View row)
{
time=(Button)row.findViewById(R.id.timebutton);
}

Categories

Resources