How to make a popup like this in Android? [duplicate] - java

I'm trying to upgrade my PopupMenu so it would come with icons and custom styles.
I have created a new layout for it
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:id="#+id/layout_sharea"
android:background="#drawable/share"
android:paddingLeft="10.0dip"
android:paddingRight="10.0dip"
android:layout_width="wrap_content"
android:layout_height="50.0dip"
android:onClick="share">
<TextView
android:id="#+id/sharetexta"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/share"
android:drawableLeft="#drawable/share_button"
android:drawablePadding="10.0dip"
android:layout_centerVertical="true" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/layout_shareb"
android:background="#drawable/share"
android:paddingLeft="10.0dip"
android:paddingRight="10.0dip"
android:layout_width="wrap_content"
android:layout_height="50.0dip"
android:layout_below="#+id/layout_sharea"
android:onClick="share">
<TextView
android:id="#+id/sharetextb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/share"
android:drawableLeft="#drawable/share_button"
android:drawablePadding="10.0dip"
android:layout_centerVertical="true" />
</RelativeLayout>
</RelativeLayout>
I want the PopupMenu to be customized (to be this layout) like in this picture

A PopupMenu is meant for displaying Menus and there really isn't a good way of customizing the appearance of the menu items. If you want something more flexible, your answer is ListPopupWindow.
private static final String TITLE = "title";
private static final String ICON = "icon";
private List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
// Use this to add items to the list that the ListPopupWindow will use
private void addItem(String title, int iconResourceId) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(TITLE, title);
map.put(ICON, iconResourceId);
data.add(map);
}
// Call this when you want to show the ListPopupWindow
private void showListMenu(View anchor) {
ListPopupWindow popupWindow = new ListPopupWindow(this);
ListAdapter adapter = new SimpleAdapter(
this,
data,
android.R.layout.activity_list_item, // You may want to use your own cool layout
new String[] {TITLE, ICON}, // These are just the keys that the data uses
new int[] {android.R.id.text1, android.R.id.icon}); // The view ids to map the data to
popupWindow.setAnchorView(anchor);
popupWindow.setAdapter(adapter);
popupWindow.setWidth(400); // note: don't use pixels, use a dimen resource
popupWindow.setOnItemClickListener(myListener); // the callback for when a list item is selected
popupWindow.show();
}

Here is my demo for custom ListPopupWindow by custom adapter
Model
public class ListPopupItem {
private String title;
private int imageRes;
public ListPopupItem(String title, int imageRes) {
this.title = title;
this.imageRes = imageRes;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImageRes() {
return imageRes;
}
}
ListAdapter
public class ListPopupWindowAdapter extends BaseAdapter {
private List<ListPopupItem> items;
public ListPopupWindowAdapter(List<ListPopupItem> items) {
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public ListPopupItem getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_popup, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvTitle.setText(getItem(position).getTitle());
holder.ivImage.setImageResource(getItem(position).getImageRes());
return convertView;
}
static class ViewHolder {
TextView tvTitle;
ImageView ivImage;
ViewHolder(View view) {
tvTitle = view.findViewById(R.id.text);
ivImage = view.findViewById(R.id.image);
}
}
}
item_list_popup.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="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="ContentDescription"
tools:src="#mipmap/ic_launcher"
/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
tools:text="Title"
/>
</LinearLayout>
Finally, show ListPopupWindow
(In this demo, I show MATCH_PARENT popup here, you can show a specific with for popup (eg: 100px, 200px,...)
If you set popup width = WRAP_CONTENT, popup width will equals ANCHOR width)
private void showListPopupWindow(View anchor) {
List<ListPopupItem> listPopupItems = new ArrayList<>();
listPopupItems.add(new ListPopupItem("Menu 1", R.mipmap.ic_launcher));
listPopupItems.add(new ListPopupItem("Menu 2", R.mipmap.ic_launcher));
listPopupItems.add(new ListPopupItem("Menu 3", R.mipmap.ic_launcher));
final ListPopupWindow listPopupWindow =
createListPopupWindow(anchor, ViewGroup.LayoutParams.MATCH_PARENT, listPopupItems);
listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
listPopupWindow.dismiss();
Toast.makeText(MainActivity.this, "clicked at " + position, Toast.LENGTH_SHORT)
.show();
}
});
listPopupWindow.show();
}
private ListPopupWindow createListPopupWindow(View anchor, int width,
List<ListPopupItem> items) {
final ListPopupWindow popup = new ListPopupWindow(this);
ListAdapter adapter = new ListPopupWindowAdapter(items);
popup.setAnchorView(anchor);
popup.setWidth(width);
popup.setAdapter(adapter);
return popup;
}
Example using
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showListPopupWindow(view);
}
});
DEMO

Related

how save value of checkbox after close the app in android?

I want save the state of checkbox after close the app
what I should to do?
I don't know how I do that with list view and arrayadapter
how use sharedpreferences here?
in MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word_list);
MyAdView.SetAd((AdView)findViewById(R.id.adView));
ListView list = (ListView) findViewById(R.id.list);
ArrayList<Word> worda = new ArrayList<>();
worda.add(new Word("The B",R.drawable.ic_launcher_background));
worda.add(new Word("The B",R.drawable.ic_launcher_background));
WordAdapter adapter = new WordAdapter(this, worda);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(MainActivity.this, TheBossBabyS1.class);
startActivity(intent);
}
} });
}
}
in Word.java
public class Word {
private String mConversation;
private int mImageResourceId = NO_IMAGE_PROVIDED;
public static final int NO_IMAGE_PROVIDED = -1;
public Word(String conversation){
mConversation = conversation;
}
public Word(String conversation, int imageResourceId){
mConversation = conversation;
mImageResourceId = imageResourceId;
}
public String getConversation(){
return mConversation;
}
public int getImageResourceId(){ return mImageResourceId; }
public boolean hasImage(){
return mImageResourceId != NO_IMAGE_PROVIDED;
}
}
in WordAdapter.java
public class WordAdapter extends ArrayAdapter {
private int mColorResourceId;
public WordAdapter(Context context, ArrayList<Word> worda){
super(context, 0, worda);
}
#SuppressLint("ResourceAsColor")
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null)
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
Word currentWord = (Word) getItem(position);
TextView convTextView = (TextView) listItemView.findViewById(R.id.conv_text_view);
convTextView.setText(currentWord.getConversation());
ImageView imageView = (ImageView) listItemView.findViewById(R.id.image);
if(currentWord.hasImage()) {
imageView.setImageResource(currentWord.getImageResourceId());
imageView.setVisibility(View.VISIBLE);
}
else {
imageView.setVisibility(View.GONE);
}
CheckBox checkbox = (CheckBox) listItemView.findViewById(R.id.checkBox2);
checkbox.setFocusable(false);
checkbox.setFocusableInTouchMode(false);
View textContainer = listItemView.findViewById(R.id.text_container2);
textContainer.setBackgroundColor(((position % 2) == 0) ? Color.parseColor("#B2DFDB") : Color.parseColor("#80CBC4"));
return listItemView;
}
}
in list_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:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/tan_background"
android:orientation="horizontal"
android:id="#+id/text_container2"
>
<ImageView
android:id="#+id/image"
android:layout_width="22dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:contentDescription="#null"
tools:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/conv_text_view"
style="#style/CategoryStyle"
android:layout_width="0dp"
android:layout_weight="8"
android:layout_height="wrap_content"
tools:text="lutti" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="24dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="16dp"
/>
</LinearLayout>
Use sharedpreferences to store the result.
boolean isChecked=false;
SharedPreferences pref = getSharedPreferences("prefs", MODE_PRIVATE);
Editor editor = pref.edit();
if(checkBox.isChecked()){
isChecked=true;
}
editor.putBoolean("checked", isChecked);
editor.apply()
retrieving the data from sharedPreferences.
write the below code just below setContentView();
if(prefs.getBoolean("checked","")==true){
checkBox.setChecked(true);
}

How to set up onItemClickListener

I set up a Listview in Android Studio but need help with coding a OnItemClickListner.
I have tried the code, but doesn't seem to work.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayList<Object> list = new ArrayList<>();
list.add(new LTCItem("30.06 Sign Violations","Submit A Complaint To Texas Attorney General",R.drawable.gavel));
list.add(new LTCItem("U.S. & Texas LawShield","Legal Defense For Self Defense",R.drawable.lawshield));
listView.setAdapter(new LTCAdapter(this, list));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
}
}
Below is my list_view file. Where in the file do block descendantFocusability as suggested? Do I put it under listView? Sorry I am learning .
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alwaysDrawnWithCache="true"
android:background="#000000"
android:padding="8dp">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/itemListViewImgIcon"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#+id/itemListViewImgIcon"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/itemListViewTxtTopicName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
<TextView
android:id="#+id/itemListViewTxtTopicSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/itemListViewTxtTopicName"
</RelativeLayout>
Ok I added the adapter code which is a Java Class item. Where do I add the code here?
public class LTCAdapter extends BaseAdapter {
ArrayList<Object> list;
private static final int LTC_Item = 0;
private static final int HEADER = 1;
private LayoutInflater inflater;
public LTCAdapter(Context context, ArrayList<Object> list) {
this.list = list;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getItemViewType(int position) {
if (list.get(position) instanceof LTCItem) {
return LTC_Item;
} else {
return HEADER;
}
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return 1;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
switch (getItemViewType(i)) {
case LTC_Item:
view = inflater.inflate(R.layout.item_list_view, null);
break;
case HEADER:
view = inflater.inflate(R.layout.item_listview_header, null);
break;
}
}
switch (getItemViewType(i)) {
case LTC_Item:
ImageView image = (ImageView) view.findViewById(R.id.itemListViewImgIcon);
TextView name = (TextView) view.findViewById(R.id.itemListViewTxtTopicName);
TextView subtitle = (TextView) view.findViewById(R.id.itemListViewTxtTopicSubtitle);
image.setImageResource(((LTCItem) list.get(i)).getImage());
name.setText(((LTCItem) list.get(i)).getName());
subtitle.setText(((LTCItem) list.get(i)).getSubtitle());
break;
case HEADER:
TextView title = (TextView) view.findViewById(R.id.itemListViewHeader);
title.setText(((String) list.get(i)));
break;
}
return view;
}
}
Your ListView element doesn't have an ID, you should add android:id="#+id/list_view" to it in the XML file.
Here is an example:
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
As your list view contains focusable elements, you need to write this piece of code in parent layout in your list view item xml file
android:descendantFocusability="blocksDescendants"

how to make a relevant toast only when press on a picture in a listview?

I made a list view with image and text view inside each view. what I'm trying to do is to make toast with the text from the text view every time I press on the image, and not when I press the rest of the view. I tried to use imageClick(View view) function that works when I press an image but I didn't find a way to get the text from the text view. another thing I tried was the onItemClick() function, so i can get the position of the view and get the text from the text view, but I can't check if the image was pressed or not.
anyway here's my code:
public class MainActivity extends AppCompatActivity {
int[] images = {R.drawable.pic_a, R.drawable.pic_b, R.drawable.pic_c,R.drawable.pic_d };
String[] names = {"aa","bb","cc","dd"};
String[] descriptions = {"1a","2a","3a","4a"};
List<ListViewItem> list = new ArrayList<>();
int lastPosition = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateList();
ListView listView = findViewById(R.id.listView);
CustomAdapter customAdapter = new CustomAdapter(this,list);
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
toast(names[position]);
}
});
}
public void imageClick(View view) {
}
private void populateList() {
int size = images.length;
for(int i = 0;i<size;i++){
ListViewItem item = new ListViewItem();
item.imageSource = images[i];
item.name = names[i];
item.description = descriptions[i];
list.add(item);
}
}
}
my listViewItem:
public class ListViewItem {
int imageSource;
String name;
String description;
}
and the XML:
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
the second XML file:
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="30dp"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:id="#+id/imageView" />
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView"
android:layout_toRightOf="#+id/imageView"
android:layout_toEndOf="#+id/imageView"
android:layout_marginLeft="24dp"
android:layout_marginStart="24dp"
android:id="#+id/textView_name" />
<TextView
android:text="TextView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView"
android:layout_alignLeft="#+id/textView_name"
android:layout_alignStart="#+id/textView_name"
android:id="#+id/textView_description" />
and my CustomAdapter:
class CustomAdapter extends BaseAdapter {
private final Activity activity;
List<ListViewItem> list;
public CustomAdapter(Activity activity, List<ListViewItem> list){
super();
this.list = list;
this.activity = activity;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = this.activity.getLayoutInflater().inflate(R.layout.customlayout, null);
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
TextView textView_name = (TextView)view.findViewById(R.id.textView_name);
TextView textView_description = (TextView)view.findViewById(R.id.textView_description);
ListViewItem item = this.list.get(i);
imageView.setImageResource(item.imageSource);
textView_name.setText(item.name);
return view;
}
}

Android: GridView shows all but a few images

I have 6 images downloaded as shown here, but the GridView in my gallery only displays 5 of those images.
I'm trying to copy how Instagram displays its gallery, with a selected image taking up 60% of the screen and the gallery images taking up the rest.
fragment_gallery.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/relLayoutl">
<!--toolbar-->
<include layout="#layout/snippet_top_gallerybar"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100"
android:layout_below="#+id/relLayoutl">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="60">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/galleryImageView"
android:scaleType="centerCrop"/>
<ProgressBar
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/progressBar"
android:layout_centerInParent="true"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="40">
<GridView
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:numColumns="5"
android:verticalSpacing="1.5dp"
android:horizontalSpacing="1.5dp"
android:gravity="center"
android:layout_marginTop="1dp"
android:stretchMode="none"
android:id="#+id/gridView">
</GridView>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
I created a square view to generate square cells
layout_grid_imageview.xml
<?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">
<com.example.sheldon.instagramclone.Util.SquareImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/gridViewImage"
android:adjustViewBounds="true"
android:scaleType="centerCrop"/>
<ProgressBar
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
android:id="#+id/gridProgressBar"/>
</RelativeLayout>
GalleryFragment.java
public class GalleryFragment extends Fragment {
private static final int NUM_COLUMNS = 4;
private ImageView mExit;
private Spinner mSpinner;
private TextView mNext;
private ProgressBar mProgressBar;
private List<String> directories;
private GridView mGridView;
private ImageView mGalleryImage;
private HashMap<String, ArrayList<String>> directoryToImage;
private String append = "file:/";
private String mSelectedImage;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
mExit = (ImageView) view.findViewById(R.id.exitShare);
mSpinner = (Spinner) view.findViewById(R.id.shareSpinner);
mNext = (TextView) view.findViewById(R.id.shareNext);
mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);
mGridView = (GridView) view.findViewById(R.id.gridView);
mGalleryImage = (ImageView) view.findViewById(R.id.galleryImageView);
mExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Navigating to next step in sharing photo");
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra("selected_image", mSelectedImage);
startActivity(intent);
}
});
init();
return view;
}
private void init() {
ImageFinder imageFinder = new ImageFinder();
imageFinder.getImages(getActivity());
directoryToImage = imageFinder.getImageMapping();
directories = new ArrayList<>(directoryToImage.keySet());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), R.layout.spinner_item, directories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemSelected: " + directories.get(position));
setUpGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setUpGridView(String directory) {
final ArrayList<String> imgURLS = directoryToImage.get(directory);
Log.d(TAG, "setUpGridView: Displaying " + directory + " with " + imgURLS.size() + " images");
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth / NUM_COLUMNS;
Log.d(TAG, "setUpGridView: Image Width is " + imageWidth);
mGridView.setColumnWidth(imageWidth);
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, append, imgURLS);
mGridView.setAdapter(adapter);
UniversalImageLoader.setImage(imgURLS.get(0),mGalleryImage, mProgressBar, append);
mSelectedImage = imgURLS.get(0);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UniversalImageLoader.setImage(imgURLS.get(position), mGalleryImage, mProgressBar, append);
mSelectedImage = imgURLS.get(0);
}
});}
I display the images using a library called Universal Image loader
GridImageAdapter.java
public class GridImageAdapter extends ArrayAdapter<String>{
private Context mContext;
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs) {
super(context, layoutResource, imgURLs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
this.layoutResource = layoutResource;
mAppend = append;
this.imgURLs = imgURLs;
}
private static class ViewHolder{
SquareImageView image;
ProgressBar mProgressBar;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.mProgressBar = (ProgressBar) convertView.findViewById(R.id.gridProgressBar);
holder.image = (SquareImageView) convertView.findViewById(R.id.gridViewImage);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
String imgURL = getItem(position);
Log.d(TAG, "getView: Loading position " + position + ", displaying " + imgURL + ", with image " + holder.image);
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(mAppend + imgURL, holder.image, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.VISIBLE);
}
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
if(holder.mProgressBar != null){
holder.mProgressBar.setVisibility(View.GONE);
}
}
});
return convertView;
}
First time posting, so I apologize if there's anything wrong with this post.
Sorry for being so general and unclear in my post, I wasn't quite sure which portion of the code was the problem area. After looking over the code again, I noticed a stupid mistake. I set GridView's numColumns attribute to 5 in fragment_gallery.xml, but calculated the column width in GalleryFragment.java using private static final int NUM_COLUMNS = 4. I assume that this caused images to be displayed in a non-existent 5th column.

How to use Radiogroup with 4 different Radio Button In ArrayAdapter

I have a custom List Adapter that has a question in a Text View and four options as an answer in Radio Buttons. All the Radio Buttons are bound together in a Radio Group.
The problem is that I cannot keep track of the buttons that are checked.On scrolling the buttons get checked on random.
How can I store the radio buttons that are checked for a particular
public class MCQAdapter extends ArrayAdapter {
public MCQAdapter(Activity context, ArrayList<MCQ> mcq) {
super(context, 0, mcq);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.activity_mcqlist, parent, false);
}
final MCQ currentContent = (MCQ) getItem(position);
TextView content = (TextView) listItemView.findViewById(R.id.Question_Block);
content.setText(currentContent.getQuestion());
RadioGroup rg = (RadioGroup) listItemView.findViewById(R.id.Radio_Group);
final RadioButton rb1 = (RadioButton) listItemView.findViewById(R.id.Option1_Block);
rb1.setText(currentContent.getOptionA());
final RadioButton rb2 = (RadioButton) listItemView.findViewById(R.id.Option2_Block);
rb2.setText(currentContent.getOptionB());
final RadioButton rb3 = (RadioButton) listItemView.findViewById(R.id.Option3_Block);
rb3.setText(currentContent.getOptionC());
final RadioButton rb4 = (RadioButton) listItemView.findViewById(R.id.Option4_Block);
rb4.setText(currentContent.getOptionD());
return listItemView;
}
}
public class MCQ {
String question,optionA,optionB,optionC,optionD,answer,userAnswer;
public MCQ(String quest,String a,String b,String c, String d,String ans){
question = quest;
optionA = a;
optionB = b;
optionC = c;
optionD = d;
answer = ans;
}
public String getQuestion(){
return question;
}
public String getOptionA() {
return optionA;
}
public String getOptionB() {
return optionB;
}
public String getOptionC() {
return optionC;
}
public String getOptionD() {
return optionD;
}
public String getAnswer() {
return answer;
}
public String getUserAnswer() {
return userAnswer;
}
public void setUserAnswer(String userAnswer) {
this.userAnswer = userAnswer;
}
}
public class PropertiesOfConstructionMaterail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_properties_of_construction_materail);
final ArrayList<MCQ> mcq = new ArrayList<MCQ>();
//Creating Different Instance Of MCQ to genarte various questions for Properties of Consrtuction Material
mcq.add(new MCQ("The property of material by which it can be beaten or rolled into thin plates, is called ?",
"Malleability","Ductility","Plasticity","Elasticity","Malleability"));
mcq.add(new MCQ("The property by which a body returns to its original shape after removal of the force, is called ?",
"Plasticity","Elasticity","Ductility","Malleability","Elasticity"));
mcq.add(new MCQ("The property of a material by which it can be drawn into smaller section due to tension, is called ?"
,"Plasticity","Ductility","Elasticity","Malleability","Ductility"));
MCQAdapter adapter = new MCQAdapter(this,mcq);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_mcqlist"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.silen.civilengineeringmcq.MCQList"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Question_Block"
android:textSize="18dp"
android:textStyle="bold"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Radio_Group">
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Option1_Block"
android:checked="false"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Option2_Block"
android:checked="false"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Option3_Block"
android:checked="false"/>
<RadioButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Option4_Block"
android:checked="false"/>
</RadioGroup>
You should create a wrapper around your PoJo class (MCQ), name it ViewModel, which store the current state of view inside adapter. In your case that state is a state of radio buttons.
It will looks like:
class ViewModel extends MCQ {
MCQ mcq;
int radioButtonSelectedId;
public ViewModel(MCQ mcq) {
this.mcq = mcq;
this.radioButtonSelectedId = R.id.Option1_Block;
}
public void setRadioButtonSelectedId(int id) {
this.id = id;
}
public int getRadioButtonSelectedId() {
return id;
}
//delegates to mcq getter/setter methods
}
Your getView method:
public View getView(int position, View convertView, ViewGroup parent) {
//your logic above
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
viewModel.setRadioButtonSelectedId(checkedId);
}
});
//same for other radio buttons
rb1.setChecked(viewModel.getRadioButtonSelectedId() == R.id.Option1_Block);
//your logic below
}
So as i mention above, your array list inside adapter would contain ViewModels wrappers, not MCQ classes directly
final ArrayList<ViewModel> mcqList = new ArrayList<>();
MCQ mcq = new MCQ("The property of material by which it can be beaten or rolled into thin plates, is called ?",
"Malleability","Ductility","Plasticity","Elasticity","Malleability")
mcqList.add(new ViewModel(mcq));
I think you should get an option

Categories

Resources