Converting an Integer to a Drawable - java

I have two Adapter classes and in the first one, i have an Array of Integers[] named mThumbIds which is initialized like this :
// References to our images
private Integer[] mThumbIds = {
R.mipmap.beyondthe_ferocious_flash_majin_vegeta_icon,
R.mipmap.full_tilt_kamehameha_super_saiyan2_gohan_youth_icon,
R.mipmap.merciless_condemnation_goku_black_super_saiyan_rose_and_zamasu_icon,
R.mipmap.everlasting_legend_super_saiyan_goku_icon,
R.mipmap.indestructible_saiyan_evil_legendary_super_saiyan_broly_icon
};
I want to extract an Integer from this array(let's say mThumbIds[0]) and then pass it into my other adapter class and use it to get a valid drawable that i can use for my imageViews.
This is the 2nd adapter's List to hold the extracted Integer:
// References to the images via a List
private List<Integer> mGLBIcons = new ArrayList<>();
And here is where i need the drawable :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
// If it's not recycled, initialize some attributes
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mGLBIcons.get(position));
return imageView;
}
So far, nothing that i've tried has worked so i am asking for your help!
EDITED
ImageViewAdapterClass:
public class UserBoxGlbImageAdapter extends BaseAdapter {
Context mContext;
public UserBoxGlbImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return mGLBIcons.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
// References to the images via a List
private List<Integer> mGLBIcons = new ArrayList<>();
// Used to add card icons from the mainScreenFragment
public List<Integer> getGLBIconsList() {
return mGLBIcons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
// If it's not recycled, initialize some attributes
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Drawable drbl = mContext.getResources().getDrawable(mGLBIcons.get(0));
imageView.setImageDrawable(drbl);
return imageView;
}
public void passInteger(Integer integer) {
mGLBIcons.add(integer);
}
}
GridSettingFragmentClass:
public class UserBoxGLBFragment extends Fragment {
GridView globalGridView;
public UserBoxGLBFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_box_glb, container, false);
globalGridView = view.findViewById(R.id.userBoxGlbGridView);
globalGridView.setAdapter(new UserBoxGlbImageAdapter(getContext()));
return view;
}
}
fragment_user_box_glb.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorSecondaryGLB"
android:orientation="vertical"
tools:context="com.dcv.spdesigns.dokkancards.ui.UserBoxGLBFragment">
<GridView
android:id="#+id/userBoxGlbGridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>
</LinearLayout>

you are using mipmap id and you are trying to load it as a drawable, i doubt it will work. try putting the images in the drawable folder and use thr drawable id.
this is how you set a drawable image in a adapter:
imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_success))
in your case it would be
imageView.setImageDrawable(context.getResources().getDrawable(listOfImages[position]))
Change your constructoras:
public UserBoxGlbImageAdapter(Context c, List<Integer> iconsList) {
mContext = c;
mGLBIcons = iconsList;
}
try using as below:
image_view_layout xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image_view"
android:layout_width="225dp"
android:layout_height="225dp" />
</LinearLayout>
public class UserBoxGLBFragment extends Fragment {
GridView globalGridView;
List<Integer> listOfimages = new ArrayList<>();
public UserBoxGLBFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_box_glb, container, false);
listOfimages.add(R.drawable.beyondthe_ferocious_flash_majin_vegeta_icon);
globalGridView = view.findViewById(R.id.userBoxGlbGridView);
globalGridView.setAdapter(new UserBoxGlbImageAdapter(getContext(),listOfimages));
return view;
}
}
public class UserBoxGlbImageAdapter extends BaseAdapter {
Context mContext;
// References to the images via a List
private List<Integer> mGLBIcons = new ArrayList<>();
public UserBoxGlbImageAdapter(Context c,List<Integer> listOfIcons) {
mContext = c;
mGLBIcons = listOfIcons;
}
#Override
public int getCount() {
return mGLBIcons.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
// Used to add card icons from the mainScreenFragment
public List<Integer> getGLBIconsList() {
return mGLBIcons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If it's not recycled, initialize some attributes
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_view_layout, parent, false));
}
ImageView imageView = (ImageView)convertView.findViewById(R.id.image_view)
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8); imageView.setImageDrawable(mContext.getResources().getDrawable(mGLBIcons.get(0)));
return imageView;
}
}

Related

Android: Spinner and ListView with the same ArrayList

I'm trying to implement a selection activity for a given list of items. Each item is checkable, so I have an item with a TextView and a CheckBox. I implemented a ListView for displaying all the options and a Spinner for showing only the "Top Ten" choices, as a subset of the same list. For now I'm showing all the items in both ListView and Spinner.
I want for the items in the ListView to update when the user selects an item in the Spinner (Note: The reverse path works fine, as the Spinner grabs the updated ArrayList each time it dropsdown).
I tried to implement setOnItemSelectedListener for my Spinner, and to call notifyOnDataSetChanged() for my ListViewAdapter inside the Listener. But the Listener is only called on collapse and I get a weird (maybe unrelated) warning message.
The onItemSelectedListener for the Spinner only runs when the Spinner gets collapsed. But notifyOnDataSetChanged() seems to ignore the checked status of the items as a change. How can I make the first option run everytime I check an item and have the change get properly received by the ListAdapter?
Here's the Activity.java code:
public class TriageReasonActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_triage_reason);
final String[] select_qualification = {
"Select Qualification", "10th / Below", "12th", "Diploma", "UG",
"PG", "Phd"};
Spinner spinner = (Spinner) findViewById(R.id.top_reasons_spinner);
ListView symptoms_list = (ListView) findViewById(R.id.view_list_symptoms);
ArrayList<Symptoms> listVOs = new ArrayList<>();
for (int i = 0; i < select_qualification.length; i++) {
Symptoms reason = new Symptoms();
reason.setTitle(select_qualification[i]);
reason.setSelected(false);
listVOs.add(reason);
}
SymptomsListAdapter mListAdapter = new SymptomsListAdapter(this, 0,
listVOs);
SymptomsSpinnerAdapter mSpinnerAdapter = new SymptomsSpinnerAdapter(this, 0,
listVOs);
symptoms_list.setAdapter(mListAdapter);
spinner.setAdapter(mSpinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
Log.i("Item selected", "but not cahnged");
symptoms_list.invalidateViews();
mListAdapter.notifyDataSetInvalidated();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
Log.i("Not item selected", "but actually it did");
}
});
}
The SpinnerCustom Adapter code:
public class SymptomsSpinnerAdapter extends ArrayAdapter<Symptoms>{
private Context mContext;
private ArrayList<Symptoms> listState;
private SymptomsSpinnerAdapter myAdapter;
private boolean isFromView = false;
/*#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
//mNotifyOnChange = true;
}*/
public SymptomsSpinnerAdapter(Context context, int resource, List<Symptoms> objects) {
super(context, resource, objects);
this.mContext = context;
this.listState = (ArrayList<Symptoms>) objects;
this.myAdapter = this;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
LayoutInflater layoutInflator = LayoutInflater.from(mContext);
convertView = layoutInflator.inflate(R.layout.item_reasons, null);
holder = new ViewHolder();
holder.mTextView = (TextView) convertView.findViewById(R.id.text);
holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.mTextView.setText(listState.get(position).getTitle());
// To check weather checked event fire from getview() or user input
isFromView = true;
holder.mCheckBox.setChecked(listState.get(position).isSelected());
isFromView = false;
if ((position == 0)) {
holder.mCheckBox.setVisibility(View.INVISIBLE);
} else {
holder.mCheckBox.setVisibility(View.VISIBLE);
}
holder.mCheckBox.setTag(position);
holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
if (!isFromView) {
listState.get(position).setSelected(isChecked);
}
}
});
return convertView;
}
#Override
public int getCount() {
return listState.size();
}
#Override
public Symptoms getItem(int position) {
if( position < 1 ) {
return null;
}
else {
return listState.get(position-1);
}
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
private TextView mTextView;
private CheckBox mCheckBox;
}
}
Here's the (almost identical) ListAdapter:
public class SymptomsListAdapter extends BaseAdapter implements ListAdapter {
private Context mContext;
private ArrayList<Symptoms> listState;
private boolean isFromView = false;
public SymptomsListAdapter(Context context, int resource, List<Symptoms> objects) {
this.mContext = context;
this.listState = (ArrayList<Symptoms>) objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(final int position, View convertView,
ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater layoutInflator = LayoutInflater.from(mContext);
convertView = layoutInflator.inflate(R.layout.item_reasons, null);
holder = new SymptomsListAdapter.ViewHolder();
holder.mTextView = (TextView) convertView.findViewById(R.id.text);
holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (SymptomsListAdapter.ViewHolder) convertView.getTag();
}
holder.mTextView.setText(listState.get(position).getTitle());
// To check weather checked event fire from getview() or user input
isFromView = true;
holder.mCheckBox.setChecked(listState.get(position).isSelected());
isFromView = false;
if ((position == 0)) {
holder.mCheckBox.setVisibility(View.INVISIBLE);
} else {
holder.mCheckBox.setVisibility(View.VISIBLE);
}
holder.mCheckBox.setTag(position);
holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
if (!isFromView) {
listState.get(position).setSelected(isChecked);
}
}
});
return convertView;
}
#Override
public int getCount() {
return listState.size();
}
#Override
public Symptoms getItem(int position) {
if( position < 1 ) {
return null;
}
else {
return listState.get(position-1);
}
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
public TextView mTextView;
public CheckBox mCheckBox;
}
}
And here's the warning I'm getting:
W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
EDIT: Adding the layouts and the model class in case they may cause an issue:
Activity Layout:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="demo.hb.activity.visit.TriageReasonActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textFontWeight="6dp"
android:textSize="30sp"
android:layout_margin="20dp"
android:textAlignment="center"
android:textColor="#000000"
android:text="What is the reason for your visit?" />
<Spinner
android:id="#+id/top_reasons_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/btn_dropdown"
android:spinnerMode="dropdown"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="end">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/view_list_symptoms"
android:layout_above="#+id/next_btn"
android:layout_alignParentTop="true"/>
</RelativeLayout>
</LinearLayout>
</FrameLayout>
Item layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:text="text"
android:textAlignment="gravity" />
<CheckBox
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Model Class:
public class Symptoms {
private String title;
private boolean selected;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
The reason that nothing is changing is because you haven't implemented the method to handle the data set changes. You need to handle how the data is reloaded in your adapter:
public class SymptomsListAdapter extends BaseAdapter implements ListAdapter {
...
public void refreshData(ArrayList<Symptoms> objects){
this.listState = (ArrayList<Symptoms>) objects;
notifyDataSetChanged();
}
...
}
This link does a great job of explaining how the notifyDataSetInvalidated() works (or in your case, why it's not working).

How to display the actual image onclick from gridview

I'm trying to get the image in the chat box when I click on any of the images from the gridview however, whenever I try to do so it comes up with a text, so please advise what can be done to get the image itself instead of the text that is appearing, please help me out I've been stuck for too long
smiles_items_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView android:id="#+id/smile_image_view"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_gravity="center"/>
</LinearLayout>
BottomSheetDialog_Smiles.java
public class ImageAdapter2 extends BaseAdapter {
private Context mContext;
private final int[] mThumbIds;
String[] mThumbIdsString = null;
public ImageAdapter2(Context c, int[] mThumbIds , String[] mThumbIdsString)
{
mContext = c;
this.mThumbIds = mThumbIds;
this.mThumbIdsString = mThumbIdsString;
}
#Override
public int getCount() {
return mThumbIds.length & mThumbIdsString.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
ImageView img;
}
#Override
public View getView(final int position, final View convertView,
ViewGroup parent) {
final Holder holder = new Holder();
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.smiles_items_layout, null);
null);
holder.img = (ImageView) grid.findViewById(R.id.smile_image_view);
holder.img.setImageResource(mThumbIds[position]);
gridView2.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
Drawable drawable;
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int i, long l) {
JSONDictionary imageChat = new JSONDictionary();
LinearLayout layout= (LinearLayout)view;
ImageView imageView = (ImageView) layout.getChildAt(0);
imageView.getDrawable();
imageChat.put("message", imageView);
Communicator.getInstance().emit("new chat message",
imageChat);
}
});
return grid;
}
}
This is the result which appears when clicking on the image
Do you need an ImageView inside an image?
I used this code to get an image.
Send your view this method get as image.
protected Bitmap ConvertToBitmap(ImageView image_view) {
Bitmap map;
image_view.setDrawingCacheEnabled(true);
image_view.buildDrawingCache();
return map=image_view.getDrawingCache();
}
In ur adapter code
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap b = ConvertToBitmap(holder.img);;
//now get bitmap used to assign
imageChat.put("message", b);
Communicator.getInstance().emit("new chat message",
imageChat);
}
});

GridView.setOnItemClickListener triggers whole row

I have a grid view 3x3. Inside this grid I have ImageViews.
I set up OnItemClickListener but when I click on the ImageView only the first one is pressed in a row no matter which column I am pressing. Also I can be pressing outside the ImageView (empty space) but still first ImageView on that row is pressed.
XML
<GridView
android:id="#+id/test"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="3"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
MainActivity
GridView gridview = (GridView) findViewById(R.id.test);
gridview.setAdapter(new HexAdapter(getBaseContext()));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Log.e("gridView", "hallo" + position);
}
});
and this is my adapter
public class HexAdapter extends BaseAdapter {
private Context mContext;
public HexAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return (Object) mThumbIds[position];
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.logo, R.drawable.logo,
R.drawable.logo, R.drawable.logo,
R.drawable.logo, R.drawable.logo,
};
}
R.drawable.logo is just a random image a chose.
I have experienced this problem and the solution I came up with is simple:
In your adapter give an unique TAG to each view
view.setTag(id); //example
And on ItemClickListener just match the tags for each view and you will be sure this will never happen:
if(view.getTag().equals(id))
doStuff();
if(view.getTag().equals(otherId))
doOtherStuff();
And so on.
Here is an example:
Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ImageView imageView;
CustomTextView textView;
LinearLayout main_grl;
if (v == null) {
v = layoutInflater.inflate(R.layout.professions_gridview_item,parent,false);
}
main_grl = (LinearLayout)v.findViewById(R.id.main_grl);
main_grl.setBackground(ContextCompat.getDrawable(mContext,R.drawable.ps_background_selector));
imageView = (ImageView) v.findViewById(R.id.imageView);
textView = (CustomTextView) v.findViewById(R.id.textView);
imageView.setImageResource(ApplicationConstants.finalListIV[position]);
textView.setText(ApplicationConstants.finalListTV[position]);
v.setTag(ApplicationConstants.finalListTV[position]);
return v;
}
Activity
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if((Integer) view.getTag() == someTag){
//doStuff
} else if((Integer) view.getTag() == otherTag){
//doOtherStuff
} else{
//andSomeOther
}
}

Android Studio Dynamically Changing Images in GridView

I have set up a GridView Successfully, however I want to be able to change the Images within the the GridView dependent upon a variable. For example:
int a = 2
if (a == 2){
Integer[] images = {
R.drawable.image1
R.drawable.image3
}
} else {
Integer[] images = (
R.drawable.image2
R.drawable.image4
}
}
However I can't find a way to do this. The code I am working with at the moment is:
GridView cardList = (GridView) findViewById(R.id.cardList);
cardList.setAdapter(new ImageAdapter(this));
cardList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(Create.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return images.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(215, 215));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(images[position]);
return imageView;
}
private Integer[] images = {
R.drawable.iamge1, R.drawable.image2
};
}
Try something like this:
The activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.gridView);
int images[] = {R.drawable.ic_action_name};
ImageAdapter imageAdapter = new ImageAdapter(getApplicationContext(),images);
gridView.setAdapter(imageAdapter);
}
}
Your adapter class:
public class ImageAdapter extends BaseAdapter {
private int images[];
Context context;
public ImageAdapter(Context context, int images[]){
this.context = context;
this.images = images;
}
private class Holder{
ImageView imageView;
}
#Override
public int getCount(){
return images.length;
}
#Override public Object getItem(int position){
return null;
}
#Override
public long getItemId(int position){
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent){
//All of this Holder stuff is so that the View doesn't jump around wildly
final Holder holder;
LayoutInflater inflater;
if (view == null){
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.singleimage,null);
holder = new Holder();
holder.imageView = (ImageView) view.findViewById(R.id.singleImage);
view.setTag(holder);
}
else {
holder = (Holder) view.getTag();}
holder.imageView.setImageResource(images[position]);
return view;
}
}
You also need a simple xml file for the single image in the gridView. Name this "singleimage.xml"
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/singleImage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
Activity xml file:
<?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_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ri.emily.testapp.MainActivity">
<GridView
android:layout_width="match_parent"
android:id="#+id/gridView"
android:layout_height="match_parent" />
</RelativeLayout>

Android custom ArrayAdapter with custom object

I am new for Android development.
I was trying to implement a custom ArrayAdapter to accept custom object in Android Studio.
I have referenced the source code from some tutorial, but my screen output was improper that the custom object only fill in the TextView which link with the textViewResourceId of ArrayAdapter , but not the custom object's properties fill in all EditText in the layout appropriately.
I tried to remove textViewResourceId parameter in the constructor of ArrayAdapter to fix the problem, but Android Studio returned error - You must supply a resource ID for a TextView
I want the properties of custom object fill in all EditText and no error message be returned, can anyone give me a hint?
Here is my layout:
row_layout.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">
<TextView
android:id="#+id/row_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
<EditText
android:id="#+id/row_no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="1dp"
android:layout_gravity="center_horizontal"
android:background="#color/colorWhite"/>
<EditText
android:id="#+id/row_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_margin="1dp"
android:layout_gravity="center_horizontal"
android:background="#color/colorWhite"/>
</LinearLayout>
Here is my custom object:
Row.java
public class Row
{
public int RowNo;
public String RowText;
public Row(int no, String text)
{
this.RowNo = no;
this.RowText = text;
}
}
Here is my custom ArrayAdapter:
RowAdapter.java
public class RowAdapter extends ArrayAdapter<Row> {
private final Activity _context;
private final ArrayList<Row> rows;
static class ViewHolder
{
EditText RowNo;
EditText RowText;
}
public RowAdapter(Activity context, ArrayList<Row> rows)
{
super(context,R.layout.row_layout, R.id.row_id ,rows);
this._context = context;
this.rows = rows;
}
public View GetView(int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
if(convertView == null)
{
LayoutInflater inflater = _context.getLayoutInflater();
convertView = inflater.inflate(R.layout.row_layout,parent,false);
holder = new ViewHolder();
holder.RowNo = (EditText)convertView.findViewById(R.id.row_no);
holder.RowText = (EditText)convertView.findViewById(R.id.row_text);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.RowNo.setText(rows.get(position).RowNo);
holder.RowText.setText(rows.get(position).RowText);
return convertView;
}
}
Here is my Activity class:
RowActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row_list_page);
listView = (ListView)findViewById(R.id.list_view);
ArrayList<Row> rows = new ArrayList<Row>();
rows.add(new Row(1,"Test"));
rows.add(new Row(2,"Test"));
rows.add(new Row(3"Test"));
RowAdapter adapter = new RowAdapter(this,rows);
listView.setAdapter(adapter);
}
Here is working adapter code
public class RowAdapter extends ArrayAdapter<Row> {
private final Activity _context;
private final ArrayList<Row> rows;
public class ViewHolder
{
EditText RowNo;
EditText RowText;
}
public RowAdapter(Activity context, ArrayList<Row> rows)
{
super(context,R.layout.row_layout, R.id.row_id ,rows);
this._context = context;
this.rows = rows;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder = null;
if(convertView == null)
{
LayoutInflater inflater = _context.getLayoutInflater();
convertView = inflater.inflate(R.layout.row_layout,parent,false);
holder = new ViewHolder();
holder.RowNo = (EditText)convertView.findViewById(R.id.row_no);
holder.RowText = (EditText)convertView.findViewById(R.id.row_text);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.RowNo.setText(""+rows.get(position).RowNo);
holder.RowText.setText(rows.get(position).RowText);
return convertView;
}
}
Your getting exception at holder.RowNo.setText(rows.get(position).RowNo);
so replace it with
holder.RowNo.setText(""+rows.get(position).RowNo);
Change with below code:-
RowAdapter.java
public class RowAdapter extends BaseAdapter {
private final Context _context;
private final ArrayList<Row> rows;
public RowAdapter(Context context, ArrayList<Row> rows)
{
this._context = context;
this.rows = rows;
}
#Override
public int getCount() {
return rows.size();
}
#Override
public Object getItem(int position) {
return rows;
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) _context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView=inflater.inflate(R.layout.row_layout, null,true);
EditText RowNo = (EditText) rowView.findViewById(R.id.row_no);
EditText RowText = (EditText) rowView.findViewById(R.id.row_text);
RowNo.setText(rows.get(position).RowNo);
RowText.setText(rows.get(position).RowText);
return rowView;
}
}
public View getView (int position, View convertView, ViewGroup parent)
This method is called to get view object.
In your code there is GetView, not getView
change your
public View GetView(int position, View convertView, ViewGroup parent)
with
#Override
public View getView(int position, View convertView, ViewGroup parent)
and
holder.RowNo.setText(rows.get(position).RowNo);
with
holder.RowNo.setText(""+rows.get(position).RowNo);

Categories

Resources