Custom Spinner setOnItemSelectedListener is not triggered - android

I have a spinner and an adapter.
Spinner spinner = findViewById(R.id.spinner);
SpinnerAdapter adapter = new SpinnerAdapter(this, R.layout.spinner_item, getList());
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Log.e("PROGRAM", "Selected |" + position + "|");
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
}
});
This is my SpinnerAdapter dropdown creation
#Override
public View getDropDownView(final int position, final View convertView, final ViewGroup parent)
{
MyObject object = getItem(position);
View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_object_item, parent, false);
((TextView) layout.findViewById(R.id.name)).setText(object.getName());
return layout;
}
And my_object_item xml is
<?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:id="#+id/item"
android:clickable="true"
android:focusable="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/icon"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/name"/>
</LinearLayout>
For some reason I can not get setOnItemSelectedListener to trigger. Should I be adding listener to every component of my_object_item and from there triggering setOnItemSelectedListener?

As you have suggested above, you can try to do things manually, by adding a listener that listens to clicks on either the TextView or ImageView (the components of each item in the spinner dropdown view), and then update the spinner view according to what was selected.
1) MainActivity.class:------------
public class MainActivity extends AppCompatActivity implements Listener {
private Spinner sp;
private SpinnerAdapter spinnerAdapter;
private String[] name = {
"N1",
"N2",
"N3",
"N4"
};
private int[] icon = {
R.drawable.icon,
R.drawable.icon,
R.drawable.icon,
R.drawable.icon
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
sp = (Spinner) findViewById(R.id.sp);
spinnerAdapter = new SpinnerAdapter(getApplicationContext() , name , icon , name[0] , icon[0] , MainActivity.this); // TODO: Every time the activity (spinner) is created, the item selected is changed
//TODO to the initial name[0] and icon[0]. In order to solve this issue you can save the selected item (name and icon) value in sharedPreferences and use the saved value every time the spinner is opened.
sp.setAdapter(spinnerAdapter);
}
#Override
public void clicked(int position) {
if(spinnerAdapter != null){
spinnerAdapter.setCurrentNameIcon(name[position] , icon[position]);
}
}
2) SpinnerAdapter.class:---------------
public class SpinnerAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
private Listener callback;
private String current_name;
private int current_icon;
private String[] name;
private int[] icon;
public SpinnerAdapter(#NonNull Context context , String[] name_ , int[] icon_ , String inital_name_ , int initial_icon_ , Listener l) {
mContext = context;
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(l != null){
callback = l;
}
name = name_;
icon = icon_;
current_name = inital_name_;
current_icon = initial_icon_;
}
public int getCount() {
return name.length;
}
public Object getItem(int position) {
return name[position];
}
public long getItemId(int position) {
return position;
}
#NonNull
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final TextView tv;
ImageView iv;
if (convertView == null) {
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.my_object_item, parent , false);
}
}
tv = (TextView) view.findViewById(R.id.name);
tv.setText(current_name);
iv = (ImageView) view.findViewById(R.id.icon);
iv.setBackground(mContext.getResources().getDrawable(current_icon));
return view;
}
#Override
public View getDropDownView(final int position, #Nullable View convertView, #NonNull final ViewGroup parent) {
View view = convertView;
final TextView tv;
ImageView iv;
if (convertView == null) {
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.my_object_item, parent , false);
}
}
tv = (TextView) view.findViewById(R.id.name);
tv.setText(name[position]);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(callback != null){
//https://stackoverflow.com/questions/7287195/android-spinner-close?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
View root = parent.getRootView();
root.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
root.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
callback.clicked(position);
}
}
});
iv = (ImageView) view.findViewById(R.id.icon);
iv.setBackground(mContext.getResources().getDrawable(icon[position]));
iv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(callback != null){
//https://stackoverflow.com/questions/7287195/android-spinner-close?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
View root = parent.getRootView();
root.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
root.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
callback.clicked(position);
}
}
});
return view;
}
public void setCurrentNameIcon(String name , int icon){
current_name = name;
current_icon = icon;
this.notifyDataSetChanged();
}
}
3) Listener interface:------------
public interface Listener {
public void clicked(int position);
}
4) main_activity.xml:---------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sp">
</Spinner>
</android.support.constraint.ConstraintLayout>
5) my_object_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="60dp"
android:id="#+id/item"
android:clickable="true"
android:focusable="true">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/icon"
android:layout_gravity="center_vertical"
android:id="#+id/icon"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center_vertical"
android:gravity="center"
android:text="HI"
android:id="#+id/name"/>
</LinearLayout>

Related

How to set onClickListener for custom ListView

I have created a custom ListView, where the layout is definited in two XML, one which contain the definition of the ListView in a layout
For example 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">
<LinearLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/myListView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</RelativeLayout>
The other part of the XML is in another file, for example custom_list.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="wrap_content"
android:background="#drawable/list_row_selector">
<LinearLayout
android:id="#+id/photoList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/takePhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="#drawable/camera"/>
</LinearLayout>
</RelativeLayout>
In my activity i have declared actvivity_main.xml as main layout:
public class MainActivity extends AppCompatActivity{
private List<CustomRow> imageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cmp_details);
/* Initialization structures, variable, ecc */
ListView lv = (ListView) findViewById(R.id.imageList);
adapter = new CustomList(this, imageList);
lv.setAdapter(adapter);
}
/* Add element list in ListView */
private void addList(int idC){
CustomRow cr = new CustomRow();
cr.setId(idC);
cr.setTitle("xxx "+ (idC+1));
cr.setThumbnailUrl(R.drawable.no_image);
imageList.add(cr);
adapter.notifyDataSetChanged();
}
private void takePhoto(){
//Do something
}
}
Custom List.java
public class CustomList extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<CustomRow> ListItem;
private ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomList(Activity activity, List<CustomRow> listPhotoItems) {
this.activity = activity;
this.ListItem = listPhotoItems;
}
#Override
public int getCount() {
return ListItem.size();
}
#Override
public Object getItem(int location) {
return ListItem.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.custom_list, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
ImageView thumbNail = (ImageView) convertView.findViewById(R.id.thumbnail);
TextView title = (TextView) convertView.findViewById(R.id.title);
CustomRow m = ListItem.get(position);
thumbNail.setImageResource(m.getThumbnailUrl());
title.setTag(m.getId());
title.setText(m.getTitle());
return convertView;
}
}
Now I have to implement the OnClickListener of takePhoto, how I can do this ?
How I can bind onClickListener from the activity ?
I tried this solution but not work...
you could use setonitemclicklistener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
imageList.get(position); // here you will get the clicked item from
//your imagelist and you can check by getting a title by using this
String title= imageList.get(position).getTitle();
if(title.equals("you title to match")){
//do your action or you can get a particular position and click there
}
}
});
This is the final solution, I have solve my problem with this code:
lv.setAdapter(adapter);
lv.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
View convertView = v;
final ImageView photo = (ImageView) convertView.findViewById(R.id.takePhoto);
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CmpDetails.this, "Click", Toast.LENGTH_SHORT).show();
}
});
return false;
}
});
tv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
list.get(position);
String str= list.get(position).getTitle();
if(str.equals("")){
//put your code here
}
}
});
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView tv = (TextView) v.findViewById(R.id.textView1);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do your code on click event
}
});
return super.getView(position, convertView, parent);
}

Implement click only on image not on text in custom listview

I have a custom Listview where it contains image & text and implemented the OnItemClickListener for list which should work only for image not for text. OnItemClick is working fine for image but there is a Fatal Exception when i click on text. Additionally image will be visible in list if it exists else it will be hide.
Tried with android:focusable="false", android:clickable="false" but still i am getting the below exception
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable.getBitmap()' on a null object reference
OnItemClick:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ImageView imageView1 = (ImageView) view.findViewById(R.id.imageList);
final GlideBitmapDrawable bitmapDrawable = (GlideBitmapDrawable) imageView1.getDrawable();
final Bitmap yourBitmap = bitmapDrawable.getBitmap();
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourBitmap);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
How can i implement click only on image?
In your custom layout xml, set
android:descendantFocusability="blocksDescendants"
to your root layout.
Edit
Check my Custom ListView.
listitem.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:gravity="center"
android:descendantFocusability="blocksDescendants"
android:layout_height="60dp">
<ImageView
android:id="#+id/m_imageview"
android:layout_width="0dp"
android:layout_weight="1"
android:src="#drawable/ic_launcher"
android:layout_height="50dp" />
<TextView
android:id="#+id/m_textview"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="50dp"
android:gravity="center|center"
android:textColor="#ffffff"
android:text="hello"/>
<Button
android:id="#+id/m_buttonview"
android:layout_width="0dp"
android:layout_weight="2"
android:text="OK"
android:layout_height="50dp" />
</LinearLayout>
activity_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" >
<ListView
android:id="#+id/lv_items"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:dividerHeight="2dp"
android:divider="#ffffff"
tools:context=".MainActivity" />
</RelativeLayout>
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView m_pic;
TextView m_title;
Button m_btn;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.listitem, null);
holder = new ViewHolder();
holder.m_title = (TextView) convertView.findViewById(R.id.m_textview);
holder.m_btn = (Button)convertView.findViewById(R.id.m_buttonview);
holder.m_pic = (ImageView) convertView.findViewById(R.id.m_imageview);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.m_title.setText(rowItem.getTxt());
holder.m_pic.setImageResource(rowItem.getImage());
holder.m_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, position + " clicked" , Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
RowItem.java
public class RowItem {
private int image;
private String txt;
public RowItem(int imageview , String textview)
{
this.image = imageview;
this.txt = textview;
}
public int getImage() {
return image;
}
public String getTxt() {
return txt;
}
public void setImage(int image) {
this.image = image;
}
public void setTxt(String txt) {
this.txt = txt;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
String m_txt[] = {"one" , "two" , "three" , "four", "five"};
int m_img [] = {R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher};
ListView m_list;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_list = (ListView)findViewById(R.id.lv_items);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < m_txt.length; i++) {
RowItem item = new RowItem(m_img[i],m_txt[i]);
rowItems.add(item);
}
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.listitem, rowItems);
m_list.setAdapter(adapter);
m_list.setOnItemClickListener(MainActivity.this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position) + ": " + rowItems.get(position).getTxt(),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
This should helps you.
Happy coding.!!!
use a recyclerview.
a recylerview handles every list item as a view, it can hold clicklisteners for every view it holds and that view can hold clicklisteners for every view its holding.

Setting the text of TextView as a child of my ListView, affects other child views text

I have a ListView in my code which contains TextViews as its child, when my OnItemClickListener is fired I will receive a view. This view is the one that I clicked from the ListView. From this part, I will cast this view to make it as TextView. Next, I will set a text of this TextView. The problem is, when I scroll my ListView upward/downward some of the ListView's child text are also change. the ListView redraw its child containing the text of other child text. How can I fix this?
UPDATE: The view I recieved on the OnItemClickListener is somehow the same with other child view. I found this out when I tried to compared the previous view I clicked and the newly clicked view by using equals() method. scrolling the listview redraws its child but sometimes there are child view that are the same with other child view those are not visible in the list.
This is my OnItemClickListener
messagesContainer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(adapter.getItemViewType(i)==ChatAdapter.VOICE_MESSAGE){
RelativeLayout rootView = (RelativeLayout) view;
LinearLayout content = (LinearLayout) rootView.getChildAt(0);
LinearLayout contentWithBackground = (LinearLayout) content.getChildAt(1);
LinearLayout voiceContent = (LinearLayout) contentWithBackground.getChildAt(1);
TextView voiceMessage = (TextView) voiceContent.getChildAt(0);
voiceMessage.setText("Sample Text");
}
}
});
This my Adapter
public class ChatAdapter extends BaseAdapter {
private List<QBChatMessage> chatMessages;
private Context context;
private static final int TXT_MESSAGE = 0;
private static final int IMAGE_MESSAGE = 1;
public static final int VOICE_MESSAGE = 2;
private DisplayImageOptions displayImageOptions;
public ChatAdapter(Context context, List<QBChatMessage> chatMessages){
this.chatMessages = chatMessages;
this.context = context;
initImageLoaderOptions();
}
public void initImageLoaderOptions() {
displayImageOptions = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisc(true).considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565).build();
}
#Override
public int getViewTypeCount() {
return 3;
}
#Override
public int getItemViewType(int position){
if(getItem(position).getProperty("fileUID") == null){
return TXT_MESSAGE;
} else {
if (getItem(position).getProperty("type").equals(QBAttachment.PHOTO_TYPE)) {
return IMAGE_MESSAGE;
} else {
return VOICE_MESSAGE;
}
}
}
#Override
public int getCount() {
if(chatMessages!=null){
return chatMessages.size();
} else{
return 0;
}
}
#Override
public QBChatMessage getItem(int position) {
if(chatMessages!=null){
return chatMessages.get(position);
} else{
return null;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
QBChatMessage chatMessage = getItem(position);
final LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int type = getItemViewType(position);
if (convertView == null) {
if(type == TXT_MESSAGE){
convertView = vi.inflate(R.layout.list_item_message, null);
} else if(type == IMAGE_MESSAGE){
convertView = vi.inflate(R.layout.list_item_message_image, null);
} else{
convertView = vi.inflate(R.layout.list_item_message_voice, null);
}
holder = createViewHolder(convertView, type, position);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
QBUser currentUser = ChatService.getInstance().getCurrentUser();
boolean isOutgoing = chatMessage.getSenderId() != null && chatMessage.getSenderId().equals(currentUser.getId());
setAlignment(holder, isOutgoing, type);
if (chatMessage.getProperty("fullName") != null) {
holder.txtInfo.setText(chatMessage.getProperty("fullName") + ": " + getTimeText(chatMessage));
} else {
holder.txtInfo.setText(getTimeText(chatMessage));
}
if(type == TXT_MESSAGE){
holder.txtMessage.setText(chatMessage.getBody());
} else if (type == IMAGE_MESSAGE){
Log.i("Loading", "Loading");
ImageLoader.getInstance().displayImage(AttachmentConstants.URL_S3+chatMessage.getProperty("fileUID"), holder.imageMessage, displayImageOptions);
}
ImageLoader.getInstance().displayImage(AttachmentConstants.URL_FACEBOOK_OPEN+chatMessage.getProperty("social_picture")+ AttachmentConstants.URL_FACEBOOK_CLOSING, holder.socialPhoto, displayImageOptions);
return convertView;
}
private ViewHolder createViewHolder(View v, int type, final int position) {
final ViewHolder holder = new ViewHolder();
holder.content = (LinearLayout) v.findViewById(R.id.content);
holder.contentWithBG = (LinearLayout) v.findViewById(R.id.contentWithBackground);
holder.txtInfo = (TextView) v.findViewById(R.id.txtInfo);
holder.socialPhoto = (ImageView) v.findViewById(R.id.social_photo);
if(type == TXT_MESSAGE){
holder.txtMessage = (TextView) v.findViewById(R.id.txtMessage);
} else if(type == IMAGE_MESSAGE) {
holder.imageMessage = (ImageView) v.findViewById(R.id.imageMessage);
} else{
holder.voiceMessage = (TextView) v.findViewById(R.id.voiceMessage);
holder.voiceSeekBar = (SeekBar) v.findViewById(R.id.voiceSeekBar);
holder.voiceSeekBar.setEnabled(false);
}
return holder;
}
private String getTimeText(QBChatMessage message) {
return TimeUtils.millisToLongDHMS(message.getDateSent() * 1000);
}
private static class ViewHolder {
public TextView txtMessage;
public TextView txtInfo;
public LinearLayout content;
public LinearLayout contentWithBG;
public ImageView socialPhoto;
public ImageView imageMessage;
public TextView voiceMessage;
public SeekBar voiceSeekBar;
}
}
This is list_item_message_voice.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants">
<TextView
android:id="#+id/txtInfo"
android:layout_width="wrap_content"
android:layout_height="20sp"
android:layout_gravity="right"
android:textSize="10sp"
android:textColor="#android:color/secondary_text_dark" />
<LinearLayout
android:id="#+id/contentWithBackground"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="#drawable/incoming_message_bg"
android:paddingLeft="10dp"
android:paddingBottom="10dp"
android:orientation="horizontal">
<ImageView
android:layout_margin="10dp"
android:id="#+id/social_photo"
android:layout_width="33.33dp"
android:layout_height="33.33dp" />
<LinearLayout
android:id="#+id/voiceContent"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:text="Play"
android:id="#+id/voiceMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"/>
<SeekBar
android:id="#+id/voiceSeekBar"
android:layout_width="100dp"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
The text is getting changed because you changing the text in the TextView but not in the chatMessages list of the adapter.
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(adapter.getItemViewType(i)==ChatAdapter.VOICE_MESSAGE){
//Your code.....
voiceMessage.setText("Sample Text");
//Update the chat messages in the list.
}
}
You can do this:
messagesContainer.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
TextView voiceMessage = (TextView)view.findViewById(R.id.txtMessage);
if(!voiceMessage.getText().toString().equals(""))
voiceMessage.setText("Sample Text");
}
});
Try replacing this in your Adapter
else
{
if(!holder.txtInfo.getText().toString().equals(""))
holder.txtInfo.setText(getTimeText(chatMessage));
}
if(convertView == null){
convertView = vi.inflate(R.layout.list_item_message, null);
}
// You can set the data here...
return covertView;

how to code checkboxes created in custom listview

I've created a custom listView which lists all installed apps on the device, in this list is the app icon, app name and a checkbox. I want to code the onCheckboxClicked method but I don't know where to place it, I've read it should be within the adapter but other examples i've been looking at have code within the main activity and I can't seem to get it working either way.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//retrieve currently installed apps
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List pkgAppsList = getPackageManager().queryIntentActivities( mainIntent, 0);
List<AppDetails> appList = new ArrayList<>();
for (Object object : pkgAppsList)
{
ResolveInfo info = (ResolveInfo) object;
Drawable icon = getBaseContext().getPackageManager().getApplicationIcon(info.activityInfo.applicationInfo);
String strAppName = info.activityInfo.applicationInfo.publicSourceDir.toString();
String strPackageName = info.activityInfo.applicationInfo.packageName.toString();
final String title = (String)((info != null) ? getBaseContext().getPackageManager().getApplicationLabel(info.activityInfo.applicationInfo) : "???");
AppDetails tmp = new AppDetails(title, icon);
appList.add(tmp); //add title and icon into list
}
final ListView listview = (ListView) findViewById(R.id.listView);
final AppDetailsAdapter adapter = new AppDetailsAdapter(this, appList);
listview.setAdapter(adapter);
}
adapter:
public class AppDetailsAdapter extends BaseAdapter {
private List<AppDetails> data;
private Context context;
public AppDetailsAdapter(Context context, List<AppDetails> data) {
this.context = context;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.custom_row_layout, null);
}
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text = (TextView) view.findViewById(R.id.text);
final AppDetails item = data.get(position);
text.setText(item.name);
icon.setImageDrawable(item.icon);
return view;
}
}
custom layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:clickable="true"
android:orientation="horizontal"
android:weightSum="1">
<ImageView
android:id="#+id/icon"
android:layout_width="39dp"
android:layout_height="39dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:textSize="17sp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right" >
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox"
android:onClick="onCheckboxClicked"/>/>
</LinearLayout>
I've also read that the getView method needs to be modified to handle the checkbox but again I can't seem to do it with what I've tried so far
Replace your adapter's get view code with below code :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.custom_row_layout, null);
}
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text = (TextView) view.findViewById(R.id.text);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);
final AppDetails item = data.get(position);
text.setText(item.name);
icon.setImageDrawable(item.icon);
checkBox .setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Handle your conditions here
}
});
return view;
}
here setOnCheckedChangeListener is method that you have to handle .

Custom List View with OnClickListener

I have custom ListView layout with a TextView and CheckBox. Everything works fine.
What I want is, when I click on the CheckBox or TextView (on the single View from ListView) both should behave like one object. (I can click on the CheckBox and it does not effect the TextView and TextView has no effect on CheckBox.) Code has no problem.
I have implemented all possible solutions but problem is still there. (One single click on every object of list should consider ONE COMPLETE CLICK for complete row.) I hope I explained very well.
MAIN ACTIVITY
package com.example.smsplanner;
public class SMSPlanner extends ListActivity {
ListView contactsListView;
private String TAG = "SMSPlanner"; CheckBox check;
int count;
List<ContactInfo> list = new ArrayList<ContactInfo>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ph = new String[3];
phType = new String[3];
LoadContactListFromPhone();
ContactsAdapter contactadAdapter = new ContactsAdapter(this, list);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
setListAdapter(contactadAdapter);
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id)
{
TextView tx =(TextView)v.findViewById(R.id.firstname);
TextView ph =(TextView)v.findViewById(R.id.phone);
Toast.makeText(this, tx.getText().toString() + " " + ph.getText().toString() + " " + Integer.toString(count), Toast.LENGTH_SHORT).show();
}
final class ContactHolder{
TextView txtviewfirstname;
CheckBox chkselected;
TextView txtviewphone;
}
void LoadContactListFromPhone()
{
loadlistandreturns();
}
void call()
{
Toast toast = Toast.makeText(this, "Called...",Toast.LENGTH_LONG);
toast.show();
}
}
CUSTOM ADAPTER
public class ContactsAdapter extends ArrayAdapter<ContactInfo>
{
private final Activity context;
int resourceid;
List<ContactInfo> list = null;
public ContactsAdapter(Activity context, List<ContactInfo> list) {
super(context, R.layout.contactrow, list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
final class ContactHolder{
TextView txtviewfirstname;
CheckBox chkselected;
TextView txtviewphone;
}
}
LAYOUT
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<RadioGroup
android:id="#+id/rgStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="15"
android:orientation="vertical" >
<TextView
android:id="#+id/firstname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RadioGroup>
<RadioGroup
android:id="#+id/rgStyle2"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="85"
android:orientation="vertical" >
<CheckBox
android:id="#+id/check"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:checked="false"
android:focusable="false"
android:focusableInTouchMode="false" >
</CheckBox>
</RadioGroup>
</LinearLayout>
1. Bydefault all the Rows of the ListView are enabled to listen to click....
You must implement onItemClickListener() for the ListView....
See this example:
http://www.mkyong.com/android/android-listview-example/
you can use a CheckedTextView, or you can create a Checkable Layout, like this one :
http://tokudu.com/2010/android-checkable-linear-layout/
i think you should make adapter as
public class ContactsAdapter extends BaseAdapter {
ArrayList<ContactInfo> mlist;
Context mcontext;
public BluetoothChatadpter(Context context,ArrayList<ChatInfo> mchtlist) {
mlist = mchtlist;
mcontext = context;
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public Object getItem(int postion) {
return mlist.get(postion);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// to open the selected file in resp
// do your work here
}});
chkselected .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(context,// "checked is clicke="+pos, 12).show();
if (chkselected.isChecked())
{
// do your work here
} else {
// do your work here
}
}
});
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
}

Categories

Resources