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
Related
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
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;
}
}
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 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.