Can someone help me with the code-I am having image slider containing multiple images and if I select any particular image and click on button that selected image should open on another page/activity.
I tried a lot but unable to display selected image on another page/activity.
So, please help me.
Thanks in advance.
**Main.java**
package com.example.imagesliderdemo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;
#SuppressWarnings("deprecation")
public class Main extends Activity {
private Gallery topsgallery;
private ImageView imgView;
int GalItemBg;
private Integer[] Imgid = {
R.drawable.a_1, R.drawable.a_2, R.drawable.a_3, R.drawable.a_4, R.drawable.a_5 };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
imgView = (ImageView)findViewById(R.id.ImageViewTops);
imgView.setImageResource(Imgid[0]);
Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
btnNextScreen.setOnClickListener(new View.OnClickListener() {
private int position;
public void onClick(View v) {
// TODO Auto-generated method stub
//Intent nextScreen = new Intent(Main.this, OpenImage.class);
Intent nextScreen=new Intent(getApplicationContext(),OpenImage.class);
nextScreen.putExtra("image",R.drawable.ic_launcher);
startActivity(nextScreen);
}
});
topsgallery = (Gallery) findViewById(R.id.gallery1);
topsgallery.setAdapter(new AddImgAdp (this));
topsgallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(#SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
imgView = (ImageView)findViewById(R.id.ImageViewTops);
}
});
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.Gallery1);
GalItemBg = typArray.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount() {
return Imgid.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(cont);
imageView.setImageResource(Imgid[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(80, 70));
imageView.setBackgroundResource(GalItemBg);
return imageView;
}
}
}
**Other activity file OpenImage.java**
package com.example.imagesliderdemo;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class OpenImage extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
ImageView image = (ImageView) findViewById(R.id.imageview);
int image_link = getIntent().getIntExtra("image_url", R.drawable.ic_launcher);
image.setImageResource(image_link);
Button btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Closing SecondScreen Activity
finish();
}
});
}
}
**activity_main.xml**
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:overScrollMode="always"
android:isScrollContainer="true"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="outsideInset"
android:scrollbars="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:scrollbars="vertical">
<LinearLayout
android:id="#+id/LinearLayoutTops"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:orientation="vertical">
<TextView
android:gravity="center"
android:text="#string/tops"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/LinearLayoutTopsGallery"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<Gallery
android:id="#+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:spacing="10dp" />
<ImageView
android:id="#+id/ImageViewTops"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/imageslide"/>
</LinearLayout>
</LinearLayout>
<Button android:id="#+id/btnNextScreen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send to Next Screen"
android:layout_marginTop="15dip"/>
</LinearLayout>
</ScrollView>
**Another Activity screen2.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" >
<Button
android:id="#+id/btnClose"
android:layout_width="151dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dip"
android:text="Close" />
<ImageView
android:id="#+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
You can use fragment,
http://developer.android.com/guide/components/fragments.html
this page have a example, maybe can help you.
Create a global variable to get the position of Slider(Let suppose that variable be pos).Now in getView of your slider adapter code like this
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(cont);
pos=position;
imageView.setImageResource(Imgid[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(80, 70));
imageView.setBackgroundResource(GalItemBg);
return imageView;
}
Now on button click code like this:
btnNextScreen.setOnClickListener(new View.OnClickListener() {
private int position;
public void onClick(View v) {
// TODO Auto-generated method stub
//Intent nextScreen = new Intent(Main.this, OpenImage.class);
Intent nextScreen=new Intent(getApplicationContext(),OpenImage.class);
//Sending data to another Activity
nextScreen.putExtra("id",Imgid[pos]);
Log.e("n", Imgid[pos]);
startActivity(nextScreen);
}
});
Just pass the selected image id value in the Gallery on click listener.
topsgallery.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long arg3)
{
// TODO Auto-generated method stub
Intent fullImage = new Intent(YourActivity.this,FullImageView.class)
fullImage.putExtra("image_url",R.drawable.image);
startActivity(fullImage);
}
});
consider the following steps :
#1 Create a new activity say for ex : FullImageView with the following view and declare that in manifest.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/android" />
</ImageView>
</LinearLayout>
3 : Receive the intent in onCreate of FullImageView activity
ImageView image = (ImageView) findViewById(R.id.image);
int image_link = getIntent().getIntExtra("image_url", R.drawable.default);
4 : Set the URL to your ImageView.
imageView.setImageResource(image_link);
Please feel free if you face any issues regarding this.
You can put the intent inside the adapter... and then do something like this (Note that you need to pass the context to the adapter):
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(cont);
imageView.setImageResource(Imgid[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(80, 70));
imageView.setBackgroundResource(GalItemBg);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent nextScreen=new Intent(context,OpenImage.class);
nextScreen.putExtra("image",ImgId[pos]);
startActivity(nextScreen);
}
});
return imageView;
}
Related
I have an array of images, and wanted to display image from it, to alert dialog when we click on grid item.
Here is my class:
mainactivity.java
package glassfibre.hospital2;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity
{
GridView grid;
String[] web = {
"Food",
"Doctor",
"Water",
"Feel Cold",
"Adjust Bed",
"Toilet"
} ;
int[] imageId = {
R.drawable.food,
R.drawable.doctor,
R.drawable.water2,
R.drawable.lowtemp,
R.drawable.bed,
R.drawable.toilet
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomGrid adapter = new CustomGrid(MainActivity.this, web, imageId);
grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
mydialog dialog = new mydialog();
dialog.show(getSupportFragmentManager(),"my_dialog");
}
});
}
}
CustomGrid.java
package glassfibre.hospital2;
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;
public class CustomGrid extends BaseAdapter{
private Context mContext;
private final String[] web;
final int[] Imageid;
public CustomGrid(Context c,String[] web,int[] Imageid ) {
mContext = c;
this.Imageid = Imageid;
this.web = web;
}
#Override
public int getCount() {
return web.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, 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.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
textView.setText(web[position]);
imageView.setImageResource(Imageid[position]);
} else {
grid = (View) convertView;
}
return grid;
}
}
grid_single.xml
<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="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >
<ImageView
android:id="#+id/grid_image"
android:src="#drawable/food"
android:layout_width="150dp"
android:layout_height="150dp">
</ImageView>
<TextView
android:id="#+id/grid_text"
android:text="#string/food"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_below="#id/grid_image"
android:gravity="center"
android:textSize="20sp" >
</TextView>
</RelativeLayout>
mydialog.java
package glassfibre.hospital2;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import java.util.zip.Inflater;
import static android.R.attr.gridViewStyle;
import static android.R.attr.id;
import static android.R.attr.thumbPosition;
import static glassfibre.hospital2.R.layout.grid_single;
public class mydialog extends DialogFragment implements View.OnClickListener
{
Button bt;
ImageView iv;
CustomGrid cg;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.my_dialog,null);
bt=(Button)view.findViewById(R.id.button);
bt.setOnClickListener(this);
iv= (ImageView) view.findViewById(R.id.imageView);
setCancelable(false);
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
// > here i wanted to set image which i click on grid view
return view;
}
#Override
public void onClick(View view)
{
if(view.getId()==R.id.button)
{
dismiss();
}
}
}
my_dialog.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"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="I want"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp"
android:id="#+id/textView3"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:gravity="center"
android:textSize="20dp"/>
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
app:srcCompat="#drawable/food"
android:id="#+id/imageView"
android:layout_marginTop="19dp"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true" />
<Button
android:text="OK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="12dp"
android:id="#+id/button" />
</RelativeLayout>
I have an array of images, and wanted to display image from it, to alert dialog when we click on grid item.
Do something like this:
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
mydialog dialog = new mydialog();
int imageResource = imageId[position];
dialog.setImageResource(imageResource);
dialog.show(getSupportFragmentManager(),"my_dialog");
}
});
And in your mydialog class declare int variable
private int imageResource;
And create a method:
public void setImageResource(int imageResource) {
this.imageResource = imageResource;
}
now you can set image resource to imageview in onCreateView method of mydialog class
Inside your myDialog class,just have a setter method which stores the Drawable Resource id , like shown below
public void setImageIdToDisplay(int aDrawableId) {
mDrawableId = aDrawableId;
}
and in your oncreateview method of myDialog class, just set the image resource id to the imageview
iv.setImageResource(mDrawableId);
and in your MainActivity's onItemClick listner of gridview, pass the drawable resource id as shown below
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
mydialog dialog = new mydialog();
dialog.setImageIdToDisplay(imageId[position]);
dialog.show(getSupportFragmentManager(),"my_dialog");
}
});
I am new to Android and I'm trying to add setOnItemClickListener to my gridview and i am getting the following error:
setOnItemClickListener in AdapterView cannot by applied to MainActivity
for this code line: grid.setOnItemClickListener(this);
What am I doing wrong? Could you help me please?
Here is my code
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
GridView grid;
TextView tvTest;
TextView tvTest2;
Random rnd = new Random();
int color;
ImageView imageView;
ArrayList<Integer> colorInts = new ArrayList<Integer>();
ArrayList<Integer> itemsList = new ArrayList<Integer>();
Integer[] items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
grid = (GridView) findViewById(R.id.grid);
tvTest =(TextView) findViewById(R.id.tvTest);
tvTest2 =(TextView) findViewById(R.id.tvTest2);
adjustGridView();
itemsList.add(R.drawable.lemon);
itemsList.add(R.drawable.lemon);
itemsList.add(R.drawable.lemon);
itemsList.add(R.drawable.lemon);
itemsList.add(R.drawable.lemon);
itemsList.add(R.drawable.lemon);
// ArrayList into Array
items = new Integer[ itemsList.size() ];
itemsList.toArray( items );
grid.setAdapter(new CustomGridAdapter(this, items));
grid.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "Clicked postion is " + arg2,
Toast.LENGTH_SHORT).show();
tvTest.setText("Number of color: "+ colorInts);
tvTest2.setText("Number of color: "+ colorInts.get(arg2));
}
// Here is your custom Adapter
public class CustomGridAdapter extends BaseAdapter {
private AppCompatActivity mContext;
// Keep all Images in array
public Integer[] mThumbIds;
// Constructor
public CustomGridAdapter(MainActivity mainActivity, Integer[] items) {
this.mContext = mainActivity;
this.mThumbIds = items;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
imageView.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
colorInts.add(color);
return imageView;
}
}
private void adjustGridView() {
grid.setNumColumns(3); //(GridView.AUTO_FIT);
grid.setColumnWidth(80);
grid.setVerticalSpacing(5);
grid.setHorizontalSpacing(5);
grid.setStretchMode(GridView.NO_STRETCH);
}
}
and here is the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.testrk.basiclayout001.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/myColor02"
android:layout_weight="2"
>
<TextView
android:id="#+id/tvTest"
android:background="#color/myColor04"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/myColor01"
android:focusable="false"
android:layout_weight="1"
>
<GridView
android:id="#+id/grid"
android:focusable="true"
android:clickable="true"
android:background="#color/myColor03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
>
</GridView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/myColor02"
android:layout_weight="2"
>
<TextView
android:id="#+id/tvTest2"
android:background="#color/myColor04"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
and cell.xml:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/imgv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
</ImageView>
The setOnItemClickListener method does not take in the context as an argument, it takes in an OnItemClickListener object. What you need to do is pass in a new OnItemClickListener in the method call and then override the OnItemClick method.
Example:
grid.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
//code to be executed on click
}
I hope this answers your question.
How can I pass an Image resource Id to my custom adapter? I have a check box in an activity called routedetails . When the checkbox is checked I want to display a check mark next to that item in the listview. But to do this I need to pass the imageId to the custom adapter. I tried doing it with an intent putExtra. But that does not work.
Heres my RouteDetails.java with the checkbox code
public class RouteDetails extends AppCompatActivity {
ImageView routeImage;
String routeName;
CheckBox routeCheckBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_details);
//back button for route details view
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
///////checkbox///////////////////////////////////////////
routeCheckBox = (CheckBox) findViewById(R.id.routeCheckBox);
////// final ImageView checkImageView = (ImageView) findViewById(R.id.checkImageView);
routeCheckBox.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
if (routeCheckBox.isChecked())
{
//checkImageView.setImageResource(R.drawable.checkmark);
Intent check = new Intent(RouteDetails.this,CustomAdapter.class);
check.putExtra("checkImageResource", R.drawable.checkmark);
startActivity(check);
/////////////////////////////////////////////
//sets actionbar title
routeName = getIntent().getExtras().getString("routeName");
getSupportActionBar().setTitle(routeName);
//TextView for route details
final TextView routeDetailsView = (TextView) findViewById(R.id.routeDetailsView);
routeDetailsView.setText(getIntent().getExtras().getCharSequence("route"));
//ImageView for route details
routeImage = (ImageView) findViewById(R.id.routeImage);
final int mImageResource = getIntent().getIntExtra("imageResourceId", 0);
routeImage.setImageResource(mImageResource);
And here's the custom adapter
class CustomAdapter extends ArrayAdapter<CharSequence>{
public CustomAdapter(Context context, CharSequence[] routes) {
super(context, R.layout.custom_row ,routes);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater routeInflater = LayoutInflater.from(getContext());
View customView = convertView;
if(customView == null){customView = routeInflater.inflate(R.layout.custom_row, parent, false);}
CharSequence singleRoute = getItem(position);
TextView routeText = (TextView) customView.findViewById(R.id.routeText);
routeText.setText(singleRoute);
////////trying to set checkmark/////
ImageView checkImageView = (ImageView) customView.findViewById(R.id.checkImageView);
checkImageView.setImageResource(((Activity) getContext()).getIntent().getIntExtra("checkImageResource",0));
////////////////////////////////////////
return customView;
}
And here's the adapter being used in my main activity
list view with xml array of routes
final CharSequence[] routeListViewItems = getResources().getTextArray(R.array.routeList);
//custom adapter for list view
ListAdapter routeAdapter = new CustomAdapter(this, routeListViewItems);
final ListView routeListView = (ListView) findViewById(R.id.routeListView);
routeListView.setAdapter(routeAdapter);
Any help would be appreciated
Basically you create two activities. Let say, MyListViewActivity containing a ListView whose items are nothing but custom views which hold an ImageView and a TextView;
then a CheckBoxActivity holding the CheckBox elements.
When a list item is clicked in MyListViewActivity, you start the CheckboxAtivity using startActivityForResult() method.
Finaly, in the CheckBoxActivity when a checkBox item is checked its textValue is send back to MyListViewActivity for updating the corresponding imageView.
See below code snippets:
Layout file for MyListViewActivity : activity_my_list_view.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/activity_my_list_view"
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="YourPackageNameHere.MyListViewActivity" >
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
</RelativeLayout>
Layout file for custom list item: list_single.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/img"
android:layout_width="40dp"
android:layout_height="40dp"/>
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_gravity="center_horizontal|center_vertical" />
</LinearLayout>
</TableRow>
</TableLayout>
Layout file for CheckBoxActivity: activity_checkbox.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_checkbox"
android:orientation="vertical"
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="YourPackageNameHere.CheckboxActivity">
<CheckBox
android:text="CheckBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox1" />
<CheckBox
android:text="CheckBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox2" />
</LinearLayout>
code for MyListViewActivity :
package YourPackageNameHere;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MyListViewActivity extends AppCompatActivity {
ImageView img;
ListView list;
private static final int MY_REQUEST_CODE= 1;
String[] itemNames = {
"Google Plus",
"Twitter",
"Windows",
"Bing",
"Itunes",
"Wordpress",
"Drupal"
} ;
Integer[] imageId = {
R.drawable.ic_home_black_18dp,
R.drawable.ic_account_circle_black_18dp,
R.drawable.ic_fingerprint_black_18dp,
R.drawable.ic_help_black_18dp,
R.drawable.ic_settings_black_18dp,
R.drawable.ic_power_settings_new_black_18dp,
R.drawable.ic_directions_run_black_18dp
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_list_view);
CustomList adapter = new CustomList(MyListViewActivity.this, itemNames, imageId);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MyListViewActivity.this, "You Clicked at " + itemNames[+ position], Toast.LENGTH_SHORT).show();
//get the image that has been clicked
img= (ImageView) view.findViewById(R.id.img);
//Starting the CheckBoxAtivity for result
Intent mIntent = new Intent(getBaseContext(), CheckboxActivity.class);
startActivityForResult(mIntent, MY_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
switch (result){
case "CheckBox1":
img.setImageResource(R.drawable.ic_gps_fixed_black_18dp);
break;
case "CheckBox2":
img.setImageResource(R.drawable.cast_ic_notification_0);
break;
}
}
}
}//onActivityResult
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final String[] itemNames;
private final Integer[] imageId;
public CustomList(Activity context, String[] itemNames, Integer[] imageId) {
super(context, R.layout.list_single, itemNames);
this.context = context;
this.itemNames = itemNames;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(itemNames[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
}
code for ChecboxActivity:
package YourPackageNameHere
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.CompoundButton;
public class CheckboxActivity extends AppCompatActivity {
CheckBox mCheckBox1;
CheckBox mCheckBox2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkbox);
mCheckBox1 = (CheckBox) findViewById(R.id.checkBox1);
mCheckBox2 = (CheckBox) findViewById(R.id.checkBox2);
mCheckBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(mCheckBox1.isChecked()){
sendResultToLisViewActivity((String) mCheckBox1.getText()); //send the text string of mCheckBox1 to MyListViewActivity
}
}
});
mCheckBox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(mCheckBox2.isChecked()){
sendResultToLisViewActivity((String) mCheckBox2.getText()); //send the text string of mCheckBox1 to MyListViewActivity
}
}
});
}
public void sendResultToLisViewActivity(String mStringExtra){
Intent returnIntent = new Intent();
returnIntent.putExtra("result",mStringExtra);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
}
Lastly in your MainActivity onCreate() method you start MyListViewActivity as follows:
Intent i = new Intent(MainActivity.this, MyListViewActivity.class);
startActivity(i);
Ps: I referred to this link for creating the Custom ListView with Images and Text.
I am working on a application which require image and text group together in horizontal scroll bar.
I have tried few things but i am unable to get this, can anyone guide me with this guys.
Here is what i a have done,
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<HorizontalScrollView
android:id="#+id/horizontalScrollView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:scrollbars="horizontal" >
<GridView
android:layout_height="wrap_content"
android:id="#+id/gridView1"
android:layout_width="wrap_content"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:scrollbars="horizontal"
android:verticalSpacing="10dp">
</GridView>
</HorizontalScrollView>
</LinearLayout>
gridview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/border"
android:padding="5dp">
<ImageView
android:layout_height="64dp"
android:id="#+id/imageView1"
android:layout_width="64dp"
android:src="#drawable/icon"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
<TextView
android:text="TextView"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_marginTop="2dp"
android:layout_centerHorizontal="true"
android:textSize="18sp"></TextView>
</RelativeLayout>
GridviewExampleActivity.java
package com.paresh.gridviewexample;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class GridViewExampleActivity extends Activity {
/** Called when the activity is first created. */
private GridviewAdapter mAdapter;
private ArrayList<String> listCountry;
private ArrayList<Integer> listFlag;
private GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(this,listCountry, listFlag);
// Set custom adapter to gridview
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(GridViewExampleActivity.this, mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
}
public void prepareList()
{
listCountry = new ArrayList<String>();
listCountry.add("india");
listCountry.add("Brazil");
listCountry.add("Canada");
listCountry.add("China");
listCountry.add("France");
listCountry.add("Germany");
listCountry.add("Iran");
listCountry.add("Italy");
listCountry.add("Japan");
listCountry.add("Korea");
listCountry.add("Mexico");
listCountry.add("Netherlands");
listCountry.add("Portugal");
listCountry.add("Russia");
listCountry.add("Saudi Arabia");
listCountry.add("Spain");
listCountry.add("Turkey");
listCountry.add("United Kingdom");
listCountry.add("United States");
listFlag = new ArrayList<Integer>();
listFlag.add(R.drawable.india);
listFlag.add(R.drawable.brazil);
listFlag.add(R.drawable.canada);
listFlag.add(R.drawable.china);
listFlag.add(R.drawable.france);
listFlag.add(R.drawable.germany);
listFlag.add(R.drawable.iran);
listFlag.add(R.drawable.italy);
listFlag.add(R.drawable.japan);
listFlag.add(R.drawable.korea);
listFlag.add(R.drawable.mexico);
listFlag.add(R.drawable.netherlands);
listFlag.add(R.drawable.portugal);
listFlag.add(R.drawable.russia);
listFlag.add(R.drawable.saudi_arabia);
listFlag.add(R.drawable.spain);
listFlag.add(R.drawable.turkey);
listFlag.add(R.drawable.united_kingdom);
listFlag.add(R.drawable.united_states);
}
}
GridviewAdapter.java
package com.paresh.gridviewexample;
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class GridviewAdapter extends BaseAdapter
{
private ArrayList<String> listCountry;
private ArrayList<Integer> listFlag;
private Activity activity;
public GridviewAdapter(Activity activity,ArrayList<String> listCountry, ArrayList<Integer> listFlag) {
super();
this.listCountry = listCountry;
this.listFlag = listFlag;
this.activity = activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listCountry.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listCountry.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public ImageView imgViewFlag;
public TextView txtViewTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.gridview_row, null);
view.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
view.imgViewFlag = (ImageView) convertView.findViewById(R.id.imageView1);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtViewTitle.setText(listCountry.get(position));
view.imgViewFlag.setImageResource(listFlag.get(position));
return convertView;
}
}
My ouput should be
------------ ---------- ------------ ----
Image Image Image Image Image Image Image Image Image Image Image
Text Text Text Text Text Text Text Text Text Text Text
------------ ---------- ------------ --
Please Help me guys
Hi there just have a look at CustomArrayAdapter used for ListViews and Gridviews especially point 10 at this Tutoiral there you get to know how to customize your GridView/ListView (handled same way)
This might also help
If you have problems with the hotrizontal way, try this project: https://github.com/jess-anders/two-way-gridview
In the below code i have created a gallery object and also have included a image view,on click of image how to get the image name and load it in image view.I have also included main.xml
package HelloGallery.com;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class HelloGalleryActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView iv=(ImageView) findViewById(R.id.imageView1);
iv.setVisibility(View.INVISIBLE);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Toast.makeText(HelloGalleryActivity.this, "" + position, Toast.LENGTH_SHORT).show();
iv.setVisibility(View.VISIBLE);
iv.setsource("android:src="#drawable/"+imagename); //how to do this
}
});
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Integer[] mImageIds = {
R.drawable.sample_1,
R.drawable.sample_2,
R.drawable.sample_3
};
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = a.getResourceId(
R.styleable.HelloGallery_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
/* public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
return null;
}*/
}
}
Main.mxml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<ImageView android:layout_width="wrap_content" android:id="#+id/imageView1" android:layout_height="wrap_content" ></ImageView>
</LinearLayout>
Try this,
Drawable d=getResources().getDrawable(R.drawable.icon);
iv.setImageDrawable(d);