I used https://github.com/wdullaer/SwipeActionAdapter to swipe each items on listview
once i swipe one of the item, textview text will increment to one. The problem if i will scroll the list, the textview will return to each default value which is 0 and some hidden items also incrementing.
Code for onswipe event:
switch (direction) {
case SwipeDirections.DIRECTION_FAR_LEFT:
selectedText = (TextView) getViewByPosition(position, getListView()).findViewById(R.id.txtNumber);
selectedText.setText(String.valueOf(Integer.parseInt(selectedText.getText().toString()) + 1));
break;
and adapter code:
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(data);
} catch (JSONException e) {
e.printStackTrace();
}
String[] strArr = new String[jsonArray.length()];
ArrayList<String> arrayList = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
strArr[i] = jsonArray.getJSONObject(i).getString("name");
arrayList.add(jsonArray.getString(i));
stringAdapter = new ArrayAdapter<String>(
this,
R.layout.items,
R.id.txtName,
new ArrayList<String>(Arrays.asList(strArr))
);
setListAdapter(stringAdapter);
stringAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
items.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="100sp"
android:background="#drawable/listview_style"
android:padding="8dp"
android:descendantFocusability="blocksDescendants">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:src="#mipmap/ic_launcher"
android:layout_centerVertical="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/txtName"
android:textSize="20sp"
android:gravity="center"
android:ellipsize="none"
android:singleLine="false"
android:scrollHorizontally="false"
android:layout_centerVertical="true"
android:layout_marginLeft="20sp"
android:layout_marginRight="20sp"
android:layout_toRightOf="#+id/imageView"
android:layout_toLeftOf="#+id/txtNumber"
android:layout_toStartOf="#+id/txtNumber"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:id="#+id/txtNumber"
android:textSize="25sp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="40dp"
android:layout_marginEnd="40dp"
/>
</RelativeLayout>
i'm thinking of item position is not valid or view is not valid.
anyidea how to solve this. thanks
UPDATE
Incrementing now working properly, but item name is not populating. See attached
The problem is that listview cheats. It's a recycling view so what happens is that you actually just have the same like 10 views you are currently seeing. When you scroll far enough that the view goes away, it appears again as the view that just came into view. To do this, it got rid of the old view, asked the adapter to make this trashed view into something that will look like the new view (which is awesome for memory and quick view creation).
This is why your items go away, because the views are recycled by the listview using the adapter after you scroll away. If you really want to see this, try making swipe turn the visibility of your view to INVISIBLE, then you'll notice views all over the place just being missing. Because they are the same view.
In short, swipe must change the data used to build the view. Any changes to the view itself will either be wiped away, or mess up the other views (things like visibility and .transform() are not often reset by adapters), which are really just the same view again.
public class SwipeActivity extends AppCompatActivity {
SwipeActionAdapter mAdapter;
private class YourCustomRowEntry {
String displayString;
int swipes;
public YourCustomRowEntry( String displayString, int swipes) {
this.swipes = swipes;
this.displayString = displayString;
}
}
private class Holder {
public TextView textName, textNumber;
public ImageView imageView;
public Holder(TextView textName, TextView textNumber, ImageView imageView) {
this.textName = textName;
this.textNumber = textNumber;
this.imageView = imageView;
}
}
ArrayList<YourCustomRowEntry> mDataYouEditThatBacksTheAdapter = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe);
for (int i = 1; i <= 200; i++) {
mDataYouEditThatBacksTheAdapter.add(new YourCustomRowEntry("Row " + i,0));
}
BaseAdapter customAdapter = new BaseAdapter() {
#Override
public int getCount() {
return mDataYouEditThatBacksTheAdapter.size();
}
#Override
public Object getItem(int position) {
return mDataYouEditThatBacksTheAdapter.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView;
Holder viewHolder;
if (convertView != null) {
itemView = convertView; //if you already made this view, and it's being recycled use that.
viewHolder = (Holder)convertView.getTag(); //And fetch the already findByViews things.
}
else {
//if this is the first time, inflate the view.
itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false);
TextView textName = (TextView)itemView.findViewById(R.id.txtName);
TextView textNumber = (TextView)itemView.findViewById(R.id.txtNumber);
ImageView imageView = (ImageView)itemView.findViewById(R.id.imageView);
viewHolder = new Holder(textName,textNumber,imageView);
itemView.setTag(viewHolder); //store the data in the view's tag.
}
YourCustomRowEntry ycre = mDataYouEditThatBacksTheAdapter.get(position);
viewHolder.textName.setText(ycre.displayString);
viewHolder.textNumber.setText("" + ycre.swipes); // Gotta tell it that this is a string and not a resource.
//You would also set the imageView from the saved set of data here too.
return itemView;
}
};
ListView listView = (ListView)findViewById(R.id.myActivitysListView);
// Wrap your content in a SwipeActionAdapter
mAdapter = new SwipeActionAdapter(customAdapter);
// Pass a reference of your ListView to the SwipeActionAdapter
mAdapter.setListView(listView);
// Set the SwipeActionAdapter as the Adapter for your ListView
listView.setAdapter(mAdapter);
// Listen to swipes
mAdapter.setSwipeActionListener(new SwipeActionAdapter.SwipeActionListener() {
#Override
public boolean hasActions(int position) {
// All items can be swiped
return true;
}
#Override
public boolean shouldDismiss(int position, int direction) {
// Only dismiss an item when swiping normal left
return false;
//return direction == SwipeDirections.DIRECTION_NORMAL_LEFT;
}
#Override
public void onSwipe(int[] positionList, int[] directionList) {
for (int i = 0; i < positionList.length; i++) {
int direction = directionList[i];
int position = positionList[i];
switch (direction) {
case SwipeDirections.DIRECTION_FAR_LEFT:
mDataYouEditThatBacksTheAdapter.get(position).swipes++; //add 1 to swipes;
mAdapter.notifyDataSetChanged();
break;
case SwipeDirections.DIRECTION_FAR_RIGHT:
mDataYouEditThatBacksTheAdapter.get(position).swipes--; //subtract 1 to swipes;
mAdapter.notifyDataSetChanged();
break;
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_swipe, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Video of it working:
https://youtu.be/6wPF2OOKu2U
Save the array you use to back your listview. You need to have that so you can change it and get the Adapter to build new views. notifyDataSetChanged() and it updates the and rebuilds the views, from the original data structure it saved. Meaning you need to modify that data, not the view. This properly writes a class and uses that to build the views.
Related
I want to list only the disliked items in my recyclerview. I have a full list of items in rv in MainActivity (did not set visibility here). I can set for each items like or dislike by clicking on imagebutton. The MainActivity shows full list of items (cardviews) that shows imagebutton likes or not. If item is liked, this is stored in firebase db as separate entry under Likes with item key (firebase key .push) and not under Items. (in firebase db I have Users, Items, Likes).
Here is my subactivity code, DislikedItemsActivity, where I want to show only items that are disliked by using setVisibility(View.GONE) for items that are liked. This still holds the space between items for the View.GONE items as well (though these cardviews are empty).
mRecyclerView = (RecyclerView) findViewById(R.id.rvItemList);
mRecyclerView .setHasFixedSize(true);
final LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
final FirebaseRecyclerAdapter<Item, MainActivity.ItemViewHolder>
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Item,
MainActivity.ItemViewHolder>(
Item.class,
R.layout.list_item,
MainActivity.ItemViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(final MainActivity.ItemViewHolder viewHolder, final Item model, final int position) {
final String itemKey = getRef(position).getKey();
mDatabaseItemsLiked.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// if item is not liked, thus no user set in db ( I want to see only items that are liked in my recyclerview)
if (!dataSnapshot.child(itemKey).hasChild(mAuth.getCurrentUser().getUid())) {
viewHolder.mView.setVisibility(View.VISIBLE);
viewHolder.itemNameSetup(model.getItemName());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent itemSheetIntent = new Intent(DislikedItemsActivity.this, ItemSheetActivity.class);
adatlapIntent.putExtra("item_key", itemKey);
startActivity(itemSheetIntent);
}
});
} else {
viewHolder.mView.setVisibility(View.GONE);
mRecyclerView.getAdapter().notifyItemRemoved(position); //this puts together the visible items, but when scrolling, it gets messed up
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, databaseError.toString());
}
});
}
#Override
public void onBindViewHolder(MainActivity.TermekViewHolder viewHolder, int position) {
super.onBindViewHolder(viewHolder, position);
}
};
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
I looked for many solutions like onBindViewHolder, notifyDataChanged, set margin to 0, set layout size in xml to wrap_content. The best I could get is to have the not-liked items without space with mRecyclerView.getAdapter().notifyItemRemoved(position);, but scrolling the list backwards the whole rv gets messed up (duplicate entry, empty spaces, disordered list).
I don't know how to list only the disliked items from the complete item list from MainActivity rv in a new activity? My code above shows only disliked items, but only until I scroll to end of list, if I scroll backwards the rv gets messed up. I logged the positions of views (18items) in onBindViewHolder and first it counts all items in sequence (17,16,15,14...0), but scrolling from end of list to backwards the position jumps from 0 to 4 like 7times (changes always how many times) then it is the same for item 5,6, until item 17 (all of their positions showed in onBindViewHolder 7 or 8 times during scrolling ie. 5,5,5,5,6,6,6,6) and only for backward scrolling and during backward move rv shows only disliked items or empty views or duplicate entry of disliked item.
my xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="horizontal"
android:background="#drawable/hatter"
tools:context="com.example.user.itemlist.ItemsLikedActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rvItemList"
>
</android.support.v7.widget.RecyclerView>
(don't know how to add pics) When disliked list appears, it shows first item (cardview takes up the full screen), and when I start to scroll the list (from 1. visible item to next visible item) if there is space(item1 vis and next vis item is 4), rearrange and I can see that next visible item(item4) moves to 1. visible item, then the rest of the list is arranged well, until I start to scroll back, then it rearranges the rv with spaces and with double entry. The list goes back and forth until both end (which is the length of full items list and not just the disliked items), but visible items gets all messed up.
use this code to remove occupied space :
ViewGroup.LayoutParams params = holder.itemView.getLayoutParams();
params.height = 0;
holder.itemView.setLayoutParams(params);
I found solution to filter the complete database. In my question I wanted to get only the liked/disliked items in a separate activity, though my previous code showed filtered items, but with gaps.
In below code, I changed the DatabaseReferences (mDatabase -node with complete item list and mDatabaseItemsLiked -node with item uid and user uid).
This gave only empty cards with only number as the likedItems, but to get name from the mDatabase (complete list), I used dataSnapshot.getValue(Item.class).getItemName().
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Item,
MainActivity.ItemViewHolder>(
Item.class,
R.layout.list_item,
MainActivity.ItemViewHolder.class,
mDatabaseItemsLiked
) {
#Override
protected void populateViewHolder(final MainActivity.ItemViewHolder
viewHolder, final Item model, final int position) {
final String itemKey = getRef(position).getKey();
mDatabase.child(itemKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
viewHolder.itemNameSetup(dataSnapshot.getValue(Item.class).getItemName());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent itemSheetIntent = new Intent(LikedItemsActivity.this, ItemSheetActivity.class);
adatlapIntent.putExtra("item_key", itemKey);
startActivity(itemSheetIntent);
}
});
This works for me without any problem. I hope it is network efficient.
You can try to store the liked ítem in boolean array and later in populateViewHolder check if ítem has like o no and set visibility.
I would do like that:
In your class declare :
private boolean [] itemLiked;
In your constructor :
this.itemLiked = new boolean [arrayOfAllItems.size]
On click event:
itemLiked[position] = true; //Where position is row position
onBindViewholder or in your case populateViewHolder:
if (!itemLiked[position]) {
viewHolder.mView.setVisibility(View.GONE); }
Hope it helps, good luck!
EDITED
I do not understand exactly what you want to do, that's why I leave you the code for two cases.
Case 1. Mark and dis-mark the rows.
Case 2. Save to database or delete.
In continuation the complete code
Activity XML add RecyclerView:
<android.support.v7.widget.RecyclerView
android:id="#+id/my_rv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Make a custom layout for row:
<TextView
android:id="#+id/question_tv"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:text="QUESTION"/>
<ImageButton
android:id="#+id/like"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#android:drawable/ic_input_add"
android:background="#android:color/transparent"
android:layout_marginRight="4dp"/>
<ImageButton
android:id="#+id/dislike"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#android:drawable/ic_delete"
android:background="#android:color/transparent"
android:layout_marginRight="4dp"/>
Make a Model class:
public class SomeModel {
private String question;
public SomeModel(String question) {
this.question = question;
}
public String getQuestion() {
return question;
}
}
Make Adapter Class:
public class SomeAdapter extends RecyclerView.Adapter {
private ArrayList<SomeModel> arrayList;
private boolean [] item_has_like, item_hase_vote;
public SomeAdapter(ArrayList<SomeModel> arrayList) {
this.arrayList = arrayList;
this.item_has_like = new boolean[arrayList.size()];
this.item_hase_vote = new boolean[arrayList.size()];
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder myViewHolder = null;
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.draw_row, parent, false);
myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final MyViewHolder myViewHolder = (SomeAdapter.MyViewHolder)holder;
final SomeModel item = arrayList.get(position);
int backGround;
/**In background you can save whateveryou need, example:
* backGround= R.drawable.some_background;
* backGround= View.GONE;
*.....
**/
if (item_hase_vote[position]){
if (item_has_like[position])
{
backGround= Color.GREEN;//
} else {
backGround= Color.RED;
}
} else {
backGround= Color.TRANSPARENT;
}
myViewHolder.questionTV.setText(item.getQuestion());
myViewHolder.questionTV.setBackgroundColor(backGround);
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView questionTV;
private ImageView like, dislike;
public MyViewHolder(final View itemView) {
super(itemView);
questionTV = (TextView)itemView.findViewById(R.id.question_tv);
like = (ImageView)itemView.findViewById(R.id.like);
dislike = (ImageView)itemView.findViewById(R.id.dislike);
like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Item been voted
item_hase_vote[getAdapterPosition()] = true;
//Item got Like save in boolean array by row position
item_has_like[getAdapterPosition()] = true;
//notify your adapter
notifyDataSetChanged();
/*OR Here comes the code where You save Item in Your Data Base.*/
}
});
dislike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Item been voted
item_hase_vote[getAdapterPosition()] = true;
// Item got DisLike save in boolean array by row position
item_has_like[getAdapterPosition()] = false;
//notify your adapter
notifyDataSetChanged();
/*OR Here You Remove item on Dislike
arrayList.remove(getAdapterPosition());
notifyItemRemoved(getAdapterPosition());
notifyItemRangeChanged(getAdapterPosition(),arrayList.size());
*/
}
});
}
}
}
And Your Activity:
public class SomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_some);
ArrayList<SomeModel> arrayList = new ArrayList<>();
for (int i = 0; i <77 ; i++) {
arrayList.add(new SomeModel("Question " + i));
}
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.my_rv);
SomeAdapter adapter = new SomeAdapter(arrayList);
recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
}
}
Saving the selected item by the adapterPosition in boolean, String, int....[], the Adapter always gona know whats going on with every item and like that your list always gona be arranged.
Good Luck!
I also got the same problem. what i thought was if RelativeLayout load one after one, height=0, the specs will remove.So it works for me.
This is my ViewHolder. I Introduces my reletivelayout here.
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
TextView txtdate;
RelativeLayout con_rel;
String name_day = "no name";
public BlogViewHolder(View itemView) {
super(itemView);
mView=itemView;
con_rel=(RelativeLayout)itemView.findViewById(R.id.con_rel);
txtdate = (TextView)itemView.findViewById(R.id.day);
}
}
The I set height and width
con_ref=FirebaseDatabase.getInstance().getReference().child("/consultation");
FirebaseRecyclerAdapter<Consultation,SelectConsaltation.BlogViewHolder>recyclerAdapter=new FirebaseRecyclerAdapter< Consultation,SelectConsaltation.BlogViewHolder>(
Consultation.class,
R.layout.consultation_card,
SelectConsaltation.BlogViewHolder.class,
con_ref
) {
#Override
protected void populateViewHolder(final SelectConsaltation.BlogViewHolder viewHolder, final Consultation model, final int Consultation) {
Shedule_ref.child(model.getScheduleID()).child("Day").addValueEventListener(new ValueEventListener() {
ViewGroup.LayoutParams params = viewHolder.con_rel.getLayoutParams();
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
name_day = dataSnapshot.getValue(String.class);
if (doctor_id_from_doctor.equals( model.getDoctorID() )){
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date strDate = null;
try {
strDate = sdf.parse(model.getDate());
} catch (ParseException e) {
e.printStackTrace();
}
if(System.currentTimeMillis()<=strDate.getTime() ) {
params.height = 300;
params.width =800;
viewHolder.con_rel.setLayoutParams(params);
viewHolder.setDate(model.getDate(),name_day);
}
else {
**params.height = 0;
params.width = 0;
viewHolder.con_rel.setLayoutParams(params);**
}
}
else {
params.height = 0;
params.width = 0;
viewHolder.con_rel.setLayoutParams(params);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
recyclerView.setAdapter(recyclerAdapter);
}
My card view code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/con_rel"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="3dp"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content" android:background="#a2ffffff">
<LinearLayout
android:layout_width="match_parent"
android:layout_marginTop="3dp"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/day"
android:layout_marginTop="10dp"
android:textSize="18sp"
android:layout_marginLeft="5dp"
android:textColor="#color/colorBlack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/_07th_of_sunday_january_2018_at_9_00am"/>
<TextView
android:id="#+id/nextnumber"
android:layout_marginLeft="5dp"
android:textSize="18sp"
android:textColor="#color/colornextnumber"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:text="#string/next_avealable_number_is_04"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/booknow"
android:textStyle="bold"
android:textSize="18sp"
android:layout_marginTop="20dp"
android:layout_marginLeft="240dp"
android:layout_marginBottom="10dp"
android:textColor="#color/colorbookNow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/book_now"/>
</LinearLayout>
</RelativeLayout>
Here is my inreface
I am making a question that could be like a duplicated question, but i have tried everything and nothing worked for me. I have created a listview witch every item has two views, one textview and one checkbox. Its like a multiselect listview. Every item has a level on its own: easy, normal, hard. When a level is chosen from a dropdown: All, Easy, Normal, Hard.. the list changes, just like a filter system.
But when i write listView.getChildAt(i).setVisibility(View.GONE); the content of the row is removed but the space occupied is not released.
Any help?
This is my code:
public class CreatePresentation extends Activity
{
DatabaseHelper db = new DatabaseHelper(this);
MyCustomAdapter dataAdapter = null;
List<Slider> list;
ListView listView;
String Text;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.create_presentation);
displayListView();
checkButtonClick();
}
private void displayListView()
{
list = new ArrayList<Slider>();
ArrayList<Slider> oldList = db.getAllSliders();
for (Slider anOldList : oldList) {
String s = anOldList.toString();
int in = anOldList.getId();
String lev = anOldList.getLevel();
Slider slider = new Slider(in, s, lev, false);
list.add(slider);
}
dataAdapter = new MyCustomAdapter(this, R.layout.list_check_box, list);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(dataAdapter);
}
private class MyCustomAdapter extends ArrayAdapter<Slider> {
private ArrayList<Slider> list;
public MyCustomAdapter(Context context, int textViewResourceId, List<Slider> list) {
super(context, textViewResourceId, list);
this.list = new ArrayList<Slider>();
this.list.addAll(list);
}
private class ViewHolder {
TextView text;
CheckBox checkbox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
final Slider slider = list.get(position);
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_check_box, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.sliderTitle);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
Spinner dropdown = (Spinner)findViewById(R.id.spinner);
String[] items = new String[]{"Tutto", "Facile", "Medio", "Difficile"};
ArrayAdapter<String> adapter = new ArrayAdapter<String (CreatePresentation.this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
Text = dropdown.getSelectedItem().toString();
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Slider slider = (Slider) cb.getTag();
slider.setSelected(cb.isChecked());
}
});
try {
if (list.get(position).getLevel().equals("Facile"))
convertView.setBackgroundColor(Color.parseColor("#477C3D"));
else if (list.get(position).getLevel().equals("Medio"))
convertView.setBackgroundColor(Color.parseColor("#936019"));
else if (list.get(position).getLevel().equals("Difficile"))
convertView.setBackgroundColor(Color.parseColor("#A02307"));
} catch (Throwable e) {
e.printStackTrace();
}
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, final int position, long id) {
Text = parentView.getItemAtPosition(position).toString();
try {
if (Text.equals("All")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
listView.getChildAt(i).setVisibility(View.VISIBLE);
}
}
};
runOnUiThread(run);
}
if (Text.equals("Easy")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLevel().equals("Easy")) {
listView.getChildAt(i).setVisibility(View.VISIBLE);
}
else {
listView.getChildAt(i).setVisibility(View.GONE);
}
}
}
};
runOnUiThread(run);
}
if (Text.equals("Normal")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLevel().equals("Normal"))
listView.getChildAt(i).setVisibility(View.VISIBLE);
else {
listView.getChildAt(i).setVisibility(View.GONE);
}
dataAdapter.notifyDataSetChanged();
}
}
};
runOnUiThread(run);
}
if (Text.equals("Hard")){
Runnable run = new Runnable(){
public void run(){
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getLevel().equals("Hard"))
listView.getChildAt(i).setVisibility(View.VISIBLE);
else
listView.getChildAt(i).setVisibility(View.GONE);
}
}
};
runOnUiThread(run);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Slider slider = (Slider) cb.getTag();
slider.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(slider.getQuestion());
holder.checkbox.setChecked(slider.isSelected());
holder.checkbox.setTag(slider);
return convertView;
}
}
the best way to do this is to remove the item from the list and call dataAdapter.notifyDataSetChanged()
As you want to remove your view but keep your item inside your List I suggest you to use a different method. When the user choose a value that will cause the item to be hide just set that value to your item and then call
dataAdapter.notifyDataSetChanged();
Doing this you have to modify the logic inside your getView(), I mean if you find an item that is eligible to get hide instead of return convertView inside the getView() method of your customAdapter just return an empty view, like this you item won't be shown but it will still be in your list;)
You can use a parent Layout for Yuor item to resolve the issue:
For example:
<LinearLayout ...>
<!-- Here Your item content starts -->
<LinearLayout android:id="#+id/content">
...
</LinearLayout>
<!-- Here Your content ends -->
</LinearLayout>
Java code:
listView.getChildAt(i).getChildAt(0).setVisibility(View.GONE);
just like a filter system. Why "like", why not make it actually filterable? There are two options. Easier one is overriding toString of your slider. Other one is creating custom filter, which wouldn't use object's toString method. However, I don't remember how exactly to do second one, only that it's possible.
Slider:
String toString(){
return this.type;
}
When spinner selection changes:
adapter.getFilter().filter(selectedDifficulty);
This will automatically display items you want to see.
You shouldnt change visibility of views generated by adapter - they change every time when you scroll listview. Instead you should change the behaviour of underlying adapter.
You can try this layout instead of the ListView since there's only 4 filters:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<include
android:id="#+id/filter_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
<include
android:id="#+id/filter_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
<include
android:id="#+id/filter_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
<include
android:id="#+id/filter_4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/<your_listview_adapter>"
android:visibility="visible" />
</LinearLayout>
When you want to hide one of the filters you can just do something like:
findViewById(R.id.filter_4).setVisibility(View.GONE);
EDIT:
For instance, if you want to add information to a TextView inside the first include you just have to call the View like this:
View filter1 = findViewById(R.id.filter_1);
TextView tv1 = (TextView) filter1.findViewById(R.id.<the_id_of_the_textview);
tv1.setText("StackOverflow filter");
To prevent add another layout in outside of your layout. You just hide the item's all child views, not item itself.
For example:
if(i == 1){ // assume we need hide the first item.
//item itself
ViewGroup parent = ((ViewGroup) holder.convertView);
for (int j = 0; j < parent.getChildCount(); j++) {
parent.getChildAt(j).setVisibility(View.GONE);
}
}
And i have test this code, works fine for me.
i have been trying to swap items in a Grid view, and this is where i got:
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parent_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<GridView
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:horizontalSpacing="10dip"
android:numColumns="4"
android:verticalSpacing="10dip" />
</RelativeLayout>
main activity class:
public class MainActivity extends Activity implements OnDragListener,
OnItemLongClickListener {
ArrayList drawables;
GridView gridView;
private BaseAdapter adapter;
private int draggedIndex = -1;
private int droppedIndex = -1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawables = new ArrayList();
drawables.add(R.drawable.ic_launcher);
drawables.add(R.drawable.ic_launcher1);
drawables.add(R.drawable.ic_launcher2);
drawables.add(R.drawable.ic_launcher);
drawables.add(R.drawable.ic_launcher);
drawables.add(R.drawable.ic_launcher);
drawables.add(R.drawable.ic_launcher);
drawables.add(R.drawable.ic_launcher);
gridView = (GridView) findViewById(R.id.grid_view);
gridView.setOnItemLongClickListener(MainActivity.this);
gridView.setAdapter(adapter = new BaseAdapter() {
#Override
// Get a View that displays the data at the specified position in
// the data set.
public View getView(int position, View convertView,
ViewGroup gridView) {
// try to reuse the views.
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse
// it
if (view == null) {
view = new ImageView(MainActivity.this);
}
view.setImageResource((Integer) drawables.get(position));
view.setTag(String.valueOf(position));
return view;
}
#Override
// Get the row id associated with the specified position in the
// list.
public long getItemId(int position) {
return position;
}
#Override
// Get the data item associated with the specified position in the
// data set.
public Object getItem(int position) {
return drawables.get(position);
}
#Override
// How many items are in the data set represented by this Adapter.
public int getCount() {
return drawables.size();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onDrag(View view, DragEvent dragEvent) {
switch (dragEvent.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// Ignore this event
return true;
case DragEvent.ACTION_DRAG_ENTERED:
// Ignore this event
return true;
case DragEvent.ACTION_DRAG_EXITED:
// Ignore this event
return true;
case DragEvent.ACTION_DRAG_LOCATION:
// Ignore this event
return true;
case DragEvent.ACTION_DROP:
// Dropped inside a new view\
adapter.notifyDataSetChanged();
ImageView v2 = (ImageView)view.getParent();
final int position1 = gridView.getPositionForView(v2);
if (position1 >= 0)
{
final long droppedIndex = gridView.getAdapter().getItemId(position1);
}
Object item1 = gridView.getAdapter().getItem(draggedIndex);
Object item2 = gridView.getAdapter().getItem(droppedIndex);
drawables.remove(draggedIndex);
drawables.remove(droppedIndex);
drawables.add(droppedIndex,item1);
drawables.add(draggedIndex,item2);
draggedIndex = -1;
droppedIndex = -1;
adapter.notifyDataSetChanged();
case DragEvent.ACTION_DRAG_ENDED:
//
view.setOnDragListener(null);
return true;
}
return false;
}
#Override
public boolean onItemLongClick(AdapterView gridView, View view,
int position, long row) {
ClipData.Item item = new ClipData.Item((String) view.getTag());
ClipData clipData = new ClipData((CharSequence) view.getTag(),
new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }, item);
view.startDrag(clipData, new View.DragShadowBuilder(view), null, 0);
view.setVisibility(View.INVISIBLE);
draggedIndex = position;
return true;
}
}
my problem is in DragEvent.ACTION_DROP. I works like this:
I drag one item and, when drop it in another place, the item disappears. And that is all.
Supposedly, first retrieve both positions: the position of the item dragged (draggedIndex) and the position where the item is dropped (droppedIndex). After, i remove both items and add them to the array again in the opposite positions (the item dragged goes to droppedIndex and the other goes to the draggedIndex, so they are exchanged/swaped)
I wonder if it is a good way to do this, or if i made any mistakes trying to retrieve the dropped position (droppedIndex).
any ideas?
Before removing the item , just add the item into dropped position. Then remove the corresponding item by incrementing the dropped position by 1.
case DragEvent.ACTION_DROP:
....
drawables.add(droppedIndex,item1);
drawables.add(draggedIndex+1,item2);
drawables.remove(draggedIndex+2);
drawables.remove(droppedIndex+2);
....
hope this will help you.
I took a slightly different approach to get the dropped index. For an ACTION_DROP event, getX() and getY() return the X and Y position of the drag point at the moment of the drop, using the coordinate system of the View that received the drop (i.e. the gridview).
float dropX = event.getX();
float dropY = event.getY();
Once you have the x and y co-ordinates you can calculate the corresponding row and column in your grid view, and then use something like the following to get the index of the object in your data array (I have a 4 x 4 grid):
index = row * 4 + column;
Finally, I'm using an array list (targetDrawables) to hold the references to my gridview contents, so to reorder use:
targetDrawables.remove(draggedIndex);
targetDrawables.add(droppedIndex, draggedContents);
// Invalidate the view to force a redraw of the Grid View
imageAdapter.notifyDataSetChanged();
Your code is fine; just replace
Object item1 = gridView.getAdapter().getItem(draggedIndex);
Object item2 = gridView.getAdapter().getItem(droppedIndex);
drawables.remove(draggedIndex);
drawables.remove(droppedIndex);
drawables.add(droppedIndex,item1);
drawables.add(draggedIndex,item2);
with
Collections.swap(drawables, draggedIndex, droppedIndex);
It swaps position of list and now it works!
Is there a good tutorial or link that shows how to add different items to a listview?
For example, one with two Text lines and a Check box, another that you just press and and something would pop up. All I have now is every list item is the same two line text view and checkbox...
Or, if there is a way to add 1 row at a time with a different layout through R.layout.xxx?
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.frag_settings, container, false);
mItems = getResources().getStringArray(R.array.setting_items);
mItemDescription = getResources().getStringArray(R.array.setting_item_descriptions);
mItemListView = (ListView) mRoot.findViewById(R.id.lvMainListView);
ArrayAdapter<String> lvRowTitle = new ArrayAdapter<String>(getActivity(),
R.layout.setting_twolinetext_checkbox, R.id.tvRowTitle,
mItems);
mItemListView.setAdapter(lvRowTitle);
ArrayAdapter<String> lvRowDesc = new ArrayAdapter<String>(getActivity(),
R.layout.setting_twolinetext_checkbox, R.id.tvRowDesc,
mItemDescription);
mItemListView.setAdapter(lvRowDesc);
return mRoot;
In my example, the list activity that will display our custom list view is called OptionsActivity, because in my project this activity is going to display the different options my user can set to control my app. There are two list item types, one list item type just has a TextView and the second list item type just has a Button. You can put any widgets you like inside each list item type, but I kept this example simple.
The getItemView method checks to see which list items should be type 1 or type 2. According to my static ints I defined up top, the first 5 list items will be list item type 1, and the last 5 list items will be list item type 2. So if you compile and run this, you will have a ListView that has five items that just contain a button, and then five items that just contain a TextView.
Below is the activity code, the activity xml file, and an xml file for each list item type.
OptionsActivity.java:
public class OptionsActivity extends ListActivity {
private static final int LIST_ITEM_TYPE_1 = 0;
private static final int LIST_ITEM_TYPE_2 = 1;
private static final int LIST_ITEM_TYPE_COUNT = 2;
private static final int LIST_ITEM_COUNT = 10;
// The first five list items will be list item type 1
// and the last five will be list item type 2
private static final int LIST_ITEM_TYPE_1_COUNT = 5;
private MyCustomAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new MyCustomAdapter();
for (int i = 0; i < LIST_ITEM_COUNT; i++) {
if (i < LIST_ITEM_TYPE_1_COUNT)
mAdapter.addItem("item type 1");
else
mAdapter.addItem("item type 2");
}
setListAdapter(mAdapter);
}
private class MyCustomAdapter extends BaseAdapter {
private ArrayList<String> mData = new ArrayList<String>();
private LayoutInflater mInflater;
public MyCustomAdapter() {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
if(position < LIST_ITEM_TYPE_1_COUNT)
return LIST_ITEM_TYPE_1;
else
return LIST_ITEM_TYPE_2;
}
#Override
public int getViewTypeCount() {
return LIST_ITEM_TYPE_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch(type) {
case LIST_ITEM_TYPE_1:
convertView = mInflater.inflate(R.layout.list_item_type1, null);
holder.textView = (TextView)convertView.findViewById(R.id.list_item_type1_text_view);
break;
case LIST_ITEM_TYPE_2:
convertView = mInflater.inflate(R.layout.list_item_type2, null);
holder.textView = (TextView)convertView.findViewById(R.id.list_item_type2_button);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
public static class ViewHolder {
public TextView textView;
}
}
activity_options.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ListView
android:id="#+id/optionsList"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
list_item_type_1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_item_type1_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/list_item_type1_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text goes here" />
</LinearLayout>
list_item_type2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_item_type2_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/list_item_type2_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button text goes here" />
</LinearLayout>
You have two possibilities to do that:
Create a Type and check for your type and return the view related to this type.
BaseAdapter has two methods to check different items in it, getItemViewType(int position) and getViewTypeCount(). Do your stuff there.
Check this tutorial:
ListView with multiple rows
You should create your own class extending BaseAdapter. I recommend watching The World of ListView, it will help you understand everything you need to know about working with ListView.
In addition to #LouMorda answer, I'd use some class, with fields that contains info about item and list item type:
public class Item {
private int itemViewType;
private Object tag;
private String title;
public Item(int itemViewType){
this.itemViewType = itemViewType;
}
public int getItemViewType() {
return itemViewType;
}
public void setItemViewType(int itemViewType) {
this.itemViewType = itemViewType;
}
...
}
So using this object gives more flexibility when adding items to the list in different sequences:
public class OptionsActivity extends ListActivity {
private static final int LIST_ITEM_TYPE_1 = 0;
private static final int LIST_ITEM_TYPE_2 = 1;
private ArrayList<String> mItemsSource = new ArrayList<>();
...
#Override
public int getItemViewType(int position) {
return mItemsSource.get(position).getItemViewType();
}
...
}
How to change an image in my specific gridview as I get the below error. I have followed similar examples elsewhere without success. ie I get "cannot change from integer to imageview" when trying the below, from
(see Android GridView - update View based on position), i.e.:
int tempid = v.getId();
ImageView imgView = FruitToChooseFromImages.get(tempid);
imgView.setBackgroundResource(R.drawable.blank);
I have also tried:
{ // remove viewable image / make blank
ImageView imageView = (ImageView) v;
imageView.setImageResource(R.drawable.blank);
}
FULL CODE BELOW IF YOU NEED IT:
Main JAVA code:
public class game1mainscreen extends Activity {
private MyGridviewAdapter1 mAdapter;
private GridView gridview;
private ArrayList<Integer> FruitToChooseFromImages;
private ArrayList<Integer> tempintarray;
int Totalfruit = 11; // starting from 0 of course (so an 11=12 fruit) this means there are 6 pairs of fruit to select
int fruitleft = 12;
int fruitstilltoadd = Totalfruit + 1;
int numberOfFruitToRemove = 6;
int puthere = 0;
int imagesSelectedThusFar = 0;
int Fruitleft = 0;
int firstfruitselected = R.drawable.blank; int firstfruitselpos;
int secondfruitselected = R.drawable.blank; int secondfruitselpos;
int removefirstimage = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameonemenu);
{
FruitToChooseFromImages = new ArrayList<Integer>();
FruitToChooseFromImages.add(R.drawable.fruit0);
.....etc....
FruitToChooseFromImages.add(R.drawable.fruit11);
}
...code removed which randomly sorts FruitToChooseFromImages (ie arraylist of images) into 6 duplicate pairs of images...
// prepared arraylist is passed to the Adapter class
mAdapter = new MyGridviewAdapter1(this, FruitToChooseFromImages);
// Set custom adapter to gridview
gridview = (GridView) findViewById(R.id.gridView1);
gridview.setAdapter(mAdapter);
// DO THIS WHEN CLICKED
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
int fruitselected = (int)FruitToChooseFromImages.get(position);
// start
if (fruitselected == R.drawable.blank)
{
// if blank/empty icon clicked on then DO NOTHING
}
else
{ // firstly, say fruit name
int soundtoplaynow = getrightsound(position, fruitselected);
SoundManager.playSound(soundtoplaynow, 1);
// next
if (imagesSelectedThusFar == 0)
{
imagesSelectedThusFar = 1;
firstfruitselected = fruitselected; firstfruitselpos = position;
//both switch fruit image to blank in the array and display blank at position clicked
FruitToChooseFromImages.set(position, R.drawable.blank);
{ // remove viewable image / make blank
ImageView imageView = (ImageView) v;
imageView.setImageResource(R.drawable.blank);
}
}
else // so two images have been selected! do they match?
{
imagesSelectedThusFar = 0; // has reached 2, so reset to zero
secondfruitselected = fruitselected; secondfruitselpos = position;
if (firstfruitselected == secondfruitselected)
{
GeneralSoundManager.playSound(0, 1);// play happy sound - change code to GeneralSoundManager
//switch fruit image to blank and display blank at position clicked **
FruitToChooseFromImages.set (position, R.drawable.blank);
{ // remove viewable image / make blank
ImageView imageView = (ImageView) v;
imageView.setImageResource(R.drawable.blank);
}
int tempid = v.getId();
ImageView imgView = FruitToChooseFromImages.get(tempid);
imgView.setBackgroundResource(R.drawable.blank);
fruitleft = (fruitleft - 2);
}
else
{ // you selected the wrong fruit, sorry.
GeneralSoundManager.playSound(1, 1);
FruitToChooseFromImages.set (firstfruitselpos, firstfruitselected);
//
}
}
}
// end
if (fruitleft == 0)
{
//end game - add code here
}
}
});
}
// returns the sound to play depending on what image was clicked on
public int getrightsound(Integer position, Integer switchused) {
...etc....
return soundtoplay;
}
}
My gridview adapter code:
public class MyGridviewAdapter1 extends BaseAdapter
{
private ArrayList<Integer> FruitToChooseFromImages;
private Activity activity;
public MyGridviewAdapter1(Activity activity,ArrayList<Integer> FruitToChooseFromImages)
{
super();
this.FruitToChooseFromImages = FruitToChooseFromImages;
this.activity = activity;
}
public int getCount() {
return FruitToChooseFromImages.size();
}
public Integer getItem(int position) {
return FruitToChooseFromImages.get(position);
}
public long getItemId(int position) {
return 0;
}
public static class ViewHolder
{
public ImageView imgViewFlag;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.gridview_row, null);
view.imgViewFlag = (ImageView) convertView.findViewById(R.id.imageView1);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.imgViewFlag.setImageResource(FruitToChooseFromImages.get(position));
return convertView;
}
}
My Main xml code - gameonemenu:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"
android:layout_gravity="center"
android:background="#drawable/tree">
<GridView
android:id="#+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="4"
android:verticalSpacing="1dp"
android:horizontalSpacing="1dp"
android:stretchMode="columnWidth"
android:gravity="center" />
</LinearLayout>
My Grirdview_row xml code:
<ImageView
android:layout_height="64dp"
android:id="#+id/imageView1"
android:layout_width="64dp"
android:src="#drawable/blank"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
</RelativeLayout>
PS I used Grirdview_row xml which originally showed text but I don't need to display text only images but is this causing an issue?
PSS please keep your advice at the COMPLETE beginner level and include code if possible to match explanation. I cannot stress this enough. Thanks.