I have a GridView of ImageViews, and while I am building the GUI I currently want to convert some stock drawables into bitmaps, and set the ImageViews to these. They currently just come out as blanks, but as far as I can tell the code is along the correct lines.
The GridView XML: (it expands as more elements are added)
<com.example.tristan.studentshare.ExpandingGridView
android:id="#+id/achievement_grid"
android:layout_below="#+id/profile_details"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:columnWidth="100dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="4dp">
</com.example.tristan.studentshare.ExpandingGridView>
The row_grid_achievements XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<ImageView
android:id="#+id/achievement_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginRight="10dp"
android:src="#drawable/ic_person_black_24dp"/>
<TextView
android:id="#+id/achievement_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="20sp"/>
</LinearLayout>
The Achievement being displayed in the GridView:
public class Achievement {
private String id;
private String name;
private String description;
private Integer progress;
private Bitmap icon;
public Achievement(String id, String name, String description, Integer progress, Bitmap icon) {
this.id = id;
this.name = name;
this.description = description;
this.progress = progress;
this.icon = icon;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Integer getProgress() {
return progress;
}
public Bitmap getIcon() {
return icon;
}
}
The GridView adapter override:
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
public RecordHolder(TextView txtTitle, ImageView imageItem) {
this.txtTitle = txtTitle;
this.imageItem = imageItem;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder = null;
if (row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder(
(TextView)row.findViewById(R.id.achievement_text),
(ImageView)row.findViewById(R.id.achievement_image));
row.setTag(holder);
}
else holder = (RecordHolder)row.getTag();
Achievement achievement = data.get(position);
holder.txtTitle.setText(achievement.getName());
holder.imageItem.setImageBitmap(achievement.getIcon());
return row;
}
The implementation in the Activity:
ExpandingGridView gridView;
ArrayList<Achievement> gridArray = new ArrayList<Achievement>();
AchievementGridViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//TODO:Actual Achievement details from server
Bitmap icon = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_person_black_24dp);
for(int i = 0; i < 5; i++)
{
gridArray.add(new Achievement("0", "Achv" + i, "test", 50, icon));
}
gridView = (ExpandingGridView) findViewById(R.id.achievement_grid);
adapter = new AchievementGridViewAdapter(this, R.layout.row_grid_achievements, gridArray);
gridView.setAdapter(adapter);
}
The visual result:
The grid items should have an icon above them similar to the "profile picture"
In the getView() method of your adapter change the below line
holder.imageItem.setImageBitmap(achievement.getIcon());
according to below
holder.imageItem.setBackgroundDrawable(achievement.getIcon());
I hope it works
Firstly, instead of using GridView, I used RecyclerView, with a GridLayoutManager (http://blog.sqisland.com/2014/12/recyclerview-grid-with-header.html)
To have the elements I wanted displayed in the grid, the RecyclerView uses an Adapter and inflates each grid element with a custom layout, in the following link they use a CardView as the layout root (http://www.androidhive.info/2016/05/android-working-with-card-view-and-recycler-view/)
To get a Drawable instance from Resources, I use the following code:
Drawable d1 = ResourceCompat.getDrawable(getResources(), R.drawable.picture, null);
//or , depending on where your Drawable is,
Drawable d2 = ResourceCompat.getDrawable(getResources(), R.mipmap.picture, null);
In the code where it actually comes to setting the ImageView to a particular Drawable, I used the code:
//Using the Resource ID
myImageView.setImageResource(myResourceID);
//Using a Drawable instance
myImageView.setImageDrawable(myDrawable);
Note that in the AndroidHive link above, whichever of the the above two lines of code would be used in the adapter class, in the Overrided method 'onBindViewHolder'
Related
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
I want to pass images in the asset/drawable folder through adapter and then show them in a new activity. I have tried making research for guidance but didn't get what i want. I want to pass images as i pass texts from string-array to new activity.
This is my Adapter
public class MyAdapter1 extends RecyclerView.Adapter<MyHolder1> implements Filterable {
Context mContext;
ArrayList<Model1> models1, filterList1; // this array list create a list of array which parameter define in our class
CustomFilter1 filter1;
public MyAdapter1(Context context, ArrayList<Model1> models) {
this.mContext = context;
this.models1 = models;
this.filterList1 = models;
}
#NonNull
#Override
public MyHolder1 onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row1, null); //this line inflate our row
return new MyHolder1(view); //this will return our view to holder class
}
#Override
public void onBindViewHolder(#NonNull final MyHolder1 myHolder, int i) {
myHolder.mTitle.setText(models1.get(i).getTitle()); //here is position
myHolder.mDesc.setText(models1.get(i).getDesc());
myHolder.mImageView.setImageResource(models1.get(i).getIcon()); // here we used imge resource
myHolder.setItemCLickListener(new ItemClickListener1() {
#Override
public void onItemClickListener(View v, int position) {
String gTitle = models1.get(position).getTitle();
String gDesc = models1.get(position).getDesc();
BitmapDrawable bitmapDrawable = (BitmapDrawable)myHolder.mImageView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
//get our data with intent
Intent intent = new Intent(mContext, NewActivity2.class);
intent.putExtra("actionBarTitle1", models1.get(position).getTitle());
intent.putExtra("brandNewDesc1", models1.get(position).getBrandNewDesc());
intent.putExtra("soundfile", models1.get(position).getSoundfile());
intent.putExtra("iImage", bytes);
mContext.startActivity(intent);
return;
}
});
}
#Override
public int getItemCount() {
return models1.size();
}
#Override
public Filter getFilter() {
if (filter1 == null){
filter1 = new CustomFilter1(filterList1, this);
}
return filter1;
}
}
This is the Model Class
public class Model1 {
String title;
String desc;
int icon;
int soundfile;
String brandNewDesc;
//constructor
public Model1(String title, String desc, String description, int icon, int music) {
this.title = title;
this.desc = desc;
this.icon = icon;
this.soundfile = music;
this.brandNewDesc = description;
}
//getters
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
public String getBrandNewDesc() {
return brandNewDesc;
}
public int getIcon() {
return icon;
}
public int getSoundfile() {
return soundfile;
}
}
This is my NewActivity2 where i want to show images
private static final String URL="file:///android_asset/html_files/chant2.pdf";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new2);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Keeps android screen on while reading through
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
ActionBar actionBar = getSupportActionBar();
ImageView imageView = (ImageView)findViewById(R.id.ImPage1);
imageView.setImageDrawable(getResources().getDrawable(R.drawable.c1_1));
//get data from previous activity when item of activity is clicked using intent
Intent intent = getIntent();
String mActionBarTitle = intent.getStringExtra("actionBarTitle");
//setctionBar Title
actionBar.setTitle(mActionBarTitle);
//ok we are done, lets run the project
The NewActivity2 XML
<ScrollView
android:id="#+id/scroller"
android:layout_width="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/ImPage1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="#drawable/page1_1" />
<ImageView
android:id="#+id/ImPage2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ImPage1"
android:scaleType="fitXY"
android:src="#drawable/page1_2" />
<ImageView
android:id="#+id/ImPage3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ImPage2"
android:scaleType="fitXY"
android:src="#drawable/page1_3" />
<ImageView
android:id="#+id/ImPage4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ImPage3"
android:scaleType="fitXY"
android:src="#drawable/page1_4" />
</RelativeLayout>
</ScrollView>
</RelativeLayout>
It all depends on how do you want to pass the array.
If you want pass the list of arrays when clicking on any of the adapter images you can write an onclicklistener for each item.
Code here.
If you want to pass in the form of a button click also use the same inside the button click listener.
Intent intent=new Intent(getApplicationContext(),NewActivity2 .class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("VAR1", models1);
intent.putExtras(bundle);
this.startActivity(intent);
And when you reach the Activity2 in the onCreate method Use the below code snippet
Bundle bundle = getIntent().getExtras();
ArrayList<Model1> arraylist = bundle.getParcelableArrayList("VAR1");
Now you will have all the list of Model1 objects. So you can load the images like you did in the adapter class.
You can also get a detailed explanation in this video : https://youtu.be/OMCctaE66b8
Hope that answered your question.
I have a RecyclerView which has CardView as its list items. The CardView have only 2 TextView and one ImageView.
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp"
android:id="#+id/dcCardView">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#drawable/detail_coast_cardview_bg">
<ImageView
android:id="#+id/dcImage"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:src="#drawable/radiation"
android:layout_gravity="center_vertical" />
<LinearLayout
android:layout_gravity="center_vertical"
android:layout_marginStart="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/dcName"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="212"
android:textSize="18dp" />
<TextView
android:textColor="#fff"
android:id="#+id/dcValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="renu asdasasd"
android:textSize="18dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
The class that goes in it is this
public class DetailedCoastRecyclerView {
//region fields
private String name;
private String value;
private int imageName;
//end region fields
//constructor
public DetailedCoastRecyclerView() {}
public DetailedCoastRecyclerView(String name, String value, int image) {
this.name = name;
this.value = value;
this.imageName = image;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public int getImageName() {
return imageName;
}
}
And my CoastDetailsActivity2
public class CoastDetailsActivity2 extends AppCompatActivity {
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private int coastId;
private String jsonCoastDetailsString = "";
private RecyclerView recyclerView;
private DetailedCoastAdapter detailedCoastAdapter;
private ImageView btnBlueFlag;
private ImageView btnHandycapFriendly;
private ImageView btnFavorite;
private ImageView btnWaze;
private LinearLayout mainLayout;
private Beach mBeach;
private TextView tvBeachName;
private DetailedCoastWithForcast detailedCoastWithForcast;
private DetailedBeachMetadata detailedBeachMetadata;
private DetailedBeachHourlyForecast dbhfToday;
private List<DetailedCoastRecyclerView> detailedCoastRecyclerViewList = new ArrayList<>();
private Map<String, String> windBearing = new HashMap<>();
private Map<String, String> jellyType = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coast_details2);
setPointer();
}
private void setPointer() {
this.context = this;
mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
sharedPreferences = context.getSharedPreferences(sharedPreferencesName, MODE_PRIVATE);
editor = sharedPreferences.edit();
tvBeachName = (TextView) findViewById(R.id.tvBeachName);
//start the forecast activity
tvBeachName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ForecastActivity.class);
intent.putExtra("coastId", coastId);
startActivity(intent);
}
});
AndroidNetworking.initialize(context);
//get the coastId
Bundle extras = getIntent().getExtras();
if (extras == null) {
//TODO add snackbar for error
} else {
coastId = extras.getInt("coastId");
}
getBeachDetails();
recyclerView = (RecyclerView) findViewById(R.id.dcRecyclerView);
detailedCoastAdapter = new DetailedCoastAdapter(detailedCoastRecyclerViewList, context);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(detailedCoastAdapter);
}
}
And the adapter
public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.myViewHolder> {
Context context;
private List<DetailedCoastRecyclerView> dbhf0;
public ForecastAdapter(Context context, List<DetailedCoastRecyclerView> dbhf0) {
this.context = context;
this.dbhf0 = dbhf0;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.detailed_coast_card, parent, false);
return new myViewHolder(view);
}
#Override
public void onBindViewHolder(myViewHolder holder, int position) {
DetailedCoastRecyclerView dcrv = dbhf0.get(position);
holder.tvName.setText(dcrv.getName());
holder.tvValue.setText(dcrv.getValue());
//holder.ivImage.setImageResource(dcrv.getImageName());
Glide.with(context).load(dcrv.getImageName()).into(holder.ivImage);
}
#Override
public int getItemCount() {
return dbhf0.size();
}
public class myViewHolder extends RecyclerView.ViewHolder {
ImageView ivImage;
TextView tvName;
TextView tvValue;
public myViewHolder(View itemView) {
super(itemView);
ivImage = (ImageView) itemView.findViewById(R.id.dcImage);
tvName = (TextView) itemView.findViewById(R.id.dcName);
tvValue = (TextView) itemView.findViewById(R.id.dcValue);
}
}
}
When I run it, the getBeachDetails() method gets all the info from the server, add it to an ArrayList and calls notifyDataSetChanged() on the adapter.
I know its working because I see the name and value for every card but the images which are stored locally are not displayed.
I use the same adapter inside a ViewPager with 3 fragments and there everything is ok.
Any ideas?
You provided code of ForecastAdapter, but actually you are using DetailedCoastAdapter. Make sure whether they are the same.
Check whether you have a valid url/resource in dcrv.getImageName()
I guess your image resolution is too high that android buffer cant handle and throws exception while rendering your image, so as I know you have to decrease your image quality when loading it on ImageView.
In Picasso this is done like this by calling resize(width,height) method.
Picasso.with(context)
.load(res)
.resize(width,height)
.placeholder(placeHolder)
.into(view);
I guess it is done in the same way with Glide.
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
I read along the code here (weblink). And the code has been modified a little bit to become like this:
FileArrayAdapter.java
public class FileArrayAdapter extends ArrayAdapter<Item> {
private Context c;
private int id;
private List<Item> items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Item> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public Item getItem(int i) {
return items.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
/* create a new view of my layout and inflate it in the row */
// convertView = ( RelativeLayout ) inflater.inflate( resource, null );
final Item o = items.get(position);
if (o != null) {
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
setDefaultTextColor(t1);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
setDefaultTextColor(t2);
TextView t3 = (TextView) v.findViewById(R.id.TextViewDate);
setDefaultTextColor(t3);
/* Take the ImageView from layout and set the city's image */
ImageView imageCity = (ImageView) v.findViewById(R.id.fd_Icon1);
String uri = "drawable/" + o.getImage();
int imageResource = c.getResources().getIdentifier(uri, null,
c.getPackageName());
Drawable image = c.getResources().getDrawable(imageResource);
imageCity.setImageDrawable(image);
if (t1 != null)
t1.setText(o.getName());
if (t2 != null)
t2.setText(o.getData());
if (t3 != null)
t3.setText(o.getDate());
}
return v;
}
private void setDefaultTextColor(TextView tx) {
tx.setTextColor(Color.parseColor("#f8f9fe"));
}
}
And also another object I made so far:
Item.java
public class Item implements Comparable<Item>{
private String name;
private String data;
private String date;
private String path;
private String image;
public Item(String n,String d, String dt, String p, String img)
{
name = n;
data = d;
date = dt;
path = p;
image = img;
}
public String getName()
{
return name;
}
public String getData()
{
return data;
}
public String getDate()
{
return date;
}
public String getPath()
{
return path;
}
public String getImage() {
return image;
}
public int compareTo(Item o) {
if(this.name != null)
return this.name.toLowerCase().compareTo(o.getName().toLowerCase());
else
throw new IllegalArgumentException();
} }
WIth the list layout a bit customized below:
listupload_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:contentDescription="#string/file_sharing_file_folder"
android:id="#+id/fd_Icon1"
android:layout_width="50dip"
android:layout_height="50dip" >
</ImageView>
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dip"
android:layout_marginTop="5dip"
android:layout_toRightOf="#+id/fd_Icon1"
android:singleLine="true"
android:text="#+id/TextView01"
android:textStyle="bold" >
</TextView>
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextView01"
android:layout_marginLeft="10dip"
android:layout_toRightOf="#+id/fd_Icon1"
android:text="#+id/TextView02" >
</TextView>
<TextView
android:id="#+id/TextViewDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/TextView01"
android:layout_marginLeft="5dip"
android:text="#+id/TextViewDate" >
</TextView>
</RelativeLayout>
My question is:
I know If I want to put Checkbox then I should put it under the XML (layout).
But my case is, I want to make the longClick available for showing the Checkboxes.
And how to do that?
If I simply add this code below, of course it will set the ListView to have onLongClick event....
dList.setLongClickable(true);
dList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// show the checkbox of each lines
return true;
}
});
But to make it once onLongClick executed, how do I show the Combobox? and vice versa....
One possible solution is to hide/show the checkbox based on a flag that is toggled when an item receives a long click.
Do something like this in your adapter's getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
if(showCheckBoxes) {
v.findViewById(R.id.checkbox).setVisible(View.VISIBLE);
} else {
v.findViewById(R.id.checkbox).setVisible(View.GONE);
}
...
}
and then in your long click listener:
dList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
showCheckBoxes = !showCheckBoxes;
fileArrayAdapter.notifyDataSetChanged();
return true;
}
});
Its simple add checkbox in xml and make visibility gone
android:visibility="gone"
And declare a radiobox in FileArrayAdapter class as you did with textbox and the put your
onItemLongClickListener();
In that check if checkbox is visible then make it disappear or if not visible the make it visible.
if(cb.isVisible()){
cb.setVisibility(View.GONE);
}else{
cb.setVisibility(View.VISIBLE);
}
Thats's it.