I'm new to Android Studio and coding in general and I am trying to display a custom ListView with an image of a colour and the name of the colour. I have used a custom Adapter to inflate the view with two arrays containing the drawable image colours and string of the names.
The problem I am having - the custom adapter is only displaying the layers from position 1 and onwards. For example, where the first layer should be img_01 and "red" - it is displaying img_02 and "Orange".
I've tried debugging the code and it seems that though the adapter is setting the values for position 0, but I cannot find the reason why it is not displaying (as the others are displaying fine).
The images & names are just placeholders, so an alternative solution that doesn't include both the drawables and names wouldn't be viable,
Thank you in advance
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context context;
int[] images;
String[] colour;
LayoutInflater mInflater;
public CustomAdapter(Context c, int[] i, String[] col) {
this.context = c; //sets the application context that has been passed to the adapter
this.images = i; //sets the images array that has been passed to the adapter
this.colour = col; //sets the colour array that has been passed to the adapter
mInflater = (LayoutInflater.from(context)); //sets the layout inflater from context
}
#Override
public int getCount() { //total number of elements in the array
return images.length;
}
#Override
public Object getItem(int position) { //gets the item using the position
return null;
}
#Override
public long getItemId(int position) { //gets the item position
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) { //this is used to update the view
convertView = mInflater.inflate(R.layout.custom_layout, null);
ImageView image = convertView.findViewById(R.id.imageView);
TextView text = convertView.findViewById(R.id.textView);
text.setText(colour[position]);
image.setImageResource(images[position]);
return convertView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView mListView;
int[] images = {R.drawable.img01,
R.drawable.img02,
R.drawable.img03,
R.drawable.img04};
String[] colour = {"Red",
"Orange",
"Yellow",
"Green"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.listView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), images, colour);
//passes information of images and application context to the item adapter
mListView.setAdapter(customAdapter);
//sets the adapter to the listview
}
}
custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="7dp"
android:layout_marginLeft="7dp"
android:layout_marginTop="9dp"
app:srcCompat="#drawable/img01" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="99dp"
android:layout_marginLeft="99dp"
android:layout_marginTop="36dp"
android:text="colourName" />
</RelativeLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="409dp"
android:layout_height="729dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try to set the height of the ListView to wrap_content instead of hardcoding it
<ListView
...
android:layout_height="wrap_content"/>
You can do it with RecyclerView.
Create a custom class
public class ExampleItem {
private int mImageResource; //your color image
private String mText1; //your text
public ExampleItem(int imageResource, String text1) {
mImageResource = imageResource;
mText1 = text1;
}
public int getImageResource() {
return mImageResource;
}
public String getText1() {
return mText1;
}
}
Create a XML layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
app:cardCornerRadius="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="2dp" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/imageView"
android:text="Line 1"
android:textColor="#android:color/black"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Create a Recycler View Adapter
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<ExampleItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public TextView mTextView1;
public ExampleViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageView);
mTextView1 = itemView.findViewById(R.id.textView);
}
}
public ExampleAdapter(ArrayList<ExampleItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
ExampleItem currentItem = mExampleList.get(position);
holder.mImageView.setImageResource(currentItem.getImageResource());
holder.mTextView1.setText(currentItem.getText1());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
your activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.application.recyclerviewproject.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray"
android:padding="4dp"
android:scrollbars="vertical" />
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<ExampleItem> exampleList = new ArrayList<>();
exampleList.add(new ExampleItem(R.drawable.img01, "Red"));
exampleList.add(new ExampleItem(R.drawable.img02, "Orange"));
exampleList.add(new ExampleItem(R.drawable.img03, "Yellow"));
exampleList.add(new ExampleItem(R.drawable.img04, "Green"));
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter(exampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
}
Related
I have an AlertDialog in it there used to be a ListView in which the contents of the ArrayList were displayed. For beauty, I decided to replace it with Recyclerview, Card and the problems started.
Items are added to ArrayList <String> mainListWord during the work and they should be included in the Recyclerview cards. The problem is that either the entire list falls into one card at once, or each next card contains the previous elements + 1. For example: the first card: 1 element, the second card: 2 elements, etc.
How to implement it so that when a new element is added to the array, it will be placed in its own card?
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/innerText"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_centerInParent="true"/>
<Button
android:id="#+id/press"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Press"
android:layout_below="#id/innerText"
android:layout_centerHorizontal="true"
android:onClick="openDialog"/>
</RelativeLayout>
recycler_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="4dp"
android:layout_margin="4dp"
app:cardBackgroundColor="#color/colorCardBack">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#color/colorCard">
<ImageView
android:id="#+id/imageView_1"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="4dp" />
<TextView
android:id="#+id/textview_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text_1"
android:textStyle="bold"
android:textColor="#android:color/black"
android:layout_centerInParent="true"
android:textSize="16sp"
android:layout_marginStart="5dp"
android:layout_toEndOf="#id/imageView_1"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
stats_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="50dp"
android:layout_margin="10dp"
android:background="#color/colorAccent"
android:scrollbars="vertical"
android:layout_above="#id/butClose"/>
<Button
android:id="#+id/butClose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText innerText;
private Button press, butClose;
private ArrayList<RecyclerViewItem> recyclerViewItem;
private ArrayList<String> mainListWord;
private AlertDialog OptionDialog;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerViewItem = new ArrayList<>();
mainListWord = new ArrayList<>();
innerText = findViewById(R.id.innerText);
press = findViewById(R.id.butClose);
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void makeRecyclerList(ArrayList<String> income){
String[] listWord_lenght = income.toArray(new String[0]);
String keyWord = (String.join("", listWord_lenght));
recyclerViewItem.add(new RecyclerViewItem(R.drawable.star, keyWord));
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void openDialog(View v){
String word = innerText.getText().toString();
mainListWord.add(word);
makeRecyclerList(mainListWord);
Dialogus();
innerText.setText("");
}
public void Dialogus(){
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.stats_fragment, null, false);
OptionDialog = new AlertDialog.Builder(this).create();
OptionDialog.setTitle("TestInfo");
recyclerView = v.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(recyclerViewItem);
layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
butClose = v.findViewById(R.id.butClose);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
butClose.setBackgroundColor(Color.CYAN);
butClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OptionDialog.dismiss();
}
});
OptionDialog.show();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewViewHolder> {
private ArrayList<RecyclerViewItem> arrayList;
public static class RecyclerViewViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView_1;
public TextView textview_1;
public RecyclerViewViewHolder(#NonNull View itemView) {
super(itemView);
imageView_1 = itemView.findViewById(R.id.imageView_1);
textview_1 = itemView.findViewById(R.id.textview_1);
}
}
public RecyclerViewAdapter(ArrayList<RecyclerViewItem> arrayList){
this.arrayList = arrayList;
}
#NonNull
#Override
public RecyclerViewViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_item, viewGroup, false);
RecyclerViewViewHolder recyclerViewViewHolder= new RecyclerViewViewHolder(view);
return recyclerViewViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewViewHolder recyclerViewViewHolder, int position) {
RecyclerViewItem recyclerViewItem = arrayList.get(position);
recyclerViewViewHolder.imageView_1.setImageResource(recyclerViewItem.getImageResource());
recyclerViewViewHolder.textview_1.setText(recyclerViewItem.getText_1());
}
#Override
public int getItemCount() {
return arrayList.size();
}
}
RecyclerViewItem.java
package freijer.app.one;
public class RecyclerViewItem {
private int imageResource;
private String text_1;
public int getImageResource() {
return imageResource;
}
public void setImageResource(int imageResource) {
this.imageResource = imageResource;
}
public String getText_1() {
return text_1;
}
public void setText_1(String text_1) {
this.text_1 = text_1;
}
public RecyclerViewItem(int imageResource, String text_1) {
this.imageResource = imageResource;
this.text_1 = text_1;
}
}
So, for a personal project I'm making a stream app for Android which are separated by three fragments in the main screen where each of those fragment will be a list of a type of show in our archive, like movies, TV series and animations by using a RecyclerView inside of them.
That being said, after some errors that I managed to fix, the app is not showing what was expected, by skipping the RecyclerView because it has no "adapter".
Here is the code so far:
The main activity:
public class MenuPrincipal extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_principal);
AbasMenuPrincipalAdapter adapter = new AbasMenuPrincipalAdapter( getSupportFragmentManager() );
adapter.adicionar( new FilmesFragment() , "Filmes");
adapter.adicionar( new SeriesFragment() , "Series");
adapter.adicionar( new AnimacoesFragment() , "Animações");
ViewPager viewPager = (ViewPager) findViewById(R.id.abas_view_pager);
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.abas);
tabLayout.setupWithViewPager(viewPager);
}
}
One of the fragments used on the main screen:
public class AnimacoesFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
ArrayList<Item> exemploItemList = new ArrayList<Item>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.animacoes_fragment, container, false);
TextView tv = view.findViewById(R.id.text1);
tv.setText("Você está na terceira aba");
exemploItemList.add(new Item(R.drawable.ic_android, "Line1", "line2"));
exemploItemList.add(new Item(R.drawable.ic_desktop_mac, "Line2", "line3"));
exemploItemList.add(new Item(R.drawable.ic_laptop_windows, "Line4", "line5"));
mRecyclerView = (RecyclerView) view.findViewById(R.id.AnimacaoRecyclerView);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(llm);
ItemAdapter adapter = new ItemAdapter(exemploItemList);
mAdapter = adapter;
mRecyclerView.setAdapter(mAdapter);
return view;
}
}
And its layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/AnimacaoRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp"
android:scrollbars="vertical" />
</LinearLayout>
This is what I'm trying to show on that RecyclerView (later will be the real thing, now it's just a test):
public class Item {
private int mImageResource;
private String text1;
private String text2;
public Item(int mImageResource, String text1, String text2) {
this.mImageResource = mImageResource;
this.text1 = text1;
this.text2 = text2;
}
public int getmImageResource() {
return mImageResource;
}
public void setmImageResource(int mImageResource) {
this.mImageResource = mImageResource;
}
public String getText1() {
return text1;
}
public void setText1(String text1) {
this.text1 = text1;
}
public String getText2() {
return text2;
}
public void setText2(String text2) {
this.text2 = text2;
}
}
It's layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="4dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#string/imagem"
android:padding="2dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="50dp"
android:layout_marginTop="0dp"
android:text="#string/line1"
android:textColor="#000000"
android:textSize="20sp"
android:textStyle="bold"
android:id="#+id/textView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="50dp"
android:layout_marginTop="28dp"
android:text="#string/line2"
android:textSize="15sp"
android:textStyle="bold"
android:id="#+id/textView2"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
Finally, the adapter used to convert the list:
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder> {
private ArrayList<Item> mItemList;
public static class ItemViewHolder extends RecyclerView.ViewHolder{
public ImageView mImageView;
public TextView mTextView1;
public TextView mTextView2;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageView);
mTextView1 = itemView.findViewById(R.id.textView);
mTextView2 = itemView.findViewById(R.id.textView2);
}
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
ItemViewHolder ivh = new ItemViewHolder(v);
return ivh;
}
public ItemAdapter(ArrayList<Item> itemList){
mItemList = itemList;
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
Item currentItem = mItemList.get(position);
holder.mImageView.setImageResource(currentItem.getmImageResource());
holder.mTextView1.setText(currentItem.getText1());
holder.mTextView2.setText(currentItem.getText2());
}
#Override
public int getItemCount() {
return mItemList.size();
}
}
First of all, check your fragment layout file. The linear layout parent orientation set to 'horizontal' and width of it's child views ('textview' & 'recyclerview') is match parent. This won't work.
Try to initialize your recyclerview adapter in 'onCreate' and use 'notifyDataSetChanged()' after setting up the adapter with recyclerview.
i have an Activity with tabLayout, each tab is represented by a Fragment (i have three fragments : Home, Caegories and my account), so i want to display on the HomeFragment an horizontal RecyclerView,everything works well but the RecyclerView doesn't work, where i get this eroor :
E/RecyclerView: No adapter attached; skipping layout.
I havre already tested this solution but i got nothing.
this what i did:
First: ActivityMain and xml layout:
private ArrayList<OfferItem> dataList;
private RecyclerView myRecycler;
private View fragmentViewLayout;
private LastOffersRecyclerAdapter listAdapter;
//......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setViewPager();
setTabIcons();
mTabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int tabPoaition = tab.getPosition();
if(tabPoaition == 0){
View view = tab.getCustomView();
TextView tabTextView = (TextView)view.findViewById(R.id.tabRoot);
tabTextView.setTextColor(Color.parseColor("#ef4437"));
tabTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_home_red, 0, 0);
}
else if(tabPoaition ==1){
View view = tab.getCustomView();
TextView tabTextView = (TextView)view.findViewById(R.id.tabRoot);
tabTextView.setTextColor(Color.parseColor("#ef4437"));
tabTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_category_red, 0, 0);
}
else{
View view = tab.getCustomView();
TextView tabTextView = (TextView)view.findViewById(R.id.tabRoot);
tabTextView.setTextColor(Color.parseColor("#ef4437"));
tabTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_person_red, 0, 0);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
int tabPoaition = tab.getPosition();
if(tabPoaition == 0){
View view = tab.getCustomView();
TextView tabTextView = (TextView)view.findViewById(R.id.tabRoot);
tabTextView.setTextColor(Color.parseColor("#bdbcbc"));
tabTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_home_gray, 0, 0);
}
else if(tabPoaition ==1){
View view = tab.getCustomView();
TextView tabTextView = (TextView)view.findViewById(R.id.tabRoot);
tabTextView.setTextColor(Color.parseColor("#bdbcbc"));
tabTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_category_gray, 0, 0);
}
else{
View view = tab.getCustomView();
TextView tabTextView = (TextView)view.findViewById(R.id.tabRoot);
tabTextView.setTextColor(Color.parseColor("#bdbcbc"));
tabTextView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_person_gray, 0, 0);
}
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
fragmentViewLayout = getLayoutInflater().inflate(R.layout.fragment_one, null);
listAdapter = new LastOffersRecyclerAdapter(this,dataList);
myRecycler = (RecyclerView)fragmentViewLayout.findViewById(R.id.my_list_recycler);
myRecycler.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false));
myRecycler.setItemAnimator(new DefaultItemAnimator());
myRecycler.setAdapter(listAdapter);
createSampleData();
}
///...
private void createSampleData(){
dataList = new ArrayList<OfferItem>();
OfferItem itm;
for(int i =0 ;i<10 ; i++){
itm = new OfferItem(i,"business_logo.png","offer_img.png","La Piscope","Fes");
dataList.add(itm);
}
listAdapter.notifyDataSetChanged();
}
activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.biliki.biliki.bilikiapp.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/my_home_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabBackground="?attr/selectableItemBackground"
/>
</android.support.design.widget.AppBarLayout>
<include
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:layout_constraintTop_toBottomOf="#id/my_home_app_bar"
app:layout_constraintLeft_toLeftOf="parent"
layout="#layout/content_main" />
</android.support.constraint.ConstraintLayout>
Second : my AdapterClass
LastOffersRecylerAdapter.java
public class LastOffersRecyclerAdapter extends RecyclerView.Adapter<LastOffersRecyclerAdapter.OffersItemHolder> {
private Context context;
private ArrayList<OfferItem> dataList;
public LastOffersRecyclerAdapter(Context context, ArrayList<OfferItem> dataList) {
this.context = context;
this.dataList = dataList;
}
#Override
public OffersItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.last_offers_item,parent,false);
OffersItemHolder offHolder = new OffersItemHolder(v);
return offHolder;
}
#Override
public void onBindViewHolder(OffersItemHolder holder, int position) {
OfferItem item = dataList.get(position);
int logoResourceId = context.getResources().getIdentifier(item.getLogoUrl(), "drawable", context.getPackageName());
int offerImgResourceId = context.getResources().getIdentifier(item.getOfferImgUrl(), "drawable", context.getPackageName());
holder.busniessLogo.setImageResource(logoResourceId);
holder.offerImg.setImageResource(offerImgResourceId);
holder.offer_business_city.setText(item.getBusiness_name() + "| "+item.getBusiness_city());
}
#Override
public int getItemCount() {
return dataList.size();
}
public class OffersItemHolder extends RecyclerView.ViewHolder{
public ImageView offerImg;
public ImageView busniessLogo;
public TextView offer_business_city;
public OffersItemHolder(View itemView) {
super(itemView);
this.offerImg = itemView.findViewById(R.id.offer_img);
this.busniessLogo = itemView.findViewById(R.id.business_logo);
this.offer_business_city = itemView.findViewById(R.id.business_name_city);
}
}
and this is the xml layout for HomeFragment
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<RelativeLayout
android:id="#+id/title_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.biliki.biliki.bilikiapp.uitemplate.font.RobotoTextView
android:id="#+id/itemTitle"
android:paddingLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_toLeftOf="#+id/btnMore"
android:text="#string/lastoffersTitle" />
<Button
android:id="#+id/btnMore"
style="#style/allButtonsstyle"
android:layout_width="65dp"
android:layout_height="42dp"
android:textAlignment="gravity"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="#string/moreLastOffers" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_list_recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="#id/title_layout" />
</android.support.constraint.ConstraintLayout>
the TextView and the button are displayed but the RecyclerView not.
could you please resolve this? thnak you.
UPDATE:
the content_main xml file contains the tabLayout ViewPager :
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="#layout/activity_main">
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabs_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
As Mr. Mike M mentioned, i have moved the code to the HomeFragment Class, and it works.
this is the HomeFragment class:
public class HomeFragment extends Fragment {
public static final String TITLE = "Accueil";
private RecyclerView myRecycler;
private LastOffersRecyclerAdapter listAdapter;
private ArrayList<OfferItem> dataList;
public static HomeFragment newInstance() {
return new HomeFragment ();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
createSampleData();
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
listAdapter = new LastOffersRecyclerAdapter(getContext(),dataList);
myRecycler = rootView.findViewById(R.id.my_list_recycler);
myRecycler.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
myRecycler.setItemAnimator(new DefaultItemAnimator());
myRecycler.setAdapter(listAdapter);
return rootView;
}
private void createSampleData(){
dataList = new ArrayList<OfferItem>();
OfferItem itm;
for(int i =0 ;i<10 ; i++){
itm = new OfferItem(i,"business_logo.png","offer_img.png","La Piscope","Fes");
dataList.add(itm);
}
}
}
I have a simple listView via a custom adapter. Each row in the list view is composed of a ImageButton and TextView.
The idea is to change the ImageButton when user taps on it and it does not work. However, ImageButton changes for the views that are scrolled and recycled. I mean, when user scrolls down the list and comes back to the top and tap on the ImageButton it works as expected for those rows that were scrolled and back again.
Can you guys help me out what i'm missing? I'm extremely new to Android and have been stuck around this for about a week now trying to fix this.
Here's the APK for the sample test app:
https://www.dropbox.com/s/pzlahtqkgj010m8/app-ListViewExample.apk?dl=0
Here are the relevant parts of my code:
avtivity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
/>
</RelativeLayout>
and to render the single row in the ListView the following xml is utilized:
single_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:src="#drawable/b"
android:layout_weight="2"
style="#style/ListView.first"
android:layout_gravity="center"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView"
android:layout_weight="10"
android:layout_gravity="center"
/>
</LinearLayout>
coming to the Java code,
MainActivity.java is
public class MainActivity extends AppCompatActivity {
String[] titles;
ListView list;
private listViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
titles = res.getStringArray(R.array.titles);
list = (ListView) findViewById(R.id.listView);
adapter = new listViewAdapter(this, titles);
list.setAdapter(adapter);
}
}
and the custom adapter listViewAdapter.java look like this
class sListItem {
public ImageButton button;
public TextView text;
public boolean active;
}
public class listViewAdapter extends ArrayAdapter<String> {
private final String[] titles;
Context context;
private int size = 15;
public sListItem mp[] = new sListItem[size];
public listViewAdapter(Context context, String[] titles) {
super(context, R.layout.single_row, R.id.imageButton, titles);
this.context = context;
this.titles = titles;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, parent, false);
if(mp[position] == null)
mp[position] = new sListItem();
mp[position].button = (ImageButton) row.findViewById(R.id.imageButton);
mp[position].button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp[position].active = !mp[position].active;
setIcon(position, mp[position].active);
}
});
mp[position].text = (TextView) row.findViewById(R.id.textView);
mp[position].text.setText(titles[position]);
setIcon(position, mp[position].active);
return row;
}
private void setIcon(int position, boolean active) {
Drawable drawable;
if(active){
drawable = getContext().getResources().getDrawable(R.drawable.a);
} else {
drawable = getContext().getResources().getDrawable(R.drawable.b);
}
mp[position].button.setImageDrawable(drawable);
}
}
EDIT: Added link to sample test app.
You should tell adapter to update by calling notifydatasetchanged in the click listener
mp[position].button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp[position].active = !mp[position].active;
setIcon(position, mp[position].active);
notifydatasetchanged();
}
});
I'm in the process of learning android app development however I have come to an impasse. My RecyclerView is picking up how many items are in my String array however it is not showing the actual data in text1, any help would be much appreciated.
This is my adapter
public class EventCalenderAdapter extends RecyclerView.Adapter<EventCalenderAdapter.ViewHolder> {
static String[] fakeData = new String[] {
"One","Two","Three","Four","Five","Ah..Ah..Ah"
};
static class ViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView titleView;
public ViewHolder(CardView card) {
super(card);
cardView = card;
titleView = (TextView) card.findViewById(R.id.text1);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
CardView v = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.event_task, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.titleView.setText(fakeData[i]);
}
#Override
public int getItemCount() {
return fakeData.length;
}
This is the corresponding XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:event_view="http://schemas.android.com/apk/res-auto"
android:layout_height="100dp"
android:layout_width="match_parent"
android:id="#+id/event_view"
android:layout_marginTop="#dimen/task_card_half_spacing"
android:layout_marginBottom="#dimen/task_card_half_spacing"
android:layout_marginLeft="#dimen/gutter"
android:layout_marginRight="#dimen/gutter"
android:layout_gravity="center"
android:elevation="#dimen/task_card_elevation"
android:foreground="?android:attr/selectableItemBackground"
event_view:cardCornerRadius="0dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/image"
android:scaleType="centerCrop"
android:layout_alignParentLeft="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Medium.Inverse"
android:id="#+id/text1"
android:maxLines="1"
android:ellipsize="end"
android:padding="10dp"
android:layout_alignTop="#+id/image"
android:layout_toRightOf="#+id/image"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
style="#android:style/TextAppearance.Inverse"
android:id="#+id/text2"
android:maxLines="3"
android:ellipsize="end"
android:padding="10dp"
android:layout_alignStart="#+id/text1"
android:layout_below="#+id/text1"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
and this is my fragment
public class EventCalenderFragment extends Fragment {
RecyclerView recyclerView;
EventCalenderAdapter adapter;
public EventCalenderFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new EventCalenderAdapter();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_event_calender, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recycler);
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return v;
}
Hm... everything looks ok, can you try setting this to it:
android:textColor="#000000"