I'm cant get the onclicklistener to work with fragments. I've searched stackoverflow and tried all the tips but i still cant get it to work. So i do my first post here. I've tried adding android:focusable="false", android:clickable="false" and android:descendantFocusability="blocksDescendants" to the layouts with no luck. Ive removed them because they make no difference. I've tried other solutions as well but none of them works. This is my first post so if i posted something wrong let me know and ill redo it, I've borrowed someones customlist just to get a working example.
Here is one of the fragments i want a clickable list in
public class ActivitiesFragment extends Fragment {
ListView list;
String[] maintitle ={
"Aktivitet 1","Aktivitet 2",
"Aktivitet 3","Aktivitet 4",
"Aktivitet 5",
};
String[] subtitle ={
"A","B",
"C","D",
"E",
};
Integer[] imgid={
R.drawable.ic_dashboard_black_24dp,R.drawable.ic_dashboard_black_24dp,
R.drawable.ic_dashboard_black_24dp,R.drawable.ic_dashboard_black_24dp,
R.drawable.ic_dashboard_black_24dp,
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_activities, container, false);
MyListAdapter adapter = new MyListAdapter(getActivity(), maintitle, subtitle,imgid);
list = (ListView) rootView.findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0) {
Toast.makeText(getActivity().getApplicationContext(),"One",Toast.LENGTH_SHORT).show();
}
else if(position == 1) {
Toast.makeText(getActivity().getApplicationContext(),"Two",Toast.LENGTH_SHORT).show();
}
else if(position == 2) {
Toast.makeText(getActivity().getApplicationContext(),"Three",Toast.LENGTH_SHORT).show();
}
else if(position == 3) {
Toast.makeText(getActivity().getApplicationContext(),"Four",Toast.LENGTH_SHORT).show();
}
else if(position == 4) {
Toast.makeText(getActivity().getApplicationContext(),"Five",Toast.LENGTH_SHORT).show();
}
}
});
return rootView;
}
}
Here is the Adapter:
public class MyListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] maintitle;
private final String[] subtitle;
private final Integer[] imgid;
public MyListAdapter(Activity context, String[] maintitle,String[] subtitle, Integer[] imgid) {
super(context, R.layout.mylist, maintitle);
// TODO Auto-generated constructor stub
this.context=context;
this.maintitle=maintitle;
this.subtitle=subtitle;
this.imgid=imgid;
}
public View getView(int position,View rowView,ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.mylist, null,true);
TextView titleText = (TextView) rowView.findViewById(R.id.title);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView subtitleText = (TextView) rowView.findViewById(R.id.subtitle);
titleText.setText(maintitle[position]);
imageView.setImageResource(imgid[position]);
subtitleText.setText(subtitle[position]);
return rowView;
}
}
The xml for the fragment:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="50dp"/>
</RelativeLayout>
The xml for the list:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp"/>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:textColor="#4d4d4d" />
<TextView
android:id="#+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_marginLeft="10dp" />
</LinearLayout>
</LinearLayout>
Here's whole implementation of RecyclerView with item click listener.
Fragment:
public class MyFragment extends Fragment implements ItemClickListener {
RecyclerView rvList;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_activities, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
rvList = view.findViewById(R.id.rvList);
ArrayList<ItemData> list = new ArrayList<>();
list.add(new ItemData("Aktivitet 1","A",R.drawable.ic_dashboard_black_24dp))
list.add(new ItemData("Aktivitet 2","B",R.drawable.ic_dashboard_black_24dp))
list.add(new ItemData("Aktivitet 3","C",R.drawable.ic_dashboard_black_24dp))
list.add(new ItemData("Aktivitet 4","D",R.drawable.ic_dashboard_black_24dp))
list.add(new ItemData("Aktivitet 5","E",R.drawable.ic_dashboard_black_24dp))
RVAdapter adapter = new RVAdapter(this, list);
rvList.setLayoutManager(new LinearLayoutManager(getContext()));
rvList.setAdapter(adapter);
}
#Override
public void onItemClicked(ItemData data, int position) {
// item click will be listened here
Toast.makeText(getContext(), String.valueOf(position), Toast.LENGTH_SHORT).show();
}
}
Fragment Layout: frag.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/rvList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Layout for the list: 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"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="5dp" />
<LinearLayout
android:layout_width="wrap_content"
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_marginLeft="10dp"
android:layout_marginTop="5dp"
android:padding="2dp"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#4d4d4d"
android:textStyle="bold" />
<TextView
android:id="#+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
RecyclerView ViewHolder:
public class RecyclerVH extends RecyclerView.ViewHolder {
private TextView titleText;
private ImageView imageView;
private TextView subtitleText;
public RecyclerVH(#NonNull View itemView) {
super(itemView);
titleText = itemView.findViewById(R.id.title);
imageView = itemView.findViewById(R.id.icon);
subtitleText = itemView.findViewById(R.id.subtitle);
}
void bind(ItemData data) {
titleText.setText(data.getMainTitle());
imageView.setImageResource(data.getImgId());
subtitleText.setText(data.getSubTitle());
}
}
RecyclerView Adapter:
public class RVAdapter extends RecyclerView.Adapter<RecyclerVH> {
private ArrayList<ItemData> list;
private ItemClickListener listener;
public RVAdapter(ItemClickListener listener, ArrayList<ItemData> list) {
this.list = list;
this.listener = listener;
}
#NonNull
#Override
public RecyclerVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecyclerVH(LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false));
}
#Override
public void onBindViewHolder(#NonNull final RecyclerVH holder, int position) {
holder.bind(list.get(position));
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClicked(list.get(holder.getAdapterPosition()),
holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return list.size();
}
}
interface ItemClickListener {
void onItemClicked(ItemData data, int position);
}
Update 1:
Add these lines to the root tag of item layout:
android:focusable="true"
android:clickable="true"
Like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:clickable="true"
android:orientation="horizontal">
...
</LinearLayout>
Time ago I had a similar problem, with an ImageView in my list item. My solution was changing android:focusable to false inside the ImageView block. I never knew why, but it worked fine.
Anyway, I strongly recommend to start using RecyclerView and ViewHolder pattern. https://developer.android.com/guide/topics/ui/layout/recyclerview
It's much more powerful, flexible and a major enhancement over ListView.
Related
I have a RecyclerView inside BottomSheetDialogFragment. The RecyclerView items touch working normally when it's scrolling slowly.
But when the RecyclerView is scrolled fast and after the list stops (without touching), than touching on any item doesn't work on fast touch. It needs double touching.
See in the below example gif, when touching on Andhra Pradesh it's working fine. After slow scrolling, touching on Haryana also works fine. Then doing a fast scroll and touching on Punjab doesn't work on the first touch. Touching again it works.
Following is the code:
OperatorListDialogFragment.java
package com.*;
import *;
public class OperatorListDialogFragment extends BottomSheetDialogFragment{
private static final String ARG_NAME = "item_name";
private static final String ARG_LOGO = "item_logo";
private Listener mListener;
private String header;
private Context mContext;
public static OperatorListDialogFragment newInstance(String[] name, int[] logo, String header) {
final OperatorListDialogFragment fragment = new OperatorListDialogFragment();
final Bundle args = new Bundle();
args.putStringArray(ARG_NAME, name);
args.putIntArray(ARG_LOGO, logo);
args.putString("header", header);
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_operator_list_dialog_list_dialog, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
TextView headerTV = view.findViewById(R.id.title);
headerTV.setText(getArguments().getString("header"));
final RecyclerView recyclerView = view.findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(new OperatorAdapter(getArguments().getStringArray(ARG_NAME), getArguments().getIntArray(ARG_LOGO)));
view.findViewById(R.id.dismiss).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
final Fragment parent = getParentFragment();
if (parent != null) {
mListener = (Listener) parent;
} else {
mListener = (Listener) context;
}
}
#Override
public void onDetach() {
mListener = null;
super.onDetach();
}
public interface Listener {
void onFilterSelected(String selected, String selectedQuery);
}
private class ViewHolder extends RecyclerView.ViewHolder {
final TextView text;
ImageView logo;
ViewHolder(LayoutInflater inflater, ViewGroup parent) {
// TODO: Customize the item layout
super(inflater.inflate(R.layout.fragment_operator_list_dialog_list_dialog_item, parent, false));
text = itemView.findViewById(R.id.tv_operator_name);
logo = itemView.findViewById(R.id.iv_recharge_provider_icon);
}
}
private class OperatorAdapter extends RecyclerView.Adapter<ViewHolder> {
private String[] mNames;
private int[] mLogos;
OperatorAdapter(String[] name, int[] logo) {
mNames = name;
mLogos = logo;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.text.setText(mNames[position]);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("clicked", "" + position);
}
});
}
#Override
public int getItemCount() {
return mNames.length;
}
}
}
dialog.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_height="match_parent"
android:layout_width="match_parent"
>
<ImageView
android:focusable="true"
android:clickable="true"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="Close"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:id="#+id/dismiss"
android:padding="14dp"
android:src="#drawable/ic_close_black_24dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/title"
app:layout_constraintTop_toTopOf="#id/dismiss"
app:layout_constraintBottom_toBottomOf="#id/dismiss"
app:layout_constraintLeft_toRightOf="#id/dismiss"
android:padding="14dp"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
tools:text="Select operator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<View
app:layout_constraintTop_toBottomOf="#id/dismiss"
android:background="#969696"
android:layout_width="match_parent"
android:layout_height="0.5dp"/>
<androidx.recyclerview.widget.RecyclerView
app:layout_constraintTop_toBottomOf="#id/dismiss"
app:layout_constraintBottom_toBottomOf="parent"
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
app:layout_constrainedHeight="true"
android:paddingTop="#dimen/list_item_spacing_half"
android:paddingBottom="#dimen/list_item_spacing_half"
tools:context=".fragments.OperatorListDialogFragment"
tools:listitem="#layout/fragment_operator_list_dialog_list_dialog_item" />
</androidx.constraintlayout.widget.ConstraintLayout>
recycler_item.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:gravity="center_vertical"
android:orientation="horizontal"
android:id="#+id/ll_operator_list_wrapper"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:visibility="gone"
android:layout_marginLeft="16dp"
android:id="#+id/iv_recharge_provider_icon"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginVertical="16dp"
android:layout_centerVertical="true"
android:src="#drawable/ic_bsnl_logo"
tools:visibility="visible"/>
<TextView
android:padding="16dp"
android:textColor="#212121"
android:textSize="14sp"
android:ellipsize="end"
android:id="#+id/tv_operator_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:text="BSNL"
android:layout_toRightOf="#+id/iv_recharge_provider_icon"
android:layout_centerInParent="true"/>
<View
android:layout_below="#id/iv_recharge_provider_icon"
android:id="#+id/divider0"
android:background="#eeeeee"
android:visibility="visible"
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_marginLeft="16dp"
android:layout_toRightOf="#+id/iv_recharge_provider_icon"
/>
</RelativeLayout>
add android:nestedScrollingEnabled="false" in RecyclerView
I am not getting any view from the recycler, I did some debug and the constructor of the adapter is called with items on its list, also the method
getItemCount()
but none of the rest seem to be executed.
I´ve been wandering around stack looking for this problem and i found different approaches to a solution, problem is none worked out for me, maybe I am just missing something i can´t see.
I read somewhere that it could be because the recycler view is inside an scroll view, but the solution given did not worked for me
my custom adapter:
public class CircumstancesAdapter extends RecyclerView.Adapter<CircumstancesAdapter.CircumstancesViewHolder> {
List<CatalogRespModel> circumList;
Context mContext;
public CircumstancesAdapter(List<CatalogRespModel> list, Context context) {
this.circumList = list;
this.mContext = context;
}
#Override
public CircumstancesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.row_item_circumstances, parent, false);
return new CircumstancesViewHolder(view);
}
#Override
public void onBindViewHolder(CircumstancesViewHolder holder, int position) {
holder.tvCircum.setText(circumList.get(position).get_Descripcion());
}
#Override
public int getItemCount() {
if(circumList != null) return circumList.size();
else return 0;
}
public class CircumstancesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
RadioButton rbCircum;
TextView tvCircum;
private Context context;
public CircumstancesViewHolder(View itemView) {
super(itemView);
rbCircum = (RadioButton) itemView.findViewById(R.id.rb_circ);
rbCircum.setOnClickListener(this);
tvCircum = (TextView) itemView.findViewById(R.id.tv_circ);
this.context = itemView.getContext();
}
#Override
public void onClick(View v) {
}
}
}
my container layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="20dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:id="#+id/text2"
android:text="#string/text_circ"
android:textSize="20sp"
android:textColor="#color/colorPrimaryshadow"/>
<RelativeLayout
android:id="#+id/placa"
android:layout_width="180dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:background="#drawable/placa">
<TextView
android:id="#+id/tv_plate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:layout_centerInParent="true"
android:text="#string/dummy"
android:textSize="40sp"
android:textColor="#android:color/black"/>
</RelativeLayout>
<ImageView
android:id="#+id/iv_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="true"
android:src="#drawable/conductora" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rview_circumstances"
android:layout_width="match_parent"
android:background="#fff"
android:orientation="vertical"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/boton_continuar_circustanciasa"
android:layout_marginTop="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/continuar"
android:layout_marginBottom="10dp"
android:elevation="30dp"
android:layout_gravity="center"/>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</FrameLayout>
my row layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:background="#fff"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:layout_height="wrap_content">
<RadioButton
android:id="#+id/rb_circ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#color/colorAccentDark"
android:gravity="center_vertical"
android:textSize="14sp" />
<TextView
android:layout_gravity="center_vertical"
android:gravity="center_vertical"
android:id="#+id/tv_circ"
android:textSize="14sp"
android:text="texto de prueba"
android:textColor="#color/colorAccentDark"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
and in my onCreateView inside the fragment:
recyclerView = (RecyclerView) rootView.findViewById(R.id.rview_circumstances);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
if(Catalogs.circumstancesArray.size() > 0){
adapter = new CircumstancesAdapter(Catalogs.circumstancesArray, getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
}
Note: I checked the List size and is greater than 0
Fragment code as requested:
public class CircumstancesFragment extends Fragment {
Button btnContinue;
TextView tvPlate;
private ImageView ivIndicator;
private static int iNumDevices;
IFragmentListener iFragmentListener;
private RecyclerView recyclerView;
RecyclerView.Adapter adapter;
private final static String TAGMap = CircumstancesFragment.class.getSimpleName();
public static final String TAG = "CircumstancesFragment.java";
public static CircumstancesFragment getInstance(Bundle bundle){
if(bundle != null){
iNumDevices = bundle.getInt("numDevices");
}
return new CircumstancesFragment();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if(context != null){
if(context instanceof IFragmentListener){
iFragmentListener = (IFragmentListener) context;
} else
throw new RuntimeException("el contexto no esta implementando la interfaz");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_circustancias_, container, false);
btnContinue = (Button) rootView.findViewById(R.id.boton_continuar_circustanciasa);
tvPlate = (TextView) rootView.findViewById(R.id.tv_plate);
recyclerView = (RecyclerView) rootView.findViewById(R.id.rview_circumstances);
ivIndicator = (ImageView) rootView.findViewById(R.id.iv_indicator);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
if(Catalogs.circumstancesArray.size() > 0){
adapter = new CircumstancesAdapter(Catalogs.circumstancesArray, getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
btnContinue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
try
{
iFragmentListener.notify(null, TAG);
} catch (Exception ex)
{
Log.d("error", ex.getMessage());
}
}
});
setLayout(iNumDevices);
return rootView;
}
private void setLayout(int i){
tvPlate.setText(FdccoreConstants.insuredArray.get(0).get_Placa_Vehiculo());
if(i== FdccoreConstants.ONE_DEVICE){
ivIndicator.setImageResource(R.drawable.conductora);
}else if(i== FdccoreConstants.TWO_DEVICE){
ivIndicator.setImageResource(R.drawable.only_conductor);
}
}
private void resetView(){
}
}
Please provide more code because Your layout and adapter is working fine.
I only changed Your model list to String.
Maybe in place when You checked list size and list.size() > 0 add
adapter.notifyDataSetChanged();
=====
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rview_circumstances);
recyclerView.setNestedScrollingEnabled(false);
recyclerView.setHasFixedSize(true);
list = new ArrayList<>();
list.add("asd");
list.add("sasf");
list.add("asasfasf");
list.add("asgagsad");
list.add("asgas");
list.add("asagasgd");
list.add("asreyeryd");
list.add("asgsheyd");
CircumstancesAdapter adapter = new CircumstancesAdapter(list, this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
solution: somehow in order to work with the scroll view i must add this line
compile 'com.android.support:recyclerview-v7:25.3.1'
compiling only appcompat-v7 wont work
I have a problem with spinner it do not let me select one item. I tried a lot of things and that still not working.
The picture shows that the spinner is in blank when the activity load
When I clicked the arrow it shows the items
but when I choose one, nothing happends.
<?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=".Activities.Inspeccion.DatosGeneralesActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
>
<TextView
android:id="#+id/tvSubestacionTitulo"
android:layout_below="#+id/imgLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/strSubestacion"
android:textSize="18sp"
android:textColor="#color/colorPrimaryDark"
android:textStyle="bold"
/>
<TextView
android:id="#+id/tvSubestacionDato"
android:layout_below="#+id/tvSubestacionTitulo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:text="Prueba"
/>
<Spinner
android:id="#+id/spinnerSubEstacion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tvSubestacionDato"
>
</Spinner>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
This is the Layout of the activity.
<?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:orientation="horizontal">
<TextView
android:id="#+id/tvNumeroOpcion"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:text="1"
android:textColor="#color/black"
android:textSize="14sp" />
<TextView
android:id="#+id/tvDescriptionOption"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:text="Guatemala"
android:textColor="#color/black"
android:textSize="14sp" />
</LinearLayout>
That is the custom layout for the spinner
Public class ComboAdapter extends BaseAdapter{
private List<Combo> combos;
private Activity activity;
private LayoutInflater inflater;
public ComboAdapter(List<Combo> combos, Activity activity) {
this.combos = combos;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return combos.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null){
view = inflater.inflate(R.layout.combo_list_item, null);
TextView tvId = (TextView) view.findViewById(R.id.tvNumeroOpcion);
TextView tvDescripcion = (TextView) view.findViewById(R.id.tvDescriptionOption);
tvId.setText(combos.get(position).getId());
tvDescripcion.setText(combos.get(position).getDescripcion());
}
return view;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getView(position, convertView,parent);
}
}
That is my Adapter
And below is my activity.
public class DatosGeneralesActivity extends AppCompatActivity {
private TextView tvSubestacionDato;
private List<Combo> listaCombo;
private Spinner spinnerSubestacion;
private ArrayAdapter<Combo> adapterSubestacion;
String seleccion;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datos_generales);
//Inicializando textos
tvSubestacionDato = (TextView) findViewById(R.id.tvSubestacionDato);
//Inicializanco listas
listaCombo = new ArrayList<>();
//Inivializando spinners
spinnerSubestacion = (Spinner) findViewById(R.id.spinnerSubEstacion);
AppService service = API.getCombos().create(AppService.class);
Call<List<Combo>> subestacionCall = service.getSubestacion();
subestacionCall.enqueue(new Callback<List<Combo>>() {
#Override
public void onResponse(Call<List<Combo>> call, Response<List<Combo>> response) {
listaCombo.clear();
listaCombo.addAll(response.body());
}
#Override
public void onFailure(Call<List<Combo>> call, Throwable t) {
}
});
//final ComboAdapter adapter = new ComboAdapter(listaCombo, DatosGeneralesActivity.this);
final ArrayAdapter<Combo> adapter = new ArrayAdapter<Combo>(this, R.layout.support_simple_spinner_dropdown_item, listaCombo);
spinnerSubestacion.setAdapter(adapter);
spinnerSubestacion.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
adapter.notifyDataSetChanged();
Toast.makeText(DatosGeneralesActivity.this, ""+position, Toast.LENGTH_SHORT).show();
tvSubestacionDato.setText(listaCombo.get(position).getDescripcion());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
Try this changes:
Call adapter like:
ComboAdapter adapter = new ComboAdapter(DatosGeneralesActivity.this,
R.layout.combo_list_item, R.id.tvDescriptionOption, listaCombo);
now in adapter class:
public ComboAdapter(Activity context,int resouceId, int textviewId, List<Combo> list){
super(context,resouceId,textviewId, list);
this.combos = list;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
Also inside your getView() method inflate layout like:
if (convertView == null){
view = inflater.inflate(R.layout.combo_list_item, parent , false);
I am trying to implement a Card view inside grid view. The grid view is showing perfectly; even when I touch on a grid view item it's showing nothing. But when I click on the text which is display below its work. I referred This but not working...
Thanks.
My code is as below,
// Contact_Backup.java
public class Contact_Backup extends AppCompatActivity {
#Bind(R.id.gridview)
GridView gridview;
String[] contact_screen_array;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_backup);
ButterKnife.bind(this);
contact_screen_array = getResources().getStringArray(R.array.TextScreen);
String[] contact_icon_array = getResources().getStringArray(R.array.IconScreen);
String concat = "\nContacts";
gridview.setAdapter(new Custom_Adapter(getApplicationContext(),contact_icon_array,contact_screen_array,concat));
}
}
//Custom_Adapter
public class Custom_Adapter extends BaseAdapter {
Context contaxt;
String[] Array_text;
String[] Array_icon;
String concat;
LayoutInflater inflater;
public Custom_Adapter(Context context,String[] Array_icon, String[] Array_text, String concat)
{
this.contaxt = context;
this.Array_text = Array_text;
this.Array_icon = Array_icon;
this.concat=concat;
inflater = (LayoutInflater)context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return Array_text.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Bind(R.id.Screen_icon)
Button Screen_icon;
#Bind(R.id.Screen_text)
TextView Screen_text;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) contaxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(contaxt);
grid = inflater.inflate(R.layout.new_app_card_layout, null);
ButterKnife.bind(this, grid);
Screen_text.setText(Array_text[position]+concat);
Screen_icon.setText(Array_icon[position]);
Typeface font = Typeface.createFromAsset(contaxt.getAssets(), "fonts/fontawesome-webfont.ttf" );
Screen_icon.setTypeface(font);
} else {
grid = (View) convertView;
}
grid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TAG::",""+position);
}
});
return grid;
}
}
// contact_backup.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="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/main_backgorund"
>
<RelativeLayout
android:background="#color/transparent"
android:padding="5.0dip"
android:id="#+id/top_bar_screen"
android:layout_weight="0.2"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:textColor="#color/newclr"
android:id="#+id/tvContacts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/contacts"
android:shadowColor="#000000"
android:shadowDx="1.0"
android:shadowDy="1.0"
android:shadowRadius="2.0"
android:layout_centerVertical="true" />
<TextView
android:textColor="#color/newclr"
android:id="#+id/tvLastBackup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/last_backup"
android:shadowColor="#000000"
android:shadowDx="1.0"
android:shadowDy="1.0"
android:shadowRadius="2.0"
android:layout_alignParentRight="true"
android:layout_centerVertical="true" />
</RelativeLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:id="#+id/v1"
android:layout_below="#+id/top_bar_screen"
android:background="#color/newclr"/>
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/swipe"
android:layout_below="#+id/v1"
android:paddingTop="20sp"
android:paddingLeft="10sp"
android:paddingRight="10sp"
android:layout_weight="0.6"
>
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:layout_height="wrap_content" />
</GridLayout>
<!-- com.startapp.android.publish.banner.Banner
android:id="#+id/startAppBanner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_weight="0.2"
android:layout_centerHorizontal="true" /-->
</RelativeLayout>
// new_app_card_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/fssr_card"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
card_view:cardBackgroundColor="#color/transparent"
>
<LinearLayout
android:gravity="center"
android:orientation="vertical"
android:id="#+id/Contacts_Button_Layout"
android:background="#drawable/linearlayout_normal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="-1.0dip"
android:layout_weight="1.0"
>
<Button
android:textSize="35.0sp"
android:textColor="#color/newclr"
android:layout_gravity="center"
android:id="#+id/Screen_icon"
android:background="#null"
android:padding="20sp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/fa_icon_contact"
android:drawablePadding="5.0dip"
android:textAllCaps="false" />
<TextView
android:textSize="15.0sp"
android:textColor="#color/white"
android:layout_gravity="center"
android:textAlignment="center"
android:id="#+id/Screen_text"
android:background="#color/newclr"
android:padding="5sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/contactsbackup"
android:textAllCaps="false"/>
</LinearLayout>
</android.support.v7.widget.CardView>
use this method for clicking on a gridview item:
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// your action when gridView item is clicked
}
});
Set the listener on the actual gridview object.
gridView.setOnItemClickListener(new OnItemClickListener()...);
Try this,
public class Contact_Backup extends AppCompatActivity {
#Bind(R.id.gridview)
GridView gridview;
String[] contact_screen_array;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_backup);
ButterKnife.bind(this);
contact_screen_array = getResources().getStringArray(R.array.TextScreen);
String[] contact_icon_array = getResources().getStringArray(R.array.IconScreen);
String concat = "\nContacts";
gridview.setAdapter(new Custom_Adapter(getApplicationContext(),contact_icon_array,contact_screen_array,concat));
gridview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<contact_screen_array.length;i++) {
Log.d("TAG::", "Position"+contact_screen_array[i]);
}
}
});
}
}
Finally, I succeed. here is the code.
Just use Textview instead of Button in // new_app_card_layout.xml.
Just Update it,
<TextView
android:textSize="35.0sp"
android:textColor="#color/newclr"
android:layout_gravity="center"
android:id="#+id/Screen_icon"
android:background="#null"
android:padding="20sp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/fa_icon_contact"
android:drawablePadding="5.0dip"
android:textAllCaps="false"
android:textAlignment="center" />
Thank You so much, All of you for help... :)
Try this i have updated your custom Adapter class.please check again with this updated code.
public class Custom_Adapter extends BaseAdapter {
Context contaxt;
String[] Array_text;
String[] Array_icon;
String concat;
LayoutInflater inflater;
public Custom_Adapter(Context context,String[] Array_icon, String[] Array_text, String concat)
{
this.contaxt = context;
this.Array_text = Array_text;
this.Array_icon = Array_icon;
this.concat=concat;
inflater = (LayoutInflater)context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return Array_text.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Bind(R.id.Screen_icon)
Button Screen_icon;
#Bind(R.id.Screen_text)
TextView Screen_text;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) contaxt
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(contaxt);
grid = inflater.inflate(R.layout.new_app_card_layout, null);
ButterKnife.bind(this, grid);
Screen_text.setText(Array_text[position]+concat);
Screen_icon.setText(Array_icon[position]);
Typeface font = Typeface.createFromAsset(contaxt.getAssets(), "fonts/fontawesome-webfont.ttf" );
Screen_icon.setTypeface(font);
grid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TAG::",""+position);
}
});
} else {
grid = (View) convertView;
grid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TAG::",""+position);
}
});
}
return grid;
}
}
Hope this helps you out !
I want to create a list of items that have a background image and a TextView. Although it creates the RecyclerView normally and sets the text, the background image doesn't set.
This is my Adapter Class
public class Casino_Adapter extends RecyclerView.Adapter<Casino_Adapter.ViewHolder> {
private Data[] mDataset;
private ClickListener clickListener;
public Context context;
// Provide a suitable constructor (depends on the kind of dataset)
public Casino_Adapter(Data[] myDataset) {
this.mDataset = myDataset;
this.context = context;
}
#Override
public Casino_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.casino_card_row, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final Context context = null;
// each data item is just a string in this case
public TextView mTextView;
public ImageView mImageView;
public CardView cardView;
//Typeface tf;
public ViewHolder(View v) {
super(v);
mTextView = (TextView) v.findViewById(R.id.text);
mImageView = (ImageView) v.findViewById(R.id.image);
cardView = (CardView) v.findViewById(R.id.card_view);
//cardView.setPreventCornerOverlap(false);
}
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(mDataset[position].getText());
holder.mImageView.setImageResource(mDataset[position].getImage());
}
public void setClickListener(ClickListener clickListener) {
this.clickListener = clickListener;
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
public interface ClickListener {
public void itemClicked(View view, int pos);
}
}
I have a Fragment Class where I want the RecyclerView to be.
public class CasinoFragment extends Fragment {
protected RecyclerView recyclerView;
protected RecyclerView.Adapter mAdapter;
protected RecyclerView.LayoutManager mLayoutManager;
public CasinoFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initial();
}
private void initial() {
final Data datas[] =
{
new Data("This is an item", R.drawable.ic_home_white_36dp),
new Data("This is an item 2", R.drawable.car),
new Data("asdasd`sdads", R.drawable.car),
new Data("This is an item 3", R.drawable.car)
};
mAdapter = new Casino_Adapter(datas);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_casino, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setAdapter(mAdapter);
return view;
}
}
And these are the Setters that I use.
public class Data {
int image;
String text;
public Data(String title, int backimage)
{
this.text = title;
this.image = backimage;
}
public String getText()
{
return text;
}
public int getImage()
{
return image;
}
public void setText()
{
this.text=text;
}
public void setImageID()
{
this.image = image;
}
}
Casino Row XML
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="8dp"
android:layout_margin="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#111111"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/image"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:background="#drawable/image_round"
android:src="#drawable/car" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/image"
android:id="#+id/rel_color"
android:background="#4c4c4c">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Μπύρα"
android:textColor="#fcfcfc"
android:textSize="30sp"
android:shadowColor="#000000"
android:shadowDx="3"
android:shadowDy="3"
android:shadowRadius="5"
android:id="#+id/text"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
The result I get is the following.
The reason why you aren't seeing your image, is because it isn't actually visible.
Your rel_color layout has the same size attributes as your ImageView.
If you want to display a layout above the ImageView, you just need to remove the background of it, otherwise the ImageView will be hidden.
Just Like that. but remember your images dimensions must be low. in my case i used 200x200
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/rl_menu_item"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_margin="5dp"
android:background="#android:color/transparent"
card_view:cardCornerRadius="4dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:id="#+id/img_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_blrr">
<ImageView
android:id="#+id/iv_icon"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_centerHorizontal="true"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"
android:adjustViewBounds="true"
android:background="#drawable/gray_circle"
android:padding="15dp"
android:scaleType="centerCrop"
android:src="#drawable/school" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#id/iv_icon"
android:layout_alignLeft="#id/iv_icon"
android:layout_alignRight="#id/iv_icon"
android:layout_alignStart="#id/iv_icon"
android:layout_below="#id/iv_icon"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="Your Favourite Place"
android:textColor="#android:color/black" />
</RelativeLayout>
</android.support.v7.widget.CardView>