How to split this activity into 2 ListViews - java

I have this listview with drinks (bebidas) but i wanted to add a new listview in the same activity for hamburguers.
My code is not working because it keeps repeating the same names.
public class Cardapios extends AppCompatActivity {
DbController db;
ListView listview_cardapios, listview_hamburguers;
public int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardapios);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
db = new DbController(getBaseContext());
Bundle b = getIntent().getExtras();
if (b != null) {
id = b.getInt("id");
}
preencheLista();
// preencheLista2();
}
private void preencheLista() {
ArrayList<CardapioGetter> itens = new ArrayList<CardapioGetter>();
Cursor c = db.getBebidas(id);
while (! c.isAfterLast()) {
itens.add(new CardapioGetter(c.getString(c.getColumnIndex(DbHelper.NOME_BEBIDAS)),c.getString(c.getColumnIndex(DbHelper.VALOR_BEBIDAS))));
c.moveToNext();
}
defineAdapter(itens);
}
private void defineAdapter(ArrayList<CardapioGetter> itens) {
listview_cardapios = (ListView) findViewById(R.id.listview_cardapios);
AdapterListCardapios adapter = new AdapterListCardapios(getApplicationContext(), itens);
listview_cardapios.setAdapter(adapter);
listview_cardapios.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CardapioGetter itemValue = (CardapioGetter) listview_cardapios.getItemAtPosition(position);
}
});
}
private void preencheLista2() {
ArrayList<CardapioGetter> itens = new ArrayList<CardapioGetter>();
Cursor h = db.getHamburguers(id);
while (! h.isAfterLast()) {
itens.add(new CardapioGetter(h.getString(h.getColumnIndex(DbHelper.NOME_HAMBURGUERS)),h.getString(h.getColumnIndex(DbHelper.VALOR_HAMBURGUERS))));
h.moveToNext();
}
defineAdapter2(itens);
}
private void defineAdapter2(ArrayList<CardapioGetter> itens) {
listview_hamburguers = (ListView) findViewById(R.id.listview_hamburguers);
AdapterListCardapios adapter = new AdapterListCardapios(getApplicationContext(), itens);
listview_hamburguers.setAdapter(adapter);
listview_hamburguers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CardapioGetter itemValue = (CardapioGetter) listview_hamburguers.getItemAtPosition(position);
}
});
}
Layout has the 4 textviews that i replace with data from database.
I want to split the 2 from the botton into a new listview.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textview_valorbebida"
android:textColor="#color/abc_input_method_navigation_guard"
android:layout_marginTop="133dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textview_nomebebida"
android:textColor="#color/abc_input_method_navigation_guard"
android:layout_alignTop="#+id/textview_valorbebida"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Bebidas"
android:id="#+id/textView2"
android:layout_above="#+id/textview_nomebebida"
android:layout_alignParentStart="true"
android:textColor="#color/abc_input_method_navigation_guard" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Pratos"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/textView4"
android:textColor="#color/abc_input_method_navigation_guard" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textview_nomehamburguer"
android:layout_below="#+id/textView4"
android:layout_alignParentStart="true"
android:textColor="#color/abc_input_method_navigation_guard" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textview_valorhamburguer"
android:layout_alignTop="#+id/textview_nomehamburguer"
android:layout_alignParentEnd="true"
android:textColor="#color/abc_input_method_navigation_guard" />
</RelativeLayout>
the adapterlist class that i am using. setting itens to textviews.
the text views that i want separate on the listview.
public class AdapterListCardapios extends BaseAdapter{
private LayoutInflater mInflater;
private ArrayList<CardapioGetter> itens;
public AdapterListCardapios(Context context, ArrayList<CardapioGetter> itens) {
//Itens que preencheram o listview
this.itens = itens;
//responsavel por pegar o Layout do item.
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return itens.size();
}
/**
* Retorna o item de acordo com a posicao dele na tela.
*/
public CardapioGetter getItem(int position) {
return itens.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
//Pega o item de acordo com a posição.
CardapioGetter item = itens.get(position);
//infla o layout para podermos preencher os dados
view = mInflater.inflate(R.layout.textview_cardapios, null);
((TextView) view.findViewById(R.id.textview_nomehamburguer)).setText(item.getNome_hamburguers());
((TextView) view.findViewById(R.id.textview_valorhamburguer)).setText("R$ "+ item.getValor_hamburguers());
((TextView) view.findViewById(R.id.textview_nomebebida)).setText(item.getNome_bebidas());
((TextView) view.findViewById(R.id.textview_valorbebida)).setText("R$ "+ item.getValor_bebidas());
return view;
}
What I want is. 1 listview with drinks and 1 listview with food on the same activity. thanks

CriarInterface p = new CriarInterface();
new Thread(p).start();
}
public class CriarInterface implements Runnable {
#Override
public void run() {
preencheLista();
preencheLista2();
}
}
worked.

Related

Why is the dialog design inconsistent on the device?

I designed dialog and assigned it a file named XML layout with a set of elements and then created a function to show it from within fragment. It appeared on the emulator screen well but it did not appear the same on the device.
What are the appropriate adjustments to be shown on the device well?
// layout xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="260dp"
android:layout_height="260dp"
android:orientation="vertical"
android:background="#f71717">
<LinearLayout
android:id="#+id/l_layout"
android:paddingTop="10dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
tools:ignore="ObsoleteLayoutParam">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:ignore="ExtraText">
<RadioGroup
android:id="#+id/radioSex"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="UselessParent">
<RadioButton
android:id="#+id/second2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:button="#null"
android:layoutDirection="rtl"
android:textAlignment="textStart"
android:layout_gravity="start"
android:textDirection="rtl"
android:drawablePadding="10dp"
android:drawableRight="#android:drawable/btn_radio"
android:text="رفض"
android:textColor="#ffffff"
android:textSize="20dp"
tools:ignore="HardcodedText,RtlHardcoded,SpUsage" />
<RadioButton
android:id="#+id/second"
android:checked="true"
android:layoutDirection="rtl"
android:textDirection="rtl"
android:textAlignment="textStart"
android:layout_gravity="start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:button="#null"
android:drawablePadding="10dp"
android:drawableRight="#android:drawable/btn_radio"
android:text="قبول"
android:textColor="#ffffff"
android:textSize="20dp"
tools:ignore="HardcodedText,RtlHardcoded,SpUsage" />
</RadioGroup>
/>
</LinearLayout>
<TextView
android:id="#+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#ffffff"
android:text="وقت التسليم"
android:textSize="20dp"
tools:ignore="HardcodedText,SpUsage" />
<Spinner
android:id="#+id/tex"
android:layout_width="172dp"
android:paddingRight="40dp"
android:layout_height="wrap_content"
android:layout_below="#+id/tv_title"
android:drawSelectorOnTop="true"
android:popupBackground="#fff78c"
style="#style/spinner_style"
tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry,SpUsage"
android:entries="#array/day_"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/rl"
android:layout_width="250dp"
android:layout_height="129dp"
android:layout_below="#+id/l_layout"
android:background="#f71717"
android:layout_marginTop="0dp"
tools:ignore="ObsoleteLayoutParam">
<TextView
android:id="#+id/tv_h"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toStartOf="#+id/spinner_minutes2"
android:paddingLeft="10dp"
android:text="ساعة"
android:textColor="#ffffff"
tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />
<TextView
android:id="#+id/tv_m"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/spinner_minutes2"
android:layout_alignBottom="#+id/spinner_minutes2"
android:layout_alignStart="#+id/button_holder"
android:paddingLeft="10dp"
android:text="دق"
android:textColor="#ffffff"
tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />
<TextView
android:id="#+id/tv_pam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/spinner_minutes"
android:layout_alignBottom="#+id/spinner_minutes"
android:layout_alignEnd="#+id/spinner_minutes3"
android:layout_marginEnd="12dp"
android:paddingLeft="30dp"
android:text="ص/م"
android:textColor="#ffffff"
tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" />
<Spinner
android:id="#+id/spinner_minutes"
android:layout_width="85dip"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
style="#style/spinner_style"
android:popupBackground="#fff78c"
android:layout_alignStart="#+id/spinner_minutes2"
android:entries="#array/hour_" />
<Spinner
android:id="#+id/spinner_minutes2"
android:layout_width="85dip"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_minutes"
android:layout_marginStart="16dp"
android:popupBackground="#fff78c"
style="#style/spinner_style"
android:layout_toEndOf="#+id/tv_m"
android:entries="#array/hour_" />
<Spinner
android:id="#+id/spinner_minutes3"
android:layout_width="85dip"
android:layout_height="wrap_content"
style="#style/spinner_style"
android:paddingRight="20dp"
android:entries="#array/apm"
android:popupBackground="#fff78c"
tools:ignore="RtlHardcoded,RtlSymmetry"
android:layout_alignBaseline="#+id/spinner_minutes2"
android:layout_alignBottom="#+id/spinner_minutes2"
android:layout_toEndOf="#+id/spinner_minutes" />
<TextView
android:id="#+id/text_timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textAppearance="?android:attr/textAppearanceMedium"
android:visibility="gone" />
<LinearLayout
android:id="#+id/button_holder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner_minutes"
android:layout_centerHorizontal="true"
android:paddingTop="10dp"
android:layout_marginTop="20dip">
<Button
android:id="#+id/button_set"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginLeft="10dip"
android:text="الغاء"
tools:ignore="ButtonStyle,HardcodedText,RtlHardcoded" />
<Button
android:id="#+id/button_cancel"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_marginBottom="5dip"
android:layout_marginRight="10dip"
android:text="إرسال"
tools:ignore="ButtonOrder,ButtonStyle,HardcodedText,RtlHardcoded" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
//calss Fragment:
public class Page_6Fragment extends android.support.v4.app.Fragment implements AdapterView.OnItemSelectedListener {
TextView t1,t2,t3,t4;
Spinner spin ,spin2,spin3,spin4;
Dialog dialog;
RecyclerView recyclerView;
List<Customer> customers;
CustomerAdapter adapter;
View rootView;
String TAG = "MainActivity - ";
Context context;
API api;
Activity a;
public static Page_6Fragment newInstance() {
Page_6Fragment fragment = new Page_6Fragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_customer, container, false);
// View rootView = inflater.inflate(R.xml.pref, container, false);
// Intent intent = new Intent(PreferenceDemoActivity.this,PrefsActivity.class);
// startActivity(intent);
this.context = getActivity();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
customers = new ArrayList<>();
adapter = new CustomerAdapter(context, customers);
adapter.setLoadMoreListener(new CustomerAdapter.OnLoadMoreListener(){
#Override
public void onLoadMore() {
recyclerView.post(new Runnable() {
#Override
public void run() {
int index = customers.size() - 1;
loadMore(index);
}
});
//Calling loadMore function in Runnable to fix the
// java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling error
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
//recyclerView.addItemDecoration(new VerticalLineDecorator(2));
recyclerView.setAdapter(adapter);
api = ServiceGenerator.createService(API.class);
load(0);
return rootView;
}
private void load(int index){
Call<List<Customer>> call = api.getCustomer(index);
call.enqueue(new Callback<List<Customer>>(){
#Override
public void onResponse(Call<List<Customer>> call, Response<List<Customer>> response){
// Toast.makeText(getActivity(), "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
// Log.i("TRUE_TRUE","Yes"+response.body().get(0).title);
if(response.isSuccessful()){
customers.addAll(response.body());
adapter.notifyDataChanged();
// Toast.makeText(MainActivity.this, "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
}else{
Log.e(TAG," Response Error "+String.valueOf(response.code()));
}
}
#Override
public void onFailure(Call<List<Customer>> call, Throwable t) {
Log.e(TAG," Response Error "+t.getMessage());
}
});
}
private void loadMore(int index){
//add loading progress view
customers.add(new Customer("load"));
adapter.notifyItemInserted(customers.size()-1);
Call<List<Customer>>call = api.getCustomer(index);
call.enqueue(new Callback<List<Customer>>(){
#Override
public void onResponse(Call<List<Customer>> call, Response<List<Customer>>response) {
if(response.isSuccessful()){
// remove loading view .......
customers.remove(customers.size()-1);
List<Customer>result=response.body();
if(result.size()>0){
// add loaded data
customers.addAll(result);
}else{//result size 0 means there is no more data available at server
adapter.setMoreDataAvailable(false);
//telling adapter to stop calling load more as no more server data available
Toast.makeText(context,"No More Data Available",Toast.LENGTH_LONG).show();
}
adapter.notifyDataChanged();
}else{
Log.e(TAG," Load More Response Error "+String.valueOf(response.code()));
}
}
#Override
public void onFailure(Call<List<Customer>>call,Throwable t) {
Log.e(TAG," Load More Response Error "+t.getMessage());
}
});
}
public void showDialog(Context context){
dialog = new Dialog(context);
dialog.setCancelable(true);
dialog.setContentView(R.layout.layout);
dialog.show();
String[] bankNames = {
"BO","SB","HD","PN","Bj"
};
t1= (TextView)dialog.findViewById(R.id.tv_h);
t2= (TextView)dialog.findViewById(R.id.tv_m);
t3= (TextView)dialog.findViewById(R.id.tv_title);
t4= (TextView)dialog.findViewById(R.id.tv_pam);
spin =(Spinner)dialog.findViewById(R.id.spinner_minutes);
spin2 =(Spinner)dialog.findViewById(R.id.spinner_minutes2);
spin3 =(Spinner)dialog.findViewById(R.id.spinner_minutes3);
spin4 =(Spinner)dialog.findViewById(R.id.tex);
spin.setOnItemSelectedListener(this);
spin2.setOnItemSelectedListener(this);
spin3.setOnItemSelectedListener(this);
spin4.setOnItemSelectedListener(this);
RadioButton radioButton2 = (RadioButton)dialog.findViewById(R.id.second2);
RadioButton radioButton = (RadioButton)dialog.findViewById(R.id.second);
RadioGroup radioGroup = (RadioGroup)dialog.findViewById(R.id.radioSex);
ArrayAdapter<String> a = new ArrayAdapter<String>(context,R.layout.spinner_item,bankNames);
//ArrayAdapter b = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames2);
a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(a);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton)dialog.findViewById(checkedId);
if (checkedId == R.id.second2) {
RadioYes();
} else if (checkedId == R.id.second) {
RadioNo();
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
((TextView) parent.getChildAt(0)).setTextColor(Color.WHITE);
((TextView) parent.getChildAt(0)).setTextSize(16);
// Toast.makeText(getApplicationContext(),"" +spin2.getSelectedItem(), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void RadioNo(){
spin.setVisibility(View.VISIBLE);
spin2.setVisibility(View.VISIBLE);
spin3.setVisibility(View.VISIBLE);
spin4.setVisibility(View.VISIBLE);
t1.setVisibility(View.VISIBLE);
t2.setVisibility(View.VISIBLE);
t3.setVisibility(View.VISIBLE);
t4.setVisibility(View.VISIBLE);
}
public void RadioYes(){
spin.setVisibility(View.GONE);
spin2.setVisibility(View.GONE);
spin3.setVisibility(View.GONE);
spin4.setVisibility(View.GONE);
t1.setVisibility(View.GONE);
t2.setVisibility(View.GONE);
t3.setVisibility(View.GONE);
t4.setVisibility(View.GONE);
}
}
// class to call function show dailoge
public class CustomerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public final int TYPE_MOVIE = 0;
public final int TYPE_LOAD = 1;
static Context context;
List<Customer> customers;
OnLoadMoreListener loadMoreListener;
boolean isLoading = false, isMoreDataAvailable = true;
public CustomerAdapter(Context context, List<Customer> customers) {
this.context = context;
this.customers = customers;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
if(viewType==TYPE_MOVIE){
return new CustomerHolder(inflater.inflate(R.layout.row_movie,parent,false));
}else{
return new LoadHolder(inflater.inflate(R.layout.row_load,parent,false));
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(position>=getItemCount()-1 && isMoreDataAvailable && !isLoading && loadMoreListener!=null){
isLoading = true;
loadMoreListener.onLoadMore();
}
if(getItemViewType(position)==TYPE_MOVIE){
((CustomerHolder)holder).bindData(customers.get(position));
if(((CustomerHolder)holder).buttonViewOption != null)((CustomerHolder)holder).buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Page_6Fragment.newInstance().showDialog(context);
}
});
}
}
#Override
public int getItemViewType(int position) {
if(customers.get(position).type.equals("movie")){
return TYPE_MOVIE;
}else{
return TYPE_LOAD;
}
}
#Override
public int getItemCount(){
return customers.size();
}
/* VIEW HOLDERS */
static class CustomerHolder extends RecyclerView.ViewHolder{
TextView tvTitle;
TextView tvRating;
Button buttonViewOption;
public CustomerHolder(View itemView) {
super(itemView);
tvTitle=(TextView)itemView.findViewById(R.id.title);
tvRating=(TextView)itemView.findViewById(R.id.rating);
buttonViewOption = (Button) itemView.findViewById(R.id.textViewOptions);
}
void bindData(Customer cust){
tvTitle.setText(cust.name);
tvRating.setText(cust.title);
}
}
static class LoadHolder extends RecyclerView.ViewHolder{
public LoadHolder(View itemView) {
super(itemView);
}
}
public void setMoreDataAvailable(boolean moreDataAvailable) {
isMoreDataAvailable = moreDataAvailable;
}
/* notifyDataSetChanged is final method so we can't override it
call adapter.notifyDataChanged(); after update the list
*/
public void notifyDataChanged(){
notifyDataSetChanged();
isLoading = false;
}
public interface OnLoadMoreListener{
void onLoadMore();
}
public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
this.loadMoreListener = loadMoreListener;
}
}

Android - ArrayAdapter toggle ImageButton src between Play and Pause in ListView

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!

Custom GridView Adapter not displaying

I'm creating a list of "channels" on an app that users can select. I want them in a grid view, (kind of like clickable tiles). There are supposed to be two separate Grids on this Fragment - default channels (channelListSupplied) and ones that the user will have to request subscriptions to (channelListEarned).
I used a custom adapter that I got from another answer here on SO, but I can't get it to work because it's in a Fragment instead of in the Activity, and I'm sure there's some reference I'm not passing correctly.
Below is a list of the relevant pieces of Java and XML...
FragmentChannels.java: (fragment to MainActivity.java)
public class FragmentChannels extends Fragment implements FragmentManager.OnBackStackChangedListener {
ViewGroup container;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
final JSONObject channelList = data.getJSONObject("channels");
final JSONArray channelListSupplied = channelList.getJSONArray("supplied");
final JSONArray channelListEarned = channelList.getJSONArray("earned");
GridView channelViewSupplied = (GridView) view.findViewById(R.id.channel_grid_supplied);
GridView channelViewEarned = (GridView) view.findViewById(R.id.channel_grid_earned);
if (Session.getSessionVar("canHasSpecial").equals("1")) {
FragmentChannels.this.createGridView(channelViewEarned, channelListEarned, FragmentChannels.this.container);
}
FragmentChannels.this.createGridView(channelViewSupplied, channelListSupplied, FragmentChannels.this.container);
...
return view;
}
public void createGridView(final GridView gridView, JSONArray list, final ViewGroup container) throws JSONException {
final String[] gridList = new String[list.length()];
final Activity activity = getActivity();
for (int i = 0; i < list.length(); i++) {
JSONObject channelData = (JSONObject) list.get(i);
gridList[i] = channelData.getString("source_name");
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
gridView.setAdapter(new GridViewAdapter(activity, gridList, container));
}
});
}
public boolean createChannelMenu(Menu menu) {
MenuInflater inflater = this.getActivity().getMenuInflater();
inflater.inflate(R.menu.menu_channels, menu);
super.onCreateOptionsMenu(menu, inflater);
return true;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
final Activity activity = getActivity();
}
#Override
public void onBackStackChanged() {
}
}
GridViewAdapter.java:
public class GridViewAdapter extends BaseAdapter {
private Context context;
private final String[] textViewValues;
private ViewGroup container;
public GridViewAdapter(Context context, String[] textViewValues, ViewGroup container) {
this.context = context;
this.textViewValues = textViewValues;
this.container = container;
}
#Override
public int getCount() {
return this.textViewValues.length;
}
#Override
public Object getItem(int position) {
return textViewValues[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("CDFF", position+": "+this.textViewValues[position]);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = inflater.inflate(R.layout.grid_item_layout, this.container);
TextView titleView = (TextView) gridView.findViewById(R.id.grid_item_title);
titleView.setText(textViewValues[position]);
}
else {
gridView = convertView;
}
return gridView;
}
}
fragment_channels.xml:
<FrameLayout 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:name="FragmentChannels"
android:id="#+id/fragment_channel_container"
tools:context="xx.xxx.xxxx.FragmentChannels"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:text="My Channels"
android:background="#color/peach"
android:textSize="20sp"
android:textColor="#color/midnightBlue"
android:gravity="center"
android:textAppearance="#style/TextAppearance.FontPath"
/>
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/channel_grid_earned"
android:layout_margin="5dp"
android:columnWidth="180dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform"
android:verticalSpacing="5dp"
android:focusable="true"
android:clickable="true"/>
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/channel_grid_supplied"
android:layout_margin="5dp"
android:columnWidth="180dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform"
android:verticalSpacing="5dp"
android:focusable="true"
android:clickable="true"/>
</LinearLayout>
</FrameLayout>
grid_item_layout.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="#color/white"
android:orientation="vertical"
android:padding="5dp">
<ImageView
android:id="#+id/grid_item_image"
android:layout_width="150dp"
android:layout_height="100dp"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/grid_item_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:gravity="center"
android:maxLines="2"
android:ellipsize="marquee"
android:textSize="12sp" />
</RelativeLayout>
As of now, nothing displays on the Fragment except the "My Channels" TextView.
I greatly appreciate any help!
Fixed.
I changed the line:
gridView = inflater.inflate(R.layout.grid_item_layout, this.container);
To:
gridView = inflater.inflate(R.layout.grid_item_layout, null);
in the GridViewAdapter.java class.

Get the position of the adpter in a fragment from a tab

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

Adding Custom Header to List Fragment in Android

I am trying to add a custom header that isnt clickable but will have a checkbox that will "check all" checkboxes under it.
This is my List Fragment
public class AssesmentListFragment extends ListFragment {
private static String BUNDLE_KEY_APPLICATION = "LIST_ITEM";
FastAssesmentListAdapter adapter;
View listHeader;
public AssesmentListFragment() {}
public AssesmentListFragment(Data[] data) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Data[] assestments = {new Data("Assesment ID","Name", "Date"), new Data("123456", "Assestment 2", "9/12/12"),
new Data("345672", "Assesment 3", "9/13/12"), new Data("566893", "Assesment 4", "9/14/12")};
//This is the part that makes the app crash
View header = getActivity().getLayoutInflater().inflate(R.layout.list_adapter_assesments, null);
ListView listView = getListView();
listView.addHeaderView(header);
adapter = new FastAssesmentListAdapter(getActivity(), assestments);
setListAdapter(adapter);
updateList(assestments);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
private void updateList(Data[] assestments) {
// NOTE: addAll is not being used to support pre-honeycomb devices
synchronized(adapter) {
adapter.clear();
adapter.addAll(assestments);
adapter.notifyDataSetChanged();
}
}
#Override
public void onListItemClick(ListView parentView, View selectedItemView, int position, long id) {
String model = (String) parentView.getItemAtPosition(position);
((FacilityActivity) getActivity()).onItemSelected(model);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//outState.putInt("curChoice", mCurCheckPosition);
}
}
This is the layout I am trying to use for header
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="25dp"
android:paddingRight="10dp"
android:orientation="horizontal">
<TextView android:id="#+id/adapter_header_textview_column1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Assesment ID" />
<TextView android:id="#+id/adapter_header_textview_column2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Name" />
<TextView android:id="#+id/adapter_header_textview_column3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textColor="#color/defaultTextColor"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="28sp"
android:text="Date"/>
<CheckBox
android:id="#+id/header_check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:color="#color/defaultTextColor"
android:layout_weight=".5"
android:gravity="center" />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="5dp"
android:background="#color/BPGreenColor" />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Then this is the array adapter I am using:
public class FastAssesmentListAdapter extends ArrayAdapter<Data> {
private static int LAYOUT_ID = R.layout.list_adapter_with_checkbox_three_column;
private final Data[] assesments;
private final Context context;
LinearLayout listHeader;
static class ViewHolder {
protected TextView column1;
protected TextView column2;
protected TextView column3;
protected CheckBox checkbox;
}
public FastAssesmentListAdapter(Context context, Data[] assesments) {
super(context, LAYOUT_ID, assesments);
this.context = context;
this.assesments = assesments;
}
//ListFragment and array adapter will automatically call this over and over to auto populate the list
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Data item = getItem(position);
// Formulate row view (create if it does not exist yet)
View view = convertView;
if(view == null) {
LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();
view = inflater.inflate(LAYOUT_ID, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.column1 = (TextView) view.findViewById(R.id.adapter_textview_column1);
viewHolder.column2 = (TextView) view.findViewById(R.id.adapter_textview_column2);
viewHolder.column3 = (TextView) view.findViewById(R.id.adapter_textview_column3);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check_box);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Clicked",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getContext(), FacilityActivity.class);
getContext().startActivity(intent);
}
});
if(viewHolder.checkbox != null) {
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked) {
item.setSelected(isChecked);
Toast.makeText(getContext(), "Checked",
Toast.LENGTH_SHORT).show();
}
}
});
}
view.setTag(viewHolder);
viewHolder.checkbox.setTag(position);
}
ViewHolder viewHolder = (ViewHolder) view.getTag();
viewHolder.checkbox.setTag(position);
viewHolder.column1.setText(item.getColumn1());
viewHolder.column2.setText(item.getColumn2());
viewHolder.column3.setText(item.getColumn3());
viewHolder.checkbox.setChecked(item.isSelected());
return view;
}
}
on a side note, the onlistitemclicked in the fragment doesnt work, i have to set a listener in the adapter and then it works. any ideas on that? but mainly I need to figure out how to use a custom header and custom rows in the list view. Here is the layout for the rows
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="25dp"
android:paddingRight="10dp"
android:orientation="horizontal">
<TextView android:id="#+id/adapter_textview_column1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<TextView android:id="#+id/adapter_textview_column2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<TextView android:id="#+id/adapter_textview_column3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25sp" />
<CheckBox
android:id="#+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".5"
android:gravity="center" />
</LinearLayout>

Categories

Resources