How do I add a border to an ImageView inside a GridView after clicking on an image and disappear border if again clicked on the same image again?
gv_gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long Id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),"You clikced on "+position,Toast.LENGTH_SHORT ).show();
// gv_gridview.setSelected(true);
// gv_gridview.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
// gv_gridview.setDrawSelectorOnTop(true);
}
});
This is grid item selection problem
I assume that your grid item is an ImageView.
Solution
Find working example project here: https://github.com/jskierbi/sample-gridview-select
You need to add CheckedImageView class to your project, so grid view can check the items for you.
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.ImageView;
public class CheckedImageView extends ImageView implements Checkable {
boolean mFlgChecked = false;
private static final int[] CHECKED_STATE_SET = {
android.R.attr.state_checked
};
public CheckedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
#Override
public boolean isChecked() {
return mFlgChecked;
}
#Override
public void setChecked(boolean checked) {
mFlgChecked = checked;
refreshDrawableState();
}
#Override
public void toggle() {
mFlgChecked = !mFlgChecked;
}
}
2. Add colors (res/values/colors.xml):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="image_selected">#0000FF</color>
<color name="transparent">#00000000</color>
</resources>
Add selector, this will define which color is used for which state of your image (res/drawable/checked_image.xml):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#color/image_selected" />
<item android:drawable="#color/transparent" />
</selector>
Add grid item layout (res/layout/grid_view_item.xml)
Remember to change com.example.CheckedImageView package name so it reflects where you put your CheckedImageView class.
<?xml version="1.0" encoding="utf-8"?>
<com.example.CheckedImageView android:id="#+id/image"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/checked_image"
android:cropToPadding="true"
android:padding="6dp" />
And finally, use this layout in adapter. Below is full code for my Activity class:
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class MainActivity extends Activity {
private static final #DrawableRes int[] IMAGES = {
R.drawable.a001, R.drawable.a002, R.drawable.a003, R.drawable.a004, R.drawable.a005,
R.drawable.a006, R.drawable.a007, R.drawable.a008, R.drawable.a009, R.drawable.a010,
R.drawable.a011, R.drawable.a012, R.drawable.a013, R.drawable.a014, R.drawable.a015,
R.drawable.a016, R.drawable.a017, R.drawable.a018
};
private GridView mGridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGridView = ((GridView) findViewById(R.id.gridview));
mGridView.setChoiceMode(GridView.CHOICE_MODE_SINGLE);
mGridView.setAdapter(new BaseAdapter() {
#Override public int getCount() {
return IMAGES.length;
}
#Override public Object getItem(int position) {
return IMAGES[position];
}
#Override public long getItemId(int position) {
return IMAGES[position];
}
#Override public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null || !(convertView instanceof ImageView)) {
ImageView imageView = (ImageView) getLayoutInflater().inflate(R.layout.grid_view_item, parent, false);
imageView.setImageResource(IMAGES[position]);
convertView = imageView;
}
return convertView;
}
});
}
}
Finally, you can use mGridView.getCheckedItemPosition() to get position of checked item.
Screen:
Not sure if this is what you are looking for but you can try the following...
In Your <GridView> Tag
android:horizontalSpacing="1dp"
android:verticalSpacing="1dp"
Related
I would like to display items in a dialog. I used GridView. If I don't set the column width manually, GridView used hard-coded column number 2 like figure 1. If I set the column width, then it showed as many columns as possible like figure 2.
The problem is GridView seems to stretch the item to fill the whole screen, when I set a hard-coded width for the item (refer the code below). What can I prevent this? My final destination is to remove the red area in Figure 2. That should shrink the dialogue width by the amount of the red areas.
Figure 1.
Figure 2.
my_dialogue.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableRow>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Family"/>
<GridView
android:stretchMode="columnWidth"
android:horizontalSpacing="0dp"
android:numColumns="auto_fit"
android:id="#+id/familyGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</TableRow>
</TableLayout>
my_item.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:orientation="horizontal"
android:layout_width="wrap_content"
android:background="#android:color/holo_red_dark"
android:layout_height="wrap_content">
<ImageView
android:background="#android:color/holo_blue_dark"
android:layout_width="48sp"
android:layout_height="48sp"/>
<TextView
tools:text="Some application"
android:id="#+id/tvLabel"
android:background="#android:color/holo_blue_bright"
android:gravity="center_vertical"
android:layout_width="192sp"
android:layout_height="48sp"/>
</LinearLayout>
MyDialogue.java
package com.example.me.test2;
import android.content.res.Resources;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.util.TypedValue.COMPLEX_UNIT_SP;
import static android.util.TypedValue.applyDimension;
public class MyDialogue extends AppCompatDialogFragment
{
String TAG = this.getClass().getName();
private static MyDialogue instance;
private GridView myGrid;
public static MyDialogue getInstance()
{
if(instance == null)
{
instance = new MyDialogue();
}
return instance;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState)
{
setStyle(STYLE_NO_TITLE, 0);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.my_dialogue, container, false);
myGrid = (GridView)v.findViewById(R.id.familyGrid);
//If I do not set the column width, it does not know the item width,
//and the column number falls back to 2.
Resources r = getResources();
float px = applyDimension(COMPLEX_UNIT_SP, 192+48, r.getDisplayMetrics());
myGrid.setColumnWidth((int)px);
ArrayList<String> list = new ArrayList<>();
list.add("Father: Homer Simpson");
list.add("Mother: Marge Simpson");
list.add("Son: Bart Simpson");
list.add("Daughter: Lisa Simpson");
list.add("Baby: Maggie Simpson");
list.add("Dog: Santa's L. Helper");
MyAdapter oa = new MyAdapter(list);
myGrid.setAdapter(oa);
return v;
}
class MyAdapter implements ListAdapter
{
List<String> list;
public MyAdapter(List<String> list)
{
this.list = list;
}
#Override
public boolean areAllItemsEnabled()
{
return true;
}
#Override
public boolean isEnabled(int position)
{
return true;
}
#Override
public void registerDataSetObserver(DataSetObserver observer)
{
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer)
{
}
#Override
public int getCount()
{
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public long getItemId(int position)
{
return 0;
}
#Override
public boolean hasStableIds()
{
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = View.inflate(myGrid.getContext(), R.layout.my_item, null);
TextView tvLabel = (TextView) v.findViewById(R.id.tvLabel);
tvLabel.setText(list.get(position));
return v;
}
#Override
public int getItemViewType(int position)
{
return 0;
}
#Override
public int getViewTypeCount()
{
return 1;
}
#Override
public boolean isEmpty()
{
return list.isEmpty();
}
}
}
MainActivity.java
package com.example.me.test2;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
{
String TAG = this.getClass().getName();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnShow = (Button)findViewById(R.id.btnShow);
btnShow.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
FragmentManager manager = getSupportFragmentManager();
AppCompatDialogFragment dialogue = MyDialogue.getInstance();
dialogue.show(manager, "dialogue");
}
});
}
}
if i understood your question, you may want to put the gridView inside a linear layout, setting to grid view to fill the linear layout, but put some padding to the linear layout. good luck.
I have an ArrayList<String> List which contains some items from the listview all_list. How can I select these items in the list view all_list programmatically by checking the ArrayList<String> List contents?
for e.g., listview all_list contains [0] apple
[1] orange
[2] banana
In ArrayList<String> List, I have orange so I want item on position 1 on the listview all_list to be selected (highlighted) automatically.
I have tried using all_list.setItemChecked(), but it does nothing and shuts down the application. I am performing the operation after listing the adapter.
set an onItemClickListener to the listview such that on click, you set a boolean flag that sets the checkbox in each row to selected. then call notifyDataSetChanged()
Try this
MainActivity.java
package com.example.multiseekbar;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView listView1;
ArrayList<ModelClass> modelClass = new ArrayList<ModelClass>();
FruitSelectAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelClass.add(new ModelClass("Orange", true));
modelClass.add(new ModelClass("Apple", false));
modelClass.add(new ModelClass("Banana", false));
modelClass.add(new ModelClass("Grapes", false));
listView1 = (ListView) findViewById(R.id.listView1);
adapter = new FruitSelectAdapter(MainActivity.this, modelClass);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(modelClass.get(arg2).isSelected()){
modelClass.get(arg2).setSelected(false);
}else{
modelClass.get(arg2).setSelected(true);
}
adapter.notifyDataSetChanged();
}
});
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.multiseekbar.MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="fill_parent"
>
</ListView>
</RelativeLayout>
FruitSelectAdapter.java
package com.example.multiseekbar;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FruitSelectAdapter extends BaseAdapter
{
private Activity activity;
private LayoutInflater inflater;
private ArrayList<ModelClass> modelClass=null;
public FruitSelectAdapter(Activity activity, ArrayList<ModelClass> modelClass) {
this.activity = activity;
this.modelClass = modelClass;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return modelClass.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return modelClass.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
holder =new ViewHolder();
convertView = inflater.inflate(R.layout.row1, null);
holder.txtFruitName = (TextView)convertView.findViewById(R.id.txtFruitName);
holder.cbFruitSelectStatus = (CheckBox)convertView.findViewById(R.id.cbFruitSelectStatus);
holder.linLayBackground = (LinearLayout) convertView.findViewById(R.id.linLayBackground);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.txtFruitName.setText(modelClass.get(position).getFruitName());
holder.cbFruitSelectStatus.setChecked(modelClass.get(position).isSelected());
if(modelClass.get(position).isSelected()){
holder.linLayBackground.setBackgroundColor(Color.parseColor("#80ccff"));
}else{
holder.linLayBackground.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
return convertView;
}
class ViewHolder{
TextView txtFruitName;
CheckBox cbFruitSelectStatus;
LinearLayout linLayBackground;
}
}
row1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/linLayBackground"
android:layout_height="70dp"
android:orientation="horizontal"
>
<TextView
android:id="#+id/txtFruitName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Fruit name"
android:layout_weight="1"
android:textSize="16sp"
android:textColor="#000000" />
<CheckBox
android:id="#+id/cbFruitSelectStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false" />
</LinearLayout>
ModelClass.java
package com.example.multiseekbar;
public class ModelClass {
String fruitName;
boolean isSelected=false;
public ModelClass(String fruitName, boolean isSelected) {
this.fruitName = fruitName;
this.isSelected = isSelected;
}
public String getFruitName() {
return fruitName;
}
public void setFruitName(String fruitName) {
this.fruitName = fruitName;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
}
package com.android.example;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class SpinnerActivity extends Activity implements OnItemSelectedListener {
private ICSAdapter mAdapter;
private String[] mNameList = {"one","two","three" };
Context context=this;
Spinner room_type;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_activity_main);
room_type = (Spinner) findViewById(R.id.ics_spinner);
mAdapter = new ICSAdapter(context, mNameList);
room_type.setAdapter(mAdapter);
room_type.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> Adapter, View view,
int position, long id) {
room_type.setSelection(position);
View selectedText = (View) Adapter.getChildAt(position);
if (selectedText != null) {
RelativeLayout real = (RelativeLayout) selectedText.findViewById(R.id.real);
TextView selected = (TextView) selectedText.findViewById(R.id.name_view);
selected.setText(mNameList[position].toUpperCase());
((View) selected.getParent()).setBackgroundColor(Color.TRANSPARENT);
// real.setBackgroundColor(Color.TRANSPARENT);
}
}
#Override
public void onNothingSelected(AdapterView<?> Adapter) {
// TODO Auto-generated method stub
}
});
}
public class ICSAdapter extends BaseAdapter {
private LayoutInflater inflater;
private Context context;
String[] room_type;
public ICSAdapter(Context context, String[] _accidentList) {
this.room_type = _accidentList;
this.context = context;
inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return room_type.length;
}
#Override
public Object getItem(int position) {
return room_type[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
convertView = inflater.inflate(R.layout.drop_down_view, null);
holder = new ViewHolder();
holder.spinnerText = (TextView) convertView.findViewById(R.id.name_view);
holder.spinnerText.setText(room_type[position]);
return convertView;
}
public class ViewHolder {
TextView spinnerText;
}
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg"
android:layout_gravity="center"
>
<Spinner
android:id="#+id/ics_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_alignParentTop="true"
android:background="#drawable/text3"
/>
</RelativeLayout>
dropdown.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/real"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#2D333C" >
<TextView
android:id="#+id/name_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginTop="5dp"
android:gravity="center"
android:text="324"
android:textColor="#color/android:white"
android:textSize="18sp" />
</RelativeLayout>
Here i am using the default spinner with some background image. I have one issue, when i click the spinner,the dropdown list will display in white color background.But the orignal color background will not displayed(android:background="#2D333C")
I am using the transparent color for backgound change.How to resolve this issue. I want to display the given background color,when i click the spinner in dropdown list.After i select the selected value,the background will transaparent.Can anyone help me to solve this issue?
Make one custom file in drawable folder.
mybackground.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="#color/yourcolorName" />
<item android:drawable="#android:color/transparent" />
</selector>
Now set this file to your Spinner.
<Spinner
android:id="#+id/ics_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_alignParentTop="true"
android:background="#drawable/mybackground"
/>
I'm working on a project that contains some images in gallery, I want to add text with button that changes respective to selected image. How can I add this?
This is the code:
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.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class GalleryView extends Activity {
Integer[] pics = {
R.drawable.antartica1,
R.drawable.antartica2,
R.drawable.antartica3,
R.drawable.antartica4,
R.drawable.antartica5,
R.drawable.antartica6,
R.drawable.antartica7,
R.drawable.antartica8,
R.drawable.antartica9,
R.drawable.antartica10
};
ImageView imageView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery ga = (Gallery)findViewById(R.id.Gallery01);
ga.setAdapter(new ImageAdapter(this));
imageView = (ImageView)findViewById(R.id.ImageView01);
ga.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getBaseContext(),
"You have selected picture " + (arg2+1) + " of Antartica",
Toast.LENGTH_SHORT).show();
imageView.setImageResource(pics[arg2]);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context ctx;
int imageBackground;
public ImageAdapter(Context c) {
ctx = c;
TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();
}
public int getCount() {
return pics.length;
}
public Object getItem(int arg0) {
return arg0;
}
public long getItemId(int arg0) {
return arg0;
}
public View getView(int arg0, View arg1, ViewGroup arg2) {
ImageView iv = new ImageView(ctx);
iv.setImageResource(pics[arg0]);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setLayoutParams(new Gallery.LayoutParams(150,120));
iv.setBackgroundResource(imageBackground);
return iv;
}
}
}
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"
>
<Gallery
android:id="#+id/Gallery01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></Gallery>
<ImageView
android:id="#+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ImageView>
</LinearLayout>
well you can make your own Customised gallery in which every image can be viewed in a grid view followed by a text view below the thumbnail and a button (may be needed for deleting the image).
To view the images dynamically from the memory card you have to implement ArrayList or you can take other oferings of collection framework ..
i did the same and it worked with mine , hopefully will work with you too.
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);