I'm working on a quiz app where there is one question and five radio buttons per CardView in a RecyclerView. Each radio button has an assigned score.
For Example, there are two CardViews
CardView #1
radio_button_1 = -20
radio_button_2 = -10
radio_button_3 = 0
radio_button_4 = 10
radio_button_5 = 20
CardView #2
radio_button_1 = -20
radio_button_2 = -10
radio_button_3 = 0
radio_button_4 = 10
radio_button_5 = 20
Say user picks radio_button_1 on CardView #1 and he picks radio_button_3 on CardView #2 and so forth. I want to add the points between CardViews and be able to preserve/ save those points as user scrolls through the CardViews. I don't know how it works with RecyclerView. SharedPreferences?
I have added a text view to test and see if the score is being updated in the background with the new score.
Recycler Adapter:
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
private List<App> mApps;
public static int score;
public static int updateScore() {
return score;
}
public MainAdapter(List<App> apps) {
mApps = apps;
}
#Override
public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_adapter, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public int getItemViewType(int position) {
return (position);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
App app = mApps.get(position);
holder.questionTextView.setText(app.getQuestion());
}
#Override
public int getItemCount() {
return mApps.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView questionTextView;
private TextView titleTextView;
public RadioGroup radioGroup;
public RadioButton rb1, rb2, rb3, rb4, rb5;
public ViewHolder(View itemView) {
super(itemView);
radioGroup = itemView.findViewById(R.id.radio_group);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int selectedValue = 0;
switch (checkedId) {
case R.id.radio_button_1:
selectedValue -= 20;
break;
case R.id.radio_button_2:
selectedValue -= 10;
break;
case R.id.radio_button_3:
selectedValue += 0;
break;
case R.id.radio_button_4:
selectedValue += 10;
break;
case R.id.radio_button_5:
selectedValue += 20;
break;
}
updateValue (selectedValue);
}
public int updateValue(int selectedValue) {
/**Only to test if value is being tallied**/
TextView valueView = titleTextView.findViewById(R.id.title);
valueView.setText(String.valueOf(selectedValue));
return selectedValue;
}
});
questionTextView = itemView.findViewById(R.id.question);
titleTextView = itemView.findViewById(R.id.title);
rb1 = itemView.findViewById(R.id.radio_button_1);
rb2 = itemView.findViewById(R.id.radio_button_2);
rb3 = itemView.findViewById(R.id.radio_button_3);
rb4 = itemView.findViewById(R.id.radio_button_4);
rb5 = itemView.findViewById(R.id.radio_button_5);
}
#Override
public void onClick(View v) {
Log.d("App", mApps.get(getAdapterPosition()).getQuestion());
}
}}
MainActivity:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(mRecyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
setupMainAdapter();
}
private void setupMainAdapter() {
List<App> apps = getApps();
MainAdapter adapter = new MainAdapter(apps);
mRecyclerView.setAdapter(adapter);
}
private List<App> getApps() {
List<App> apps = new ArrayList<>();
apps.add(new App((getResources().getString(R.string.question_1))));
apps.add(new App((getResources().getString(R.string.question_2))));
apps.add(new App((getResources().getString(R.string.question_3))));
apps.add(new App((getResources().getString(R.string.question_4))));
apps.add(new App((getResources().getString(R.string.question_5))));
apps.add(new App((getResources().getString(R.string.question_6))));
apps.add(new App((getResources().getString(R.string.question_7))));
apps.add(new App((getResources().getString(R.string.question_8))));
apps.add(new App((getResources().getString(R.string.question_9))));
apps.add(new App((getResources().getString(R.string.question_10))));
return apps;
}
}
CardView XML
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="275dp"
android:layout_height="575dp"
android:layout_margin="16dp"
card_view:cardBackgroundColor="#color/colorAccent"
card_view:cardCornerRadius="0dp"
card_view:cardElevation="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:fontFamily="#font/futura_medium"
android:padding="24dp"
android:textColor="#000000"
android:textSize="32sp"
tools:text="#string/title" />
<TextView
android:id="#+id/question"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_centerHorizontal="true"
android:fontFamily="#font/futura_medium"
android:textColor="#000000"
android:textSize="18sp"
tools:text="#string/question" />
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/question"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="16dp"
android:orientation="horizontal">
<RadioButton
android:id="#+id/radio_button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimaryDark"
android:text="-2"
android:textColor="#000000" />
<RadioButton
android:id="#+id/radio_button_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimaryDark"
android:text="-1"
android:textColor="#000000" />
<RadioButton
android:id="#+id/radio_button_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimaryDark"
android:text="0"
android:textColor="#000000" />
<RadioButton
android:id="#+id/radio_button_4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimaryDark"
android:text="1"
android:textColor="#000000" />
<RadioButton
android:id="#+id/radio_button_5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimaryDark"
android:text="2"
android:textColor="#000000" />
</RadioGroup>
<com.google.android.material.button.MaterialButton
android:id="#+id/submit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_margin="16dp"
android:layout_marginBottom="32dp"
android:fontFamily="#font/futura_medium"
android:text="#string/submit"
android:textColor="#color/colorAccent"
android:textSize="16sp"
app:backgroundTint="#color/colorPrimaryDark"
app:rippleColor="#color/colorPrimary" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
You can declare an interface inside MainAdapter, lets call it ScoreUpdatesListener. It has one method that will be called whenever you want to update the textView.
You will need to implement that interface in your MainActivity, you may do it anonymously, or have the class itself implements that interface. like class MainActivity implements MainAdapter.ScoreUpdatesListener {}.
Either way, you need to pass that interface implementation to the adapter and save its reference. You may do it in the constructor, or add a set method to the adapter.
Now, when updating viewHolder's value, call that listener and it will update the textView from the activity.
class MainAdaptaer {
private ScoreUpdates listener;
...
class ViewHolder... {
...
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int selectedValue = 0;
switch (checkedId) {
case R.id.radio_button_1:
selectedValue -= 20;
break;
case R.id.radio_button_2:
selectedValue -= 10;
break;
case R.id.radio_button_3:
selectedValue += 0;
break;
case R.id.radio_button_4:
selectedValue += 10;
break;
case R.id.radio_button_5:
selectedValue += 20;
break;
}
score += selectedValue;
// score is an existing attribute of MainAdapter
// it can and should be non static attribute
listener.updateScore(score);
}
}
interface ScoreUpdatesListener {
void onScoreUpdate(int score);
}
}
In your activity:
private void setupMainAdapter() {
List<App> apps = getApps();
MainAdapter adapter = new MainAdapter(apps, new MainAdapter.ScoreUpdatesListener() {
#Override
public void onScoreUpdate(int score) {
TextView valueView = titleTextView.findViewById(R.id.title);
valueView.setText(String.valueOf(score));
}
});
mRecyclerView.setAdapter(adapter);
}
If the class itself implemented the interface, just pass this to the adapter.
You don't have to move the TextView handling to the activity, but you should. The adapter shouldn't mess with views that isn't ViewHolders
Related
When I add an item by button Scan Now, the public double sumCost value incrementes by the cost value in the AddItem method and then TextView(android:id="#+id/SumText") assigns this value. And How to decrease sumCost by the number that is in cost and set new text in TextView when pressing the Delete button? Thanks for any help
enter image description here
My full code:
MainActivity:
package com.example.testfirst;
...
public class MainActivity extends AppCompatActivity {
TextView sumText;
Button buttonAdd;
List<Contact> contacts = new LinkedList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
buttonAdd = (Button) findViewById(R.id.scanBtn);
sumText = (TextView) findViewById(R.id.SumText);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddItem("Tom", 2.45);
sumText.setText(Double.toString(sumCost));
}
});
}
public void AddItem(String name, double cost){
sumCost += cost;
RecyclerView rvContacts = (RecyclerView) findViewById(R.id.recyclerView);
ContactsAdapter adapter = new ContactsAdapter(contacts);
rvContacts.setAdapter(adapter);
rvContacts.setLayoutManager(new LinearLayoutManager(this));
contacts.add(new Contact(name,Double.toString(cost)));
}
public double sumCost = 0;
}
Contact(Model class):
...
public class Contact {
private String mName;
private String mCost;
public Contact(String name, String cost) {
mName = name;
mCost = cost;
}
public String getName() {
return mName;
}
public String getCost() {
return mCost;
}
}
ContactsAdapter:
...
public class ContactsAdapter extends RecyclerView.Adapter<ViewHolder>{
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.item_contact, parent, false);
return new ViewHolder(contactView).linkAdapter(this);
}
///////////////
#NonNull
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Contact contact = mContacts.get(position);
TextView textViewId = holder.nameId;
textViewId.setText(contact.getName());
TextView textViewCost = holder.nameCost;
textViewCost.setText(contact.getCost());
}
#Override
public int getItemCount() {
return mContacts.size();
}
List<Contact> mContacts;
public ContactsAdapter(List<Contact> contacts) {
mContacts = contacts;
}
}
class ViewHolder extends RecyclerView.ViewHolder {
private ContactsAdapter adapter;
public TextView nameId;
public TextView nameCost;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nameId = (TextView) itemView.findViewById(R.id.text);
nameCost = (TextView) itemView.findViewById(R.id.textCost);
itemView.findViewById(R.id.delete).setOnClickListener(view -> {
adapter.mContacts.remove(getAdapterPosition());
adapter.notifyItemRemoved(getAdapterPosition());
});
}
public ViewHolder linkAdapter(ContactsAdapter adapter){
this.adapter = adapter;
return this;
}
}
item_contact.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp"
app:cardCornerRadius="10dp"
app:cardElevation="5dp"
app:contentPadding="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="#string/app_name"
android:textSize="20sp" />
<TextView
android:id="#+id/textCost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text"
android:text="#string/app_name"
android:textSize="20sp" />
<Button
android:id="#+id/delete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="3dp"
android:layout_marginEnd="3dp"
android:text="Delete" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
activity_users.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<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"
tools:context=".MainActivity"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/SumText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="0.00"
android:textSize="30sp"/>
<Button
android:id="#+id/scanBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scan now"
android:textSize="30sp"
android:layout_gravity="center_horizontal"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
One easy way to do that would be do add a "Decrementer" interface in the adapter that it can call to decrement the total cost, like this:
// Define the interface
public interface Decrementer {
void onDelete(double cost);
}
// Define an instance of the interface to hold
private final Decrementer mDecrementer;
// Pass in a decrementer at construction
public ContactsAdapter(List<Contact> contacts, Decrementer decr) {
mContacts = contacts;
mDecrementer = decr;
}
#NonNull
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// get views and such ...
// Call the decrementer method when the button is clicked
// Could set this in onBindViewHolder, or pass the decrementer
// into the ViewHolder itself and use it there.
deleteButton.setOnClickListener(view -> {
int pos = holder.getAdapterPosition();
Contact c = mContacts.get(pos);
// add getCostAmount to return a double, or better yet, just
// store it as a Double instead of a string in Contact
mDecrementer.onDelete(c.getCostAmount());
mContacts.remove(pos);
notifyItemRemoved(pos);
});
}
and you would define the Decrementer when you create the adapter so it can access the Activity class members, like this:
ContactsAdapter adapter = new ContactsAdapter(contacts, new ContactsAdapter.Decrementer() {
#Override
public void onDelete(double cost) {
sumCost -= cost;
// change activity TextViews and such here too
sumText.setText(Double.toString(sumCost));
}
});
Side note: you don't need to create a whole new adapter every time you add an item, just add it to the contacts array and call an appropriate notifyDataSetChanged method on the existing adapter.
private ContactsAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
//...
RecyclerView rvContacts = (RecyclerView) findViewById(R.id.recyclerView);
ContactsAdapter adapter = new ContactsAdapter(contacts);
rvContacts.setAdapter(adapter);
rvContacts.setLayoutManager(new LinearLayoutManager(this));
}
public void AddItem(String name, double cost){
sumCost += cost;
contacts.add(new Contact(name,Double.toString(cost)));
adapter.notifyDataSetChanged(); // or a less expensive notify call
}
I am still learning android. Here I need help to toggle between Play and Pause source in ImageButton in the ListView.
There should be only one song in Play state at a time. So if clicked other should stop.
SongAdapter.java
public class SongAdapter extends ArrayAdapter<Song> {
public SongAdapter(#NonNull Context context, int resource, #NonNull List<Song> objects) {
super(context, resource, objects);
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View playlistItemView = convertView;
if (playlistItemView == null) {
playlistItemView = LayoutInflater.from(getContext()).inflate(R.layout.playlist_item, parent, false);
}
Song currentSong = getItem(position);
// get list item elements
ImageView albumCoverThumbnail = playlistItemView.findViewById(R.id.playlist_album_thumbnail);
TextView songTitle = playlistItemView.findViewById(R.id.playlist_song_title);
TextView songAlbumTitle = playlistItemView.findViewById(R.id.playlist_song_album_title);
TextView songArtist = playlistItemView.findViewById(R.id.playlist_song_artist);
final ImageButton songPlayButton = playlistItemView.findViewById(R.id.playlist_play_button);
// set data to the list item
assert currentSong != null;
albumCoverThumbnail.setImageResource(currentSong.getSongAlbumCoverId());
songTitle.setText(currentSong.getSongTitle());
songAlbumTitle.setText(currentSong.getSongAlbumTitle());
songArtist.setText(currentSong.getSongSingers());
// set song button action
songPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
Toast.makeText(getContext(), "Button clicked for item " + position, Toast.LENGTH_LONG).show();
}
});
return playlistItemView;
}
}
Song.java
public class Song {
private String songAlbumTitle;
private String songTitle;
private String songSingers;
private int songAlbumCoverId;
public Song(String albumTitle, String title, String singers, int albumCoverId) {
songAlbumTitle = albumTitle;
songTitle = title;
songSingers = singers;
songAlbumCoverId = albumCoverId;
}
public String getSongAlbumTitle() {
return songAlbumTitle;
}
public String getSongTitle() {
return songTitle;
}
public String getSongSingers() {
return songSingers;
}
public int getSongAlbumCoverId() {
return songAlbumCoverId;
}
}
Activity.java
public class DreamVoyage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dream_voyage);
// get view ids
ImageView albumCoverImage = findViewById(R.id.album_cover);
// get intent extras
Bundle bundle = getIntent().getExtras();
// check if bundle in not null and containing value
if (bundle != null) {
String albumTitle = bundle.getString("album_one_title");
String albumBand = bundle.getString("album_one_band");
int albumCover = bundle.getInt("album_one_cover");
albumCoverImage.setImageResource(albumCover);
TextView albumTitleText = findViewById(R.id.album_title);
TextView albumBandText = findViewById(R.id.album_band);
albumTitleText.setText(albumTitle);
albumBandText.setText(albumBand);
ArrayList<Song> songs = new ArrayList<Song>();
songs.add(new Song(albumTitle, "I do it for you", "Bryn Adams", albumCover));
songs.add(new Song(albumTitle, "Here I am", "Bryn Adams", albumCover));
SongAdapter songAdapter = new SongAdapter(this, 0, songs);
ListView listView = findViewById(R.id.playlist_view);
listView.setAdapter(songAdapter);
}
}
}
playlist_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:background="#drawable/border_bottom"
android:orientation="horizontal">
<ImageView
android:id="#+id/playlist_album_thumbnail"
android:layout_width="32dp"
android:layout_height="32dp"
android:src="#drawable/album_three"
android:scaleType="centerCrop"
android:contentDescription="#string/album_thumbnail_desc"/>
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/playlist_song_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mon voyage de rêve"
android:layout_marginLeft="8dp"
android:textColor="#000000"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<TextView
android:id="#+id/playlist_song_album_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dream Voyage"
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toStartOf="#id/playlist_song_title"/>
<TextView
android:id="#+id/playlist_song_credit_separator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" - "
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toEndOf="#id/playlist_song_album_title"/>
<TextView
android:id="#+id/playlist_song_artist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" - John Doen, Jane Doe"
android:textSize="10sp"
android:textColor="#666666"
app:layout_constraintTop_toBottomOf="#+id/playlist_song_title"
app:layout_constraintStart_toEndOf="#id/playlist_song_credit_separator"/>
</android.support.constraint.ConstraintLayout>
<ImageButton
android:id="#+id/playlist_play_button"
android:layout_width="24dp"
android:layout_height="24dp"
android:padding="0dp"
android:layout_gravity="center_vertical"
android:background="#00FFFFFF"
android:src="#drawable/ic_play_arrow_black_24dp"
android:scaleType="centerCrop"/>
</LinearLayout>
Use a variable to store current playing items index
SongAdapter {
int playingIndex = -1 //-1 means no song is playing
.
.
.
}
Set play/pause drawable based on playingIndex and set the playingIndex in the songPlayButton.setOnClickListener
public View getView(final int position, ...) {
if(playingIndex == position)
songPlayButton.setImageResource(R.drawable.ic_play_black_24dp);
else
songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
songPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position == playIndex)
playIndex = -1;
else
playIndex = position;
notifyDataSetChanged();
}
});
}
It should get the job done. But it forces a redraw of all rows. In RecyclerView there is the notifyItemChanged method which can force redraw on single item.
You may try using the method here to update single row https://stackoverflow.com/a/3727813/4907678
My suggestion is migrating to RecyclerView and using notifyItemChanged.
cheers!
I'm trying to show an additional CardView that contains a different layout but have got lost with my code. I'm also unsure of how to to show the array of strings within a GridView for the CardView itself. Does anyone know where I may have gone wrong & what can be done so that the following can be achieved?:
Place the CardView containing the GridView wherever I want within the RecyclerView.
Show the array of strings in a GridView within a CardView
What I want to add to the RecyclerView (above the Item A CardView)
RecyclerView current contents
Fragment class
public class MyFragment extends android.support.v4.app.Fragment {
private MonRecyclerAdapterWithGrid adapterG;
static final String[] frenchVowels = new String[]{
"a", "e", "i", "o", "u", "y"
};
public MyFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_rv, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
View v = getView();
assert v != null;
recyclerView = v.findViewById(R.id.my_recyclerview);
linearLayoutManager = new LinearLayoutManager(getActivity());
MyRecyclerAdapter adapter = new MyRecyclerAdapter(getContext(), getHeader(), getListItemsG(), getListItemsT());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
super.onActivityCreated(savedInstanceState);
}
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
public RecyclerViewHeader getHeader()
{
return new RecyclerViewHeader();
}
public List<RecyclerViewItemGV> getListItemsG() {
List<RecyclerViewItemGV> rvItemsG = new ArrayList<>();
RecyclerViewItemGV itemG = new RecyclerViewItemGV();
itemG.setTitleGV("Item A");
itemG.setVowelsGV(adapterG);
for (String fVowels : frenchVowels) {
// ?????? Still not working :-(
adapterG.addAdapterItem(new MyFragment.AdapterItem(frenchVowels));
}
rvItemsG.add(itemG);
return rvItemsG;
}
public List<RecyclerViewItemTV> getListItemsT()
{
List<RecyclerViewItemTV> rvItemsT = new ArrayList<>();
RecyclerViewItemTV itemA = new RecyclerViewItemTV();
itemA.setTitleTV("Item A");
itemA.setDescriptionTV("Feature A1");
rvItemsT.add(itemA);
RecyclerViewItemTV itemB = new RecyclerViewItemTV();
itemB.setTitleTV("Item B");
itemB.setDescriptionTV("Feature B1\nFeature B2");
rvItemsT.add(itemB);
RecyclerViewItemTV itemC = new RecyclerViewItemTV();
itemC.setTitleTV("Item C");
itemC.setDescriptionTV("Feature C1\nFeature C2\nFeature C3");
rvItemsT.add(itemC);
return rvItemsT;
}
}
RecyclerView adapter class
public class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEMG = 1;
private static final int TYPE_ITEMT = 2;
private Context mContext;
RecyclerViewHeader header;
List<RecyclerViewItemGV> listItemsG;
List<RecyclerViewItemTV> listItemsT;
ValueAnimator mAnimator;
public MyRecyclerAdapter(Context context, RecyclerViewHeader header, List<RecyclerViewItemGV> listItemsG, List<RecyclerViewItemTV> listItemsT)
{
this.mContext = context;
this.header = header;
this.listItemsG = listItemsG;
this.listItemsT = listItemsT;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_HEADER)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_header_expandcollapsebuttons, parent, false);
return new MyRecyclerAdapter.VHHeader(v);
}
else if(viewType == TYPE_ITEMG)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_gv, parent, false);
return new MyRecyclerAdapter.VHItemG(v);
}
else if(viewType == TYPE_ITEMT)
{
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_tv, parent, false);
return new MyRecyclerAdapter.VHItemT(v);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
private RecyclerViewItemGV getItemG(int position)
{
return listItemsG.get(position);
}
private RecyclerViewItemTV getItemT(int position)
{
return listItemsT.get(position);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Typeface iconFont = FontManager.getTypeface(mContext, FontManager.FONTAWESOME);
if (holder instanceof MyRecyclerAdapter.VHHeader)
{
final MyRecyclerAdapter.VHHeader vhHeader = (MyRecyclerAdapter.VHHeader)holder;
}
else if (holder instanceof MyRecyclerAdapter.VHItemG){
RecyclerViewItemGV currentItemG = getItemG(position-1);
final MonRecyclerAdapterWithGrid.VHItemG vhItemG = (MyRecyclerAdapter.VHItemG)holder;
vhItemG.txtAG.setText(currentItemG.getTitleGV());
vhItemG.mGridViewG.setVisibility(View.GONE);
vhItemG.txtExpandCollapseG.setText(R.string.fa_icon_chevron_down);
vhItemG.txtExpandCollapseG.setTypeface(iconFont);
//Add onPreDrawListener
vhItemG.mGridViewG.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
vhItemG.mGridViewG.getViewTreeObserver().removeOnPreDrawListener(this);
vhItemG.mGridViewG.setVisibility(View.GONE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
vhItemG.mGridViewG.measure(widthSpec, heightSpec);
vhItemG.mGridViewHeight = vhItemG.mGridViewG.getMeasuredHeight();
return true;
}
});
vhItemG.mCardViewG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(vhItemG.mGridViewG.getVisibility() == View.GONE){
vhItemG.expandG();
} else {
vhItemG.collapseG();
}
}
});
}
else if (holder instanceof MyRecyclerAdapter.VHItemT)
{
RecyclerViewItemTV currentItem = getItemT(position-2);
final MyRecyclerAdapter.VHItemT vhItemT = (MyRecyclerAdapter.VHItemT)holder;
vhItemT.txtA.setText(currentItem.getTitleTV());
vhItemT.txtB.setText(currentItem.getDescriptionTV());
vhItemT.txtB.setVisibility(View.GONE);
vhItemT.txtExpandCollapse.setText(R.string.fa_icon_chevron_down);
vhItemT.txtExpandCollapse.setTypeface(iconFont);
//Add onPreDrawListener
vhItemT.txtB.getViewTreeObserver().addOnPreDrawListener(
new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
vhItemT.txtB.getViewTreeObserver().removeOnPreDrawListener(this);
vhItemT.txtB.setVisibility(View.GONE);
final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
vhItemT.txtB.measure(widthSpec, heightSpec);
vhItemT.textBHeight = vhItemT.txtB.getMeasuredHeight();
return true;
}
});
vhItemT.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(vhItemT.txtB.getVisibility() == View.GONE){
vhItemT.expandT();
} else {
vhItemT.collapseT();
}
}
});
}
}
// need to override this method
#Override
public int getItemViewType(int position) {
if(isPositionHeader(position))
return TYPE_HEADER;
return TYPE_ITEMG;
return TYPE_ITEMT;
}
private boolean isPositionHeader(int position)
{
return position == 0;
}
#Override
public int getItemCount() {
return listItemsG.size()+1;
return listItemsT.size()+1;
}
class VHHeader extends RecyclerView.ViewHolder{
Button btnCollapseAll, btnExpandAll;
public VHHeader(View headerView) {
super(headerView);
this.btnCollapseAll = headerView.findViewById(R.id.btn_collapseall);
this.btnExpandAll = headerView.findViewById(R.id.btn_expandall);
}
}
public class VHItemG extends RecyclerView.ViewHolder{
CardView mCardViewG;
LinearLayout mLinearLayoutG;
RelativeLayout mRelativeLayoutG;
RecyclerView mRecyclerViewG;
GridView mGridViewG;
TextView txtExpandCollapseG, txtAG;
public int mGridViewHeight;
public VHItemG(View itemView) {
super(itemView);
this.mCardViewG = itemView.findViewById(R.id.cv_gv);
this.mLinearLayoutG = itemView.findViewById(R.id.linearlayout_gv_titlerow);
this.mRelativeLayoutG = itemView.findViewById(R.id.relativelayout_gv);
this.mRecyclerViewG = itemView.findViewById(R.id.my_recyclerview);
this.txtAG = itemView.findViewById(R.id.tv_gv_A);
this.txtExpandCollapseG = itemView.findViewById(R.id.tv_gv_expandcollapse);
this.mGridViewG = itemView.findViewById(R.id.gv_a);
}
private void expandG() {
// change visibility to 'VISIBLE'
mGridViewG.setVisibility(View.VISIBLE);
// change direction of chevron to 'up'
txtExpandCollapseG.setText(R.string.fa_icon_chevron_up);
// apply animation to the height of 'txtB'
mAnimator = slideAnimator(0, mGridViewHeight);
// start the animation
mAnimator.start();
}
private void collapseG() {
// change direction of chevron to 'down'
txtExpandCollapseG.setText(R.string.fa_icon_chevron_down);
int finalHeight = mGridViewG.getHeight();
ValueAnimator mAnimator = slideAnimator(finalHeight, 0);
mAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animator) {
// Height will be 0, but set visibility to 'GONE'
mGridViewG.setVisibility(View.GONE);
}
#Override
public void onAnimationStart(Animator animator) {
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
mAnimator.start();
}
public ValueAnimator slideAnimator(int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
// update height
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = mGridViewG.getLayoutParams();
layoutParams.height = value;
mGridViewG.setLayoutParams(layoutParams);
}
});
return animator;
}
}
public class VHItemT extends RecyclerView.ViewHolder{
CardView cardView;
LinearLayout mLinearLayout;
RecyclerView mRecyclerView;
RelativeLayout mRelativeLayout;
TextView txtExpandCollapse, txtA, txtB;
public int textBHeight;
public VHItemT(View itemView) {
super(itemView);
this.cardView = itemView.findViewById(R.id.linearlayout_tv_main);
this.mLinearLayout = itemView.findViewById(R.id.linearlayout_tv_titlerow);
this.mRelativeLayout = itemView.findViewById(R.id.relativelayout_tv);
this.mRecyclerView = itemView.findViewById(R.id.my_recyclerview);
this.txtExpandCollapse = itemView.findViewById(R.id.tv_tv_expandcollapse);
this.txtA = itemView.findViewById(R.id.tv_tv_A);
this.txtB = itemView.findViewById(R.id.tv_tv_B);
}
private void expandT() {
// change visibility to 'VISIBLE'
txtB.setVisibility(View.VISIBLE);
// change direction of chevron to 'up'
txtExpandCollapse.setText(R.string.fa_icon_chevron_up);
// apply animation to the height of 'txtB'
mAnimator = slideAnimator(0, textBHeight);
// start the animation
mAnimator.start();
}
private void collapseT() {
// change direction of chevron to 'down'
txtExpandCollapse.setText(R.string.fa_icon_chevron_down);
int finalHeight = txtB.getHeight();
ValueAnimator mAnimator = slideAnimator(finalHeight, 0);
mAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationEnd(Animator animator) {
// Height will be 0, but set visibility to 'GONE'
txtB.setVisibility(View.GONE);
}
#Override
public void onAnimationStart(Animator animator) {
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
}
});
mAnimator.start();
}
public ValueAnimator slideAnimator(int start, int end) {
ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
// update height
int value = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = txtB.getLayoutParams();
layoutParams.height = value;
txtB.setLayoutParams(layoutParams);
}
});
return animator;
}
}
}
GridView adapter (currently excluded from project)
private class MyGVAdapter extends ArrayAdapter<AdapterItem> {
private List<AdapterItem> items = new ArrayList<>();
MyGVAdapter(Context context, int textviewid) {
super(context, textviewid);
}
void addAdapterItem(MyGVFragment.AdapterItem item) {
items.add(item);
}
#Override
public int getCount() {
return items.size();
}
#Override
public MyGVFragment.AdapterItem getItem(int position) {
return ((null != items) ? items.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull final ViewGroup parent) {
View rowView;
if (convertView == null) {
rowView = getActivity().getLayoutInflater().inflate(R.layout.gridview_item, parent, false);
} else {
rowView = convertView;
}
TextView tv = rowView.findViewById(R.id.item_gridview);
tv.setText(items.get(position).first);
return rowView;
}
}
class AdapterItem {
String first;
AdapterItem(String first) {
this.first = first;
}
}
}
gridview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/item_gridview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="0dp"
android:paddingEnd="10dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="?android:attr/textColorPrimary"
/>
</LinearLayout>
CardView with GridView (recyclerview_item_gv)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:id="#+id/cv_gv"
android:layout_marginBottom="20dp"
>
<LinearLayout
android:id="#+id/lineralayout_gv_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:animateLayoutChanges="true">
<LinearLayout
android:id="#+id/linearlayout_gv_titlerow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="2dp"
android:weightSum="100">
<TextView
android:id="#+id/tv_gv_A"
android:layout_weight="90"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="?android:attr/textColorPrimary"
style="#android:style/TextAppearance.Medium" />
<TextView
android:id="#+id/tv_gv_expandcollapse"
android:importantForAccessibility="no"
android:clickable="true"
android:focusable="true"
android:layout_weight="10"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textColor="?android:attr/textColorPrimary"
style="#android:style/TextAppearance.Large" />
</LinearLayout>
<RelativeLayout
android:id="#+id/relativelayout_gv"
android:animateLayoutChanges="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<GridView
android:id="#+id/gv_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnWidth="100dp"
android:numColumns="auto_fit"
android:layout_marginBottom="20dp"
android:stretchMode="columnWidth" />
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
CardView with TextView (recyclerview_item_tv.xml)
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:id="#+id/cv_tv"
android:layout_marginBottom="20dp">
<LinearLayout
android:id="#+id/linearlayout_gv_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
android:animateLayoutChanges="true">
<LinearLayout
android:id="#+id/linearlayout_tv_titlerow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginBottom="2dp"
android:weightSum="100">
<TextView
android:id="#+id/tv_tv_A"
android:layout_weight="90"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="?android:attr/textColorPrimary"
style="#android:style/TextAppearance.Medium" />
<TextView
android:id="#+id/tv_tv_expandcollapse"
android:importantForAccessibility="no"
android:clickable="true"
android:focusable="true"
android:layout_weight="10"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textColor="?android:attr/textColorPrimary"
style="#android:style/TextAppearance.Large" />
</LinearLayout>
<RelativeLayout
android:id="#+id/relativelayout_tv"
android:animateLayoutChanges="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tv_B"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?android:attr/textColorPrimary"
style="#android:style/TextAppearance.Large" />
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Ok so I made a quick example of how to do it. This is how the Activity class I'm posting looks like, all items are in the same RecyclerView:
Bear in mind, it might not look like your code because I am trying to use (At least for me) best practices, and also shorten the amount of code and classes by containing a lot of things in the same class.
Here is the Activity:
public class RecyclerActivity extends AppCompatActivity {
RecyclerView recycler;
ArrayList<String> data;
RecyclerView.Adapter<ViewHolder> adapter;
private static final int ITEM_TYPE = 100;
private static final int HEADER_TYPE = 101;
private static final int HEADER_TYPE_2 = 102;
private static final int GRID_TYPE = 103;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler);
// find recycler,
recycler = findViewById(R.id.recycler);
// set the layout
recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
// init data,
data = new ArrayList<>();
data.add("Item A");
data.add("Item B");
data.add("Item C");
// create the adapter
adapter = createAdapter();
// set the adapter
recycler.setAdapter(adapter);
}
// creates the adapter,
private RecyclerView.Adapter<ViewHolder> createAdapter() {
return new RecyclerView.Adapter<ViewHolder>() {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int type) {
switch (type) {
case HEADER_TYPE:
// inflate the layout,
ViewHolder holderHeader1 = new ViewHolder(inflateHelper(R.layout.header, parent));
// set an on click to the view here to create only one object,
holderHeader1.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
return holderHeader1;
case HEADER_TYPE_2:
// inflate the layout,
ViewHolder holderHeader2 = new ViewHolder(inflateHelper(R.layout.header, parent));
// set an on click to the view here to create only one object,
holderHeader2.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
return holderHeader2;
case ITEM_TYPE:
// inflate the layout,
ViewHolder holderItem = new ViewHolder(inflateHelper(R.layout.item, parent));
// set an on click to the view here to create only one object,
holderItem.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
return holderItem;
case GRID_TYPE:
// inflate the layout,
ViewHolder holderGrid = new ViewHolder(inflateHelper(R.layout.grid, parent));
// set an on click to the view here to create only one object,
holderGrid.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
return holderGrid;
default:
// inflate the layout,
ViewHolder holderItemDefault = new ViewHolder(inflateHelper(R.layout.item, parent));
// set an on click to the view here to create only one object,
holderItemDefault.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// do something
}
});
return holderItemDefault;
}
}
/**
* Keep the viewholder simple and the all the view finding here. This way you
* only have one viewholder.
*/
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int position) {
// go through the positions
switch (getItemViewType(position)) {
case HEADER_TYPE:
Button expandButton = viewHolder.itemView.findViewById(R.id.button);
expandButton.setText("Expand");
break;
case HEADER_TYPE_2:
Button collapseButton = viewHolder.itemView.findViewById(R.id.button);
collapseButton.setText("Collapse");
break;
case ITEM_TYPE:
// get the current item
String item = data.get(position - 3);
TextView title = viewHolder.itemView.findViewById(R.id.title);
title.setText(item);
break;
case GRID_TYPE:
break;
}
}
#Override
public int getItemCount() {
return data.size() + 3;
}
#Override
public int getItemViewType(int position) {
switch (position) {
case 0:
return HEADER_TYPE;
case 1:
return HEADER_TYPE_2;
case 2:
return GRID_TYPE;
default: return ITEM_TYPE;
}
}
};
}
private View inflateHelper(int resId, ViewGroup parent) {
return LayoutInflater.from(this).inflate(resId, parent, false);
}
// inner class for viewholder to use,
class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(#NonNull View itemView) {
super(itemView);
}
}
}
You might notice that I have used one ViewHolder. This is a pattern I believe we should adopt because it simplifies code so much more. You can find the views you need in the onBind method and thus get away with using one for all types of views.
Also I add the on click listener in the onCreateViewHolder because it is much more efficient to set it there, and it allows for the viewholder to not be onClick specific.
As I said, you can use as many types as you want, you just need to check for it, and set it at the right position.
Here are the layout files if you are interested:
Header
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:gravity="center">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Expand" />
</LinearLayout>
Item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:elevation="2dp"
android:layout_margin="16dp"
android:background="#drawable/rounded">
<TextView
android:id="#+id/title"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Item A"
android:textColor="#fff"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_chevron_right"
android:tint="#fff"/>
</LinearLayout>
Grid Layout (I cheated a bit here because I didn't see a reason to not hardcode vowels, although you might need to do it dynamically)
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:padding="16dp"
android:background="#drawable/rounded"
android:backgroundTint="#fff"
android:elevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingBottom="16dp"
android:text="French Vowels"
android:textStyle="bold"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/a"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="a"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
<TextView
android:id="#+id/e"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="e"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
<TextView
android:id="#+id/i"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="i"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp">
<TextView
android:id="#+id/o"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="o"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
<TextView
android:id="#+id/u"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="u"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
<TextView
android:id="#+id/y"
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="y"
style="#style/Base.TextAppearance.AppCompat.Medium"/>
</LinearLayout>
</LinearLayout>
</FrameLayout>
Rounded Drawable
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#222"/>
<corners android:radius="6dp"/>
</shape>
For anyone reading, if you happen to use Kotlin, consider using my small library which eliminates this recycler view boilerplate to a simple chain of functions:
https://github.com/Pfuster12/BoilerCycle
I have a listview with multiple row layouts (radio group, edit text, text view), with multiple choice mode. I want to retrieve it's selected data (user-selected or typed data) on a submit button.
This is the code from my main file:
public class GraduatingSurvey extends Fragment {
private static final String LOGTAG = "log" ;
public String stdcode = "024-15-16079";
Button submit;
RadioGroup radioGroup;
RadioButton radioButton;
EditText comment;
ArrayList<GraduatingSurveyModel> graduatingModelList;
ListView listView;
View view;
public GraduatingSurvey() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_graduating_survey, container, false);
submit = (Button) view.findViewById(R.id.btn_graduate_submit);
listView = (ListView) view.findViewById(R.id.graduate_list);
graduatingModelList = new ArrayList<GraduatingSurveyModel>();
//handle submit form Event.
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int child=listView.getAdapter().getCount();
Log.i("radio", "child: " + child);
SparseBooleanArray checked = listView.getCheckedItemPositions(); //Is returning empty
Log.i("radio", "sparseArray: " + checked);
for(int i=0;i<child;i++) {
int type = listView.getAdapter().getItemViewType(i);
Log.i("radio", "type: " + type);
if(type == 2){
// Want to retrieve data here
}
if(type == 0)
{
}
if(type == 1){
}
}
}
});
NetAsync(view);
return view;
}
This is the adapter:
public class GraduatingSurveyAdapter extends ArrayAdapter<GraduatingSurveyModel> {
private static final int TYPE_ITEM1 = 0;
private static final int TYPE_ITEM2 = 1;
private static final int TYPE_ITEM3 = 2;
int type;
ArrayList<GraduatingSurveyModel> ArrayListSurvey;
int Resource;
Context context;
LayoutInflater vi;
public GraduatingSurveyAdapter(Context context, int resource, ArrayList<GraduatingSurveyModel> objects) {
super(context, resource, objects);
ArrayListSurvey = objects;
Resource = resource;
this.context = context;
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getItemViewType(int position) {
if (position == 14){
type = TYPE_ITEM1;
} else if (position == 23 || position == 24 || position == 25){
type = TYPE_ITEM2;
}
else
{
type= TYPE_ITEM3 ;
}
return type;
}
#Override
public int getViewTypeCount() {
return 3;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
//first Item or row is being created hence ConvertView is NULL
if(convertView == null){
if (type == TYPE_ITEM2) {
convertView = vi.inflate(R.layout.graduates_survey_comment,null);
holder = new ViewHolder();
holder.tv_question = (TextView) convertView.findViewById(R.id.graduate_question);
holder.tv_comment = (TextView) convertView.findViewById(R.id.graduate_comment);
}
else if (type == TYPE_ITEM1) {
convertView = vi.inflate(R.layout.graduates_survey_subheader,null);
holder = new ViewHolder();
holder.tv_question = (TextView) convertView.findViewById(R.id.graduate_question);
}
else {
//infalte layout of normaltype
//Inflating items only once
convertView = vi.inflate(Resource,null);
holder = new ViewHolder();
holder.tv_question = (TextView) convertView.findViewById(R.id.graduate_question);
holder.tv_comment = (TextView) convertView.findViewById(R.id.graduate_comment);
holder.rg = (RadioGroup) convertView.findViewById(R.id.graduate_radioGroup);
holder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
/* RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
Log.i("radio", "onCheckedChanged: " + radioButton + " " + checkedId);
notifyDataSetChanged();*/
Integer pos = (Integer) group.getTag();
GraduatingSurveyModel element = ArrayListSurvey.get(pos);
switch (checkedId) {
case R.id.graduate_sAgree:
element.current = GraduatingSurveyModel.ANSWER_ONE_SELECTED;
break;
case R.id.graduate_agree:
element.current = GraduatingSurveyModel.ANSWER_TWO_SELECTED;
break;
case R.id.graduate_uncertain:
element.current = GraduatingSurveyModel.ANSWER_THREE_SELECTED;
break;
case R.id.graduate_disagree:
element.current = GraduatingSurveyModel.ANSWER_FOUR_SELECTED;
break;
case R.id.graduate_sDisagree:
element.current = GraduatingSurveyModel.ANSWER_FIVE_SELECTED;
break;
default:
element.current = GraduatingSurveyModel.NONE; // Something was
}
}
});
}
convertView.setTag(holder);
}else{
//reuse code. (Inflate items only once then reuse them.)
holder = (ViewHolder) convertView.getTag();
}
// get info from ArrayList(that came through JSON), and set it in the View.
if (type == TYPE_ITEM1) {
holder.tv_question.setText(ArrayListSurvey.get(position).getQuestion());
}
else if (type == TYPE_ITEM2) {
holder.tv_question.setText(ArrayListSurvey.get(position).getQuestion());
}
else{
holder.rg.setTag(new Integer(position));
holder.tv_question.setText(ArrayListSurvey.get(position).getQuestion());
if(ArrayListSurvey.get(position).current != GraduatingSurveyModel.NONE){
RadioButton r = (RadioButton) holder.rg.getChildAt(ArrayListSurvey.get(position).current);
r.setChecked(true);
}else{
holder.rg.clearCheck();
}
}
return convertView;
}
static class ViewHolder{
private TextView tv_question;
private TextView tv_comment;
private LinearLayout lv_choices;
private RadioGroup rg;
}
}
This is my model:
public class GraduatingSurveyModel {
public String question;
public String comment;
public String choices;
public String subHeading;
public int current = NONE; // hold the answer picked by the user, initial is NONE(see below)
public static final int NONE = 1000; // No answer selected
public static final int ANSWER_ONE_SELECTED = 0; // first answer selected
public static final int ANSWER_TWO_SELECTED = 1; // second answer selected
public static final int ANSWER_THREE_SELECTED = 2; // third answer selected
public static final int ANSWER_FOUR_SELECTED = 3; // forth answer selected
public static final int ANSWER_FIVE_SELECTED = 4; // forth answer selected
public GraduatingSurveyModel() {
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getChoices() {
return choices;
}
public void setChoices(String choices) {
this.choices = choices;
}
public String getSubHeading() {
return subHeading;
}
public void setSubHeading(String subHeading) {
this.subHeading = subHeading;
}
}
And this is the XML layout of the main fragment:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:background="#color/dialog_background"
android:orientation="vertical"
tools:context="iulms.iunc.edu.pk.iqraiulms.GraduatingSurvey"
android:id="#+id/main_layout">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/graduate_list"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/btn_graduate_submit"
/>
<Button
android:id="#+id/btn_graduate_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
These are the layouts for the different types of rows in listview
Row type 1:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dialog_background"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingTop="16dp">
<TextView
android:id="#+id/graduate_question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="1. Here comes questions?"
android:textSize="13dp" />
<!-- <EditText
android:id="#+id/graduate_comment"
style="#style/GraduateTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/textbox"
android:ems="10"
android:hint="Comment"
android:inputType="textMultiLine"
android:lines="3" />-->
<LinearLayout
android:id="#+id/graduate_choices"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioGroup
android:id="#+id/graduate_radioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/graduate_sAgree"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Strongly Agree" />
<RadioButton
android:id="#+id/graduate_agree"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Agree" />
<RadioButton
android:id="#+id/graduate_uncertain"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Uncertain"
/>
<RadioButton
android:id="#+id/graduate_disagree"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Disagree" />
<RadioButton
android:id="#+id/graduate_sDisagree"
style="#style/GraduateRadioButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/checkbox_selector"
android:button="#android:color/transparent"
android:checked="false"
android:text="Strongly Disagree" />
</RadioGroup>
</LinearLayout>
</LinearLayout>
Row type 2
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dialog_background"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingTop="16dp">
<TextView
android:id="#+id/graduate_question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="1. Here comes questions?"
android:textSize="13dp" />
<EditText
android:id="#+id/graduate_comment"
style="#style/GraduateTextBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/textbox"
android:ems="10"
android:hint="Comment"
android:inputType="textMultiLine"
android:lines="3" />
</LinearLayout>
Row type 3:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/dialog_background"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingTop="16dp">
<TextView
android:id="#+id/graduate_question"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="1. Here comes questions?"
android:textSize="15dp"
android:textColor="#color/primary_dark"/>
</LinearLayout>
How can I retrieve the data submitted in the main fragment?
Thanks
For this You can create a custom class with row values like,
Arraylist<CustomClass> mnewList = new ArrayList();
Class CustomClass
{
private String edValues,
private int rowId,
}
etc.
Then Implement on change listener for radio button in that add/remove current selected items to that custom list.
I have a static tab in the position 0 which return data from the server. I want by the position return data from the server at that position 1,2,3 etc. I will post the code and I cant figure what is wrong in this code.
the fragment xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
tools:context="app.amplitudenet.com.materialapp.Fragmentos.AtendimentoHistorico">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/IDProcolo1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Numero do Protocolo"
android:layout_marginLeft="12dp"
android:textSize="24dp"
android:layout_marginTop="12dp"
android:textColor="#color/colorPrimary"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Histórico: "
android:id="#+id/textoHistorico"
android:textStyle="bold"
android:layout_below="#+id/IDProcolo1"
android:layout_alignBottom="#+id/Historico"
android:layout_alignLeft="#+id/IDProcolo1"
android:layout_alignStart="#+id/IDProcolo1" />
<TextView
android:id="#+id/Historico"
android:text="Número do Histórico"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#666"
android:layout_below="#+id/IDProcolo1"
android:layout_toRightOf="#+id/textoHistorico"
android:layout_toEndOf="#+id/textoHistorico" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Responsável: "
android:layout_marginTop="5dp"
android:id="#+id/textoDataCadastro"
android:textStyle="bold"
android:layout_below="#+id/Historico"
android:layout_marginLeft="12dp"
android:layout_marginStart="8dp"
/>
<TextView
android:id="#+id/FuncionarioHistorico"
android:text="Thiago Belão"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#666"
android:layout_alignTop="#+id/textoDataCadastro"
android:layout_toRightOf="#+id/textoDataCadastro"
android:layout_toEndOf="#+id/textoDataCadastro" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Data de Solução: "
android:layout_marginTop="5dp"
android:id="#+id/textoDataSolucaoHistorico"
android:textStyle="bold"
android:layout_below="#+id/textoDataCadastro"
android:layout_marginLeft="12dp"
android:layout_marginStart="8dp"
/>
<TextView
android:id="#+id/DataSolucaoHistorico"
android:text="19/11/2015"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#666"
android:layout_alignTop="#+id/textoDataSolucaoHistorico"
android:layout_toRightOf="#+id/textoDataSolucaoHistorico"
android:layout_toEndOf="#+id/textoDataSolucaoHistorico" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Etapa Finalizada : "
android:layout_marginTop="5dp"
android:id="#+id/textoEtapa"
android:textStyle="bold"
android:layout_below="#+id/textoDataSolucaoHistorico"
android:layout_marginLeft="12dp"
android:layout_marginStart="8dp"
/>
<TextView
android:id="#+id/Etapa"
android:text="Sim / Não"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#666"
android:layout_alignTop="#+id/textoEtapa"
android:layout_toRightOf="#+id/textoEtapa"
android:layout_toEndOf="#+id/textoEtapa" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Solicitação: "
android:layout_marginTop="5dp"
android:layout_marginLeft="12dp"
android:id="#+id/textoSolicitacaoHistorico"
android:layout_below="#+id/textoEtapa"
android:textStyle="bold"
/>
<TextView
android:id="#+id/textoHistoricoAtendimento"
android:text="Texto da Solicitação"
android:layout_width="fill_parent"
android:layout_marginTop="8dp"
android:layout_height="fill_parent"
android:textColor="#666"
android:textSize="14dp"
android:layout_marginLeft="12dp"
android:layout_below="#+id/textoSolicitacaoHistorico"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/IntPosicao"
android:text="1"
android:visibility="gone" />
</RelativeLayout>
the fragment code.java
public class AtendiementoOcorrencia extends ActionBarActivity {
private Toolbar toolbar;
ViewPager pager;
AtendimentoTabsAdpter adapter;
SlidingTabLayout tabs;
ArrayList<String>Titles;
public static final int CONNECTION_TIME = 1000 *15;
public static final String SERVIDOR = "http://www.creativeriopreto.com.br/app/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_atendiemento_ocorrencia);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Bundle id = getIntent().getExtras();
String get = id.getString("id");
String total = id.getString("total");
String codigo = id.getString("codigo");
int abas = Integer.parseInt(total);
Titles = Abas(abas+1);
int numerodeabas = abas + 1;
adapter = new AtendimentoTabsAdpter(getSupportFragmentManager(),Titles, numerodeabas);
pager = (ViewPager) findViewById(R.id.pagerAtendimento);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) findViewById(R.id.tabsAtendimento);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.selector);
}
});
tabs.setViewPager(pager);
tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
TextView texto = (TextView) findViewById(R.id.IntPosicao);
texto.setText(String.valueOf(position));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public ArrayList<String> Abas(int numeroAbas) {
int i;
ArrayList<String> titulos = new ArrayList<>();
titulos.add("Detalhes");
for (i = 1; i < numeroAbas; i++)
{
titulos.add("Hist. Nº" + i);
}
return titulos;
}
}
the activity.java
public class AtendimentoHistorico extends Fragment {
Historico item;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View tela = inflater.inflate(R.layout.fragment_atendimento_historico, container, false);
Bundle id = getActivity().getIntent().getExtras();
String codigo = id.getString("codigo");
int codid = Integer.parseInt(codigo);
TextView posicao = (TextView) tela.findViewById(R.id.IntPosicao);
String coisocoisado = posicao.getText().toString();
int pos;
pos = Integer.parseInt(coisocoisado);
item = new Historico(codid,pos);
Autenticado(item);
return tela;
}
public void Autenticado(Historico historico) {
ServerRequests server = new ServerRequests(getActivity());
server.getDadosHistoricoBackground(historico, new GetHistoricoCallBack() {
#Override
public void done(Historico returnedHistorico) {
if (returnedHistorico == null)
{
Erro();
}
else
{
Bundle id = getActivity().getIntent().getExtras();
String get = id.getString("id");
TextView momo = (TextView) getActivity().findViewById(R.id.IDProcolo1);
momo.setText("Protocolo Nº "+get);
TextView momo1 = (TextView) getActivity().findViewById(R.id.FuncionarioHistorico);
if (returnedHistorico.Setor == "null")
{
momo1.setText(""+returnedHistorico.Funcionario);
}
else
{
momo1.setText(""+returnedHistorico.Setor);
}
TextView momo2 = (TextView) getActivity().findViewById(R.id.DataSolucaoHistorico);
momo2.setText(""+returnedHistorico.Data);
TextView momo3 = (TextView) getActivity().findViewById(R.id.Etapa);
momo3.setText(""+returnedHistorico.Etapa);
TextView momo4 = (TextView) getActivity().findViewById(R.id.textoHistoricoAtendimento);
momo4.setText(""+returnedHistorico.Solucao);
TextView momo5 = (TextView) getActivity().findViewById(R.id.Historico);
momo5.setText(""+returnedHistorico.Sequencia);
TextView momo6 = (TextView) getActivity().findViewById(R.id.txtFinalizado);
momo6.setText(""+returnedHistorico.Finalizado);
}
}
});
}
private void Erro() {
AlertDialog.Builder alerta = new AlertDialog.Builder(getActivity());
alerta.setMessage("Erro ao Carregar Histórico de Atendimento");
alerta.setPositiveButton("OK", null);
alerta.show();
}
}
the adpter code
public class AtendimentoTabsAdpter extends FragmentStatePagerAdapter {
ArrayList<String> Titles; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
// Build a Constructor and assign the passed Values to appropriate values in the class
public AtendimentoTabsAdpter(FragmentManager fm,ArrayList<String> mTitles, int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
AtendimentoDetalhado tab1 = new AtendimentoDetalhado();
return tab1;
}
else // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
AtendimentoHistorico tab2 = new AtendimentoHistorico();
return tab2;
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles.get(position);
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
I have changed the adpater and make a list, updatated the method in my rest api now i have two tabs and all the data i want