Android RecyclerView inside popupwindow is not working? - java

popup_layout
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
app:cardUseCompatPadding="true">
<android.support.v7.widget.RecyclerView
android:id="#+id/landmarkView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_take_photo_surrounding"/>
</android.support.v7.widget.CardView>
Above code is design for How PopUpWindow will look like. I am opening this PopWindows on EditText.addTextChangedListener.onTextChanged() by calling following method:
private void popupWindow() {
int popupwindowHeight = LinearLayout.LayoutParams.WRAP_CONTENT;
LayoutInflater layoutInflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(
R.layout.dashboard_profile_popup_window, null);
final PopupWindow pwindow = new PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
pwindow.setHeight(popupwindowHeight);
pwindow.setFocusable(true);
pwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
//TODO dismiss settings
}
});
RecyclerView landmarkRecyclerView = (RecyclerView) layout.findViewById(R.id.landmarkView);
List<String> data = new ArrayList<String>();
data.add("my data");
data.add("set Data");
landmarkRecyclerView.setAdapter(new LandmarkRecyclerViewAdapter(data, getContext()));
pwindow.setWindowLayoutMode(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
pwindow.setHeight(1);
pwindow.setWidth(1);
pwindow.showAtLocation(layout, Gravity.NO_GRAVITY, mPoint.x, mPoint.y);
pwindow.showAsDropDown(place_pop_up);
}
But what I can see through above code is :
A blank PopUpWindow on Text change listener. What I am doing wrong here?
edit
Adding LandMarkRecyclerViewAdapter too
public class LandmarkRecyclerViewAdapter extends RecyclerView.Adapter<LandmarkRecyclerViewAdapter.ViewHolder> {
private Context mContext;
private List<String> mLocalityEntities;
public LandmarkRecyclerViewAdapter(List<String> localityEntityList, Context context){
this.mContext = context;
this.mLocalityEntities = localityEntityList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.landmark_view_adapter, null);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if( null != mLocalityEntities.get(position)){
holder.mTextView.setText(mLocalityEntities.get(position).toString());
}
}
#Override
public int getItemCount() {
return mLocalityEntities.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
public ViewHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.landmarkText);
}
}
}

Related

How can I create Alert dialog list with different background between row

how can I set background odd and even row in alert dialog like this ?
AlertDialog.Builder builder = new AlertDialog.Builder(MenuRegister.this);
builder.setTitle("Pilih Tipe User");
builder.setItems(arrData, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
spinerUserType.setText(profesi.get(position).getName());
changeView(profesi.get(position).getId());
role = profesi.get(position).getId();
if (role.equalsIgnoreCase("4")) {
loadSpesialis();
}
}
}).show();
You would have to implement a custom view using builder.setView().
Then, if using a ListView for example, just use something like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ...;
}
convertView.setBackgroundColor(position % 2 ? Color.GREY : Color.WHITE);
...
}
cf https://stackoverflow.com/a/9697599/603270
You can set your own adapter instead of set items.
AlertDialog.Builder builder = new AlertDialog.Builder(TestActivity.this);
builder.setTitle("Pilih Tipe User");
// Create an ArrayAdapter from List
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, new String[]{"test1", "test2", "test3"}){
#Override
public View getView(int position, View convertView, ViewGroup parent){
// Get the current item from ListView
View view = super.getView(position,convertView,parent);
if(position %2 == 1)
{
// Set a background color for ListView regular row/item
view.setBackgroundColor(Color.parseColor("#FFB6B546"));
}
else
{
// Set the background color for alternate row/item
view.setBackgroundColor(Color.parseColor("#FFCCCB4C"));
}
return view;
}
};
builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
}
}).show();
In getView method
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.file_list_row, parent, false);
LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.layout_id);
//set the background color of alternative row
if (position % 2 == 0) {
linearLayout.setBackgroundColor(Color.parseColor("#BDBDBD"));
} else {
linearLayout.setBackgroundColor(Color.parseColor("#EEEEEE"));
}
return view;
}
In Your raw xml file
<?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="vertical">
<LinearLayout
android:id="#+id/layout_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
/* Your Views */
</LinearLayout>
</LinearLayout>
you must use from recyclerView and custom adapter like this :
private void selectCategoryDialog() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // before
dialog.setContentView(R.layout.chips_dialog_layout);
dialog.setCancelable(true);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
RecyclerView recyclerView = dialog.findViewById(R.id.recyclerView);
TextView dialogTitle = dialog.findViewById(R.id.dialog_title);
dialogTitle.setText(getResources().getString(R.string.category));
recyclerView.setLayoutManager(new LinearLayoutManager(this));
AdapterCategory _adapter = new AdapterCategory(this, placeCategories);
recyclerView.setAdapter(_adapter);
_adapter.setOnItemClickListener((view, obj, position) -> {
addCategoryChip(obj);
dialog.hide();
});
HelperFunctions.setFont(dialog
.findViewById(android.R.id.content), this, Constants.iranSansFont);
dialog.show();
dialog.getWindow().setAttributes(lp);
}
adapter:
public class AdapterCategory extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<PlaceCategory> items = new ArrayList<>();
private OnItemClickListener mOnItemClickListener;
private Typeface mTypeface;
public interface OnItemClickListener {
void onItemClick(View view, PlaceCategory obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
public AdapterCategory(Context context, List<PlaceCategory> items) {
this.items = items;
this.mTypeface = HelperFunctions.getTypeface(context);
}
public class OriginalViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public TextView title;
public View lyt_parent;
public OriginalViewHolder(View v) {
super(v);
image = v.findViewById(R.id.image);
title = v.findViewById(R.id.type_title);
lyt_parent = v.findViewById(R.id.lyt_parent);
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.chips_item, parent, false);
HelperFunctions.setFontForAdapter((ViewGroup) v, mTypeface);
vh = new OriginalViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof OriginalViewHolder) {
OriginalViewHolder view = (OriginalViewHolder) holder;
PlaceCategory p = items.get(position);
view.title.setText(p.toString());
view.lyt_parent.setOnClickListener(view1 -> {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(view1, items.get(position), position);
}
});
view.lyt_parent.setBackgroundColor(position % 2 == 0 ? Color.GRAY : Color.WHITE);
}
}
#Override
public int getItemCount() {
return items.size();
}
custom layout for dialog :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:background="#android:color/white"
android:orientation="vertical">
<TextView
android:id="#+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:padding="#dimen/spacing_large"
android:text="Contact List"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Title" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/spacing_middle"
android:scrollbars="vertical"
android:scrollingCache="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
i hope helped you

RecyclerView not populating on fragment

I have been trying to figure this problem out for quite a while now, but i just can't figure out what the problem is. The aim is to make a request to Songkick api (which is json), which will return the upcoming events of artist and populate it on the the fragment. The request works fine, but it doesn't come on the screen using recyclerView.
This is my xml:
<LinearLayout 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="com.example.artispot.fragments.FragmentEvents">
<android.support.v7.widget.RecyclerView
android:id="#+id/List"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
This is the Adapter:
public class AdapterEvents extends RecyclerView.Adapter<AdapterEvents.ViewHolderEvents> {
private LayoutInflater layoutInflater;
private String cls = "TAG";
private ArrayList<Events> listEvents = new ArrayList<>();
public AdapterEvents(Context context){
layoutInflater = LayoutInflater.from(context);
}
public void setListEvents(ArrayList<Events> listEvents){
this.listEvents = listEvents;
notifyItemRangeChanged(0,listEvents.size());
}
#Override
public ViewHolderEvents onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.custom_events,parent,false);
ViewHolderEvents viewHolder =new ViewHolderEvents(view);
return viewHolder;
}
//create an object for each textview
#Override
public void onBindViewHolder(ViewHolderEvents holder, int position) {
Events currentEvent = listEvents.get(position);
holder.DateTextView.setText(currentEvent.getStartDate());
// + "--"+ currentEvent.getEndDate()
holder.displayName.setText(currentEvent.getDisplayName());
holder.Venue.setText(currentEvent.getVenue());
}
#Override
public int getItemCount() {
return listEvents.size();
}
static class ViewHolderEvents extends RecyclerView.ViewHolder{
private TextView DateTextView;
private TextView displayName;
private TextView Venue;
public ViewHolderEvents(View itemView){
super(itemView);
DateTextView = (TextView) itemView.findViewById(R.id.DateTextView);
displayName = (TextView) itemView.findViewById(R.id.displayName);
Venue = (TextView) itemView.findViewById(R.id.Venue);
}
}
}
and this part is from my fragment class:
public void sendRequest(){
// Formulate the request and handle the response.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
getRequestUrl(),(String)null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse( JSONObject response) {
listEvents= parseJSONResponse(response);
adapterEvents.setListEvents(listEvents);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
requestQueue.add(request);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_events, container,false);
recyclerView = (RecyclerView)view.findViewById(R.id.List);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
adapterEvents = new AdapterEvents(getActivity());
recyclerView.setAdapter(adapterEvents);
return view;
}
I have been on this for about a few days, and it's sort of frustrating because it's my project that is due in a week time. Any sort of help will be much appreciated. Thanks in advance.

Android listview not being populated

I'm trying to populate a listview with the id android.id/list with some xml data.. The data is successfully requested and I get no errors when passing it to my Lazy Adapter and setting it to the listview.. Can somebody help me?
The request:
private void requestFeed() {
SimpleXmlRequest<StationList> simpleRequest = new SimpleXmlRequest<StationList>(Request.Method.GET, url, StationList.class,
new Response.Listener<StationList>()
{
#Override
public void onResponse(StationList response) {
list = response.getStationList();
buildFeed();
if(mSplashDialog != null) {
removeSplashScreen();
} else {
setReloadFeedButtonState(false);
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error Object
Log.d("TESTE", error.toString());
}
}
);
simpleRequest.setTag(SIMPLE_TAG);
queue = Volley.newRequestQueue(this);
queue.add(simpleRequest);
}
The buildFeed:
private void buildFeed() {
if(stations == null) {
stations = (ListView) findViewById(android.R.id.list);
adapter = new LazyAdapter(this, list);
stations.setAdapter(adapter);
}
adapter.notifyDataSetChanged();
}
The adapter:
public class LazyAdapter extends BaseAdapter {
private List<Station> stations;
private static LayoutInflater inflater = null;
public LazyAdapter(Activity activity, List<Station> stations) {
this.stations = stations;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return stations.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if(convertView == null)
vi = inflater.inflate(R.layout.list_row, null);
TextView name = (TextView) vi.findViewById(R.id.station_name);
TextView ct = (TextView) vi.findViewById(R.id.station_ct);
TextView cl = (TextView) vi.findViewById(R.id.station_cl);
Station tmp = stations.get(position);
name.setText(tmp.get_name());
ct.setText(tmp.get_ct());
cl.setText(tmp.get_lc().toString());
return vi;
}
}
the xml of the activity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/MainActivityLL"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="me...MainActivity" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:layout_weight="1"
android:listSelector="#drawable/list_row_selector" />
<TextView
android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAppearance="#android:style/TextAppearance.Medium"
android:text="#string/emptyList"
android:gravity="center" />
I've checked the stations list that comes in the response and is not empty.. I have all the data I need, but the listview is always showing the empty message from the textview with id android.id/empty ..
Remove android:id="#android:id/list"
Replace it with android:id="#+id/list"
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:layout_weight="1"
android:listSelector="#drawable/list_row_selector" />
Try to Use ViewHolder design pattern when you make custom adapter :
public class LazyAdapter extends BaseAdapter {
private List<Station> stations;
private Context context;
public LazyAdapter(Context context, List<Station> stations) {
this.stations = stations;
this.context=context;
}
public int getCount() {
return stations.size();
}
public Object getItem(int position) {
return stations.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_row, null);
holder.name = (TextView) convertView.findViewById(R.id.station_name);
holder.ct = (TextView) convertView.findViewById(R.id.station_ct);
holder.cl = (TextView) convertView.findViewById(R.id.station_cl);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(stations.get(position).get_name());
holder.ct.setText(stations.get(position).get_ct());
holder.cl.setText(stations.get(position).get_lc().toString());
return convertView;
}
class ViewHolder{
TextView name;
TextView ct;
TextView cl;
}
}

How to implement Favorite Button to my BaseAdapter ListView?

I'm learning Android SDK and I need some advices.
I have custom ListView with BaseAdapter and I want to implement some new feature - Favorite Button.
What I want to do is, when I press the Favorite Button, ListItem goes to the beginning of the list, Favorite image change and all that stuff will be saved in the SharedPrefs.
Someone tell me what I need to do, to make it works?
my existing code:
row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/layout_element_list"
>
<ImageView
android:id="#+id/icon"
android:layout_width="150dp"
android:padding="5dp"
android:layout_height="150dp"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px"
android:src="#drawable/radio" >
</ImageView>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/label"
android:paddingTop="20dp"
android:layout_gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:textAlignment="center"
android:text="RadioName"
android:textColor="#color/color1"
android:textSize="30dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView
android:id="#+id/label2"
android:layout_gravity="center_vertical"
android:layout_width="fill_parent"
android:layout_weight="1"
android:layout_height="fill_parent"
android:textAlignment="center"
android:text="Description.."
android:textColor="#color/color1"
android:textSize="15dp" />
<ImageView
android:id="#+id/favButton"
android:layout_weight="1"
android:layout_width="fill_parent"
android:padding="5dp"
android:layout_height="fill_parent"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="4px"
android:src="#drawable/fav_off" >
</ImageView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
BaseAdapter class:
public class RadioAdapter extends BaseAdapter
{
ArrayList<RadioStation> myList = new ArrayList<RadioStation>();
LayoutInflater inflater;
Context context;
public RadioAdapter(Context context, ArrayList<RadioStation> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public RadioStation getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.activity_menu_row, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.label, myList.get(position).getTitle());
mViewHolder.tvDesc = detail(convertView, R.id.label2, myList.get(position).getDescription());
mViewHolder.ivIcon = detail(convertView, R.id.icon, myList.get(position).getImgResId());
return convertView;
}
private TextView detail(View v, int resId, String text) {
TextView tv = (TextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
private ImageView detail(View v, int resId, int icon) {
ImageView iv = (ImageView) v.findViewById(resId);
iv.setImageResource(icon); //
return iv;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
}
}
RadioStation class:
public class RadioStation
{
public String title;
public String description;
public int imgResId;
//getters and setters
public static Comparator<RadioStation> comparatorByRadioName = new Comparator<RadioStation>()
{
#Override
public int compare(RadioStation radioStation, RadioStation radioStation2)
{
String name1 = radioStation.getTitle().toLowerCase();
String name2 = radioStation2.getTitle().toLowerCase();
return name1.compareTo(name2);
}
};
}
ActivityListView:
public class ActivityMenuList extends Activity implements AdapterView.OnItemClickListener
{
private ListView lvDetail;
private Context context = ActivityMenuList.this;
private ArrayList <RadioStation> myList = new ArrayList <RadioStation>();
private String[] names = new String[] { "one", "two", "three" };
private String[] descriptions = new String[] { "notset", "notset", "notset"};
private int[] images = new int[] { R.drawable.one, R.drawable.two, R.drawable.three };
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
getWindow().setBackgroundDrawableResource(R.drawable.bg1);
setContentView(R.layout.activity_menu_list);
lvDetail = (ListView) findViewById(R.id.list);
lvDetail.setOnItemClickListener(this);
getDataInList();
lvDetail.setAdapter(new RadioAdapter(context, myList));
}
private void getDataInList() {
for(int i=0;i<3;i++) {
RadioStation ld = new RadioStation();
ld.setTitle(names[i]);
ld.setDescription(descriptions[i]);
ld.setImgResId(images[i]);
myList.add(ld);
}
Collections.sort(myList, RadioStation.comparatorByRadioName);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
String item = names[i];
Intent e = new Intent(ActivityMenuList.this, ActivityRadioStation.class);
Bundle data = new Bundle();
data.putString("radiostation",item);
e.putExtras(data);
startActivity(e);
}
}
That's a lot of changes you have to do. Let's start with the basic.
Add a boolean to your RadioStation for the favorite state.
public boolean isFavorite;
Next on your getView add the favorite button click listener(add its reference to the viewholder too, but let's keep it simple this time)
public class RadioAdapter extends BaseAdapter
{
ArrayList<RadioStation> myList = new ArrayList<RadioStation>();
LayoutInflater inflater;
Context context;
ListView mListview;
public RadioAdapter(Context context, ArrayList<RadioStation> myList, ListView list) {
this.myList = myList;
this.context = context;
mListView = list;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public RadioStation getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.activity_menu_row, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.label, myList.get(position).getTitle());
mViewHolder.tvDesc = detail(convertView, R.id.label2, myList.get(position).getDescription());
mViewHolder.ivIcon = detail(convertView, R.id.icon, myList.get(position).getImgResId());
convertView.findViewById(R.id.favButton).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
myList.get(position).isFavorite=! myList.get(position).isFavorite;
//reorder mlist
notifyDataSetChanged();
//mListView. smoothscroll here
}
});
((ImageView) convertView.findViewById(R.id.favButton)).setImageResource(myList.get(position).isFavorite?R.drawable.favoriteOn:R.drawable.favoriteOff);
return convertView;
}
private TextView detail(View v, int resId, String text) {
TextView tv = (TextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
private ImageView detail(View v, int resId, int icon) {
ImageView iv = (ImageView) v.findViewById(resId);
iv.setImageResource(icon); //
return iv;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
}
}
I left commented what you should do on the listener. You should be able to continue from here.
When you create your adapter pass the list as the last parameter on the constructor.
Edited: Removed interface. No need to use it here.

Multiple click in listview android

I am doing an app which shows a database users. I want add differents actions depends on zone of click in each element.
This is my actually code for this list view:
<?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="5dp" >
<ImageView
android:id="#+id/logo"
android:layout_width="100px"
android:layout_height="100px"
android:layout_marginLeft="5px"
android:layout_marginRight="20px"
android:layout_marginTop="5px"
android:src="#drawable/icondatabase" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.91"
android:text="Not users"
android:textSize="70px" />
<ImageView
android:id="#+id/imageAction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</LinearLayout>
and this the class which creates list:
public class UsersArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
private final List<Bitmap> listImages;
private final String process;
public UsersArrayAdapter(Context context, String[] values,
List<Bitmap> listImages, String process) {
super(context, R.layout.users, values);
this.context = context;
this.values = values;
this.listImages = listImages;
this.process = process;
}
public UsersArrayAdapter(Context context, String[] values) {
super(context, R.layout.users, values);
this.context = context;
this.values = values;
this.listImages = null;
this.process = "";
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.users, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
ImageView imageView2 = (ImageView) rowView
.findViewById(R.id.imageAction);
textView.setText(values[position]);
if (listImages == null) {
imageView.setImageResource(R.drawable.iconenroll);
} else {
imageView.setImageBitmap(listImages.get(position));
if (process.compareTo("users") == 0) {
imageView2.setImageResource(android.R.drawable.ic_menu_delete);
}
if (process.compareTo("verify") == 0) {
imageView2.setImageResource(android.R.drawable.ic_media_play);
}
}
return rowView;
}
}
How can i do to if user clicks in imageaction do some action and if clicks in textview do other one?
thanks
you can set onclicklisteners for both textview and imageview . but you have to use ViewHolders.
static class ViewHolder{
ImageView imageone;
ImageView imagetwo;
TextView tvone;
}
in the adapter getview
final ViewHolder holder;
if(convertView == null){
convertView = layoutInflater.inflate(R.layout.custom_view_new, null);
holder = new ViewHolder();
........
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.imageone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// do ur work
}
}
holder.tvone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// do ur work
}
}
By default textView is not clickable, you have to set android:clickable="true" in your textView.
textView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO
}
});
imageView2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO
}
});
Try this :
static class ViewHolder {
public TextView searchpageNameTextView;
public ImageView ivStar;
}
Inside getView method:
View rowView = convertView;
// reuse views
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.demo, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.searchpageNameTextView = (TextView) rowView.findViewById(R.id.tvName);
viewHolder.ivStar = (ImageView) rowView.findViewById(R.id.ivgstar);
rowView.setTag(viewHolder);
}
final ViewHolder holder = (ViewHolder) rowView.getTag();
holder.searchpageNameTextView.setText(text you want to set);
holder.image.setImageBitmap(your bitmap);
holder.searchpageNameTextView.setOnClickListener(do your stuffs);
holder.image.setOnClickListener(do your stuffs);
return rowView;
Above code is working fine. I implemented it in my app.
You can just setOnClickListeners for the respective elements in getView() of your custom BaseAdapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.search_result_item, null);
}
final int fPos=position;
ImageView image1=(ImageView)convertView.findViewById(R.id.img1);
TextView tv1=(TextView)convertView.findViewById(R.id.tv1);
image1.setOnClickListener(new onClickListener(){
#Override
public void onClick(View v) {
Log.i("CustomAdapter", "List item "+ fPos +" had it's image clicked");
}
});
tv1.setOnClickListener(new onClickListener(){
#Override
public void onClick(View v) {
Log.i("CustomAdapter", "List item "+ fPos +" had it's text view clicked");
}
});
return convertView;
}
Sadly setting onClick methods of these views make the List Row itself un-clickable since they take all focus. If youw ant your whole row to be clickable and have a seperate action for that with an onItemClickListener of your ListView, you will have to add android:descendantFocusability="blocksDescendants" tag to the parent layout of the imageview/textview and set
android:focusable="false"
android:focusableInTouchMode="false"
for the ImageView and TextView in xml.

Categories