I am trying to write an application which takes items from a database and populates rows within a ListView. I can't click on the items after tapping on the rows and the dpad won't go to any of the rows either. I am using a custom Adapter.
Tweet.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="?android:attr/listPreferredItemHeight"
android:padding="6dip"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/textUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="NAME"/>
<TextView
android:id="#+id/textDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#333333"
android:text="DATE" />
</LinearLayout>
<TextView
android:id="#+id/textTweet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TWEET" />
</LinearLayout>
Activity_main.xml
<?xml version="1.0" encoding="UTF-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:context=".MainActivity" >
</ListView>
Oncreate Method
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView view = (ListView) findViewById(R.id.listView);
MyArrayAdapter theAdapter = new MyArrayAdapter(tweetDb,this);
//setContentView(theAdapter.getView(0, null, null));
view.setAdapter(theAdapter);
view.setOnItemClickListener( new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id)
{
//Tweet theTweet = (Tweet)parent.getAdapter().getItem(position);
//saved.insert(theTweet);
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
Log.v("SCHEMA", "onItemClick fired!");
}
} );
}
Adapter Class getView
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE
);
View tweetView = inflater.inflate(R.layout.tweet, null);
TextView textTweet = (TextView) tweetView.findViewById(R.id.textTweet);
textTweet.setText(items.get(position).getTweet());
textTweet = (TextView)tweetView.findViewById(R.id.textUser);
textTweet.setText(items.get(position).getName());
textTweet = (TextView)tweetView.findViewById(R.id.textDate);
textTweet.setText(textFormat.format(items.get(position).getCreated()));
return tweetView;
}
MyArrayAdapter Class
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.content.Context;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MyArrayAdapter implements ListAdapter
{
private ArrayList<Tweet> items;
private Context context;
private SimpleDateFormat textFormat = new SimpleDateFormat("E MMM dd HH:mm:ss z yyyy");
public MyArrayAdapter(TweetDbSource db, Context context)
{
items = new ArrayList<Tweet>();
this.context = context;
Cursor cursor = db.getReadableDatabase().query("Tweet", null, null, null, null, null, null);
while (!cursor.isLast())
{
cursor.moveToNext();
items.add(new Tweet(cursor.getLong(0),cursor.getLong(1),cursor.getString(2),cursor.getString(3),
cursor.getString(4),new Date(),cursor.getInt(6)));
}
}
#Override
public int getCount()
{
return items.size();
}
#Override
public Object getItem(int position)
{
return items.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public int getItemViewType(int arg0)
{
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater)context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE
);
OnClickListener saveTweet = new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(v.getContext(), "Saved", Toast.LENGTH_LONG).show();
}
};
View tweetView = inflater.inflate(R.layout.tweet, null);
TextView textTweet = (TextView) tweetView.findViewById(R.id.textTweet);
textTweet.setText(items.get(position).getTweet());
textTweet = (TextView)tweetView.findViewById(R.id.textUser);
textTweet.setText(items.get(position).getName());
textTweet = (TextView)tweetView.findViewById(R.id.textDate);
textTweet.setText(textFormat.format(items.get(position).getCreated()));
return tweetView;
}
#Override
public int getViewTypeCount()
{
// TODO Auto-generated method stub
return 1;
}
#Override
public boolean hasStableIds()
{
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isEmpty()
{
// TODO Auto-generated method stub
return items.size() == 0;
}
#Override
public void registerDataSetObserver(DataSetObserver arg0)
{
// TODO Auto-generated method stub
}
#Override
public void unregisterDataSetObserver(DataSetObserver arg0)
{
// TODO Auto-generated method stub
}
#Override
public boolean areAllItemsEnabled()
{
// TODO Auto-generated method stub
return false;
}
#Override
public boolean isEnabled(int arg0)
{
// TODO Auto-generated method stub
return false;
}
}
Toast or log is not working, that's how I can tell it's not working
Updated getView Method
public View getView(int position, View convertView, ViewGroup parent)
{
OnClickListener SaveView = new OnClickListener() {
#SuppressLint("NewApi")
public void onClick(View v)
{
Toast.makeText(v.getContext(), "Saved", Toast.LENGTH_LONG).show();
v.callOnClick();
}
};
LayoutInflater inflater = (LayoutInflater)context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE
);
View tweetView = inflater.inflate(R.layout.tweet, null);
TextView textTweet = (TextView) tweetView.findViewById(R.id.textTweet);
textTweet.setText(items.get(position).getTweet());
textTweet = (TextView)tweetView.findViewById(R.id.textUser);
textTweet.setText(items.get(position).getName());
textTweet = (TextView)tweetView.findViewById(R.id.textDate);
textTweet.setText(textFormat.format(items.get(position).getCreated()));
tweetView.setOnClickListener(SaveView);
return tweetView;
}
UPDATE
The issue was solved and I figured it out :D I had to return true instead of false in these two methods within my adapter class!
#Override
public boolean areAllItemsEnabled()
{
return true;
}
#Override
public boolean isEnabled(int arg0)
{
return true;
}
Usually this happens because the items in your listview are in focus. Try adding
android:descendantFocusability="blocksDescendants"
in your custom listview row
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants">
I usually put the click listener in the adapter itself:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
OnClickListener yourClickListener = new OnClickListener() {
public void onClick(View v) {
//put your desired action here
v.callOnClick();
}
};
...
// then add the listener to your view
tweetView.setOnClickListener(yourClickListener);
add inside onItemClick method:
v.setSelected(true);
Add the line below to your ListView xml
android:choiceMode="singleChoice"
Tried this?
#Override
public boolean isEnabled(int position) {
//Set a Toast or Log over here to check.
return true;
}
Related
I am trying to implement expandable list view. When the list is expanded, it is not scrollable anymore. The header got misplaced.
Here is the layout for the lisltview in my main activity:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_below="#+id/dashboard_scrollview">
<ExpandableListView
android:id="#+id/leaderboard_list_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:transcriptMode="alwaysScroll" />
</RelativeLayout>
and after the list view is tapped, it expanded but is unable to scroll:
I'm wondering why the header and the first element are not showing up in the list view.
MainActivity:
public void setupLeaderboardListView(){
leaderboardDetail = ExpandableLeaderboardData.getData();
leaderboardListView.setStackFromBottom(true);
leaderboardtitle = new ArrayList<String>(leaderboardDetail.keySet());
leaderboardAdapter = new LeaderboardAdapter(this, leaderboardtitle, leaderboardDetail);
leaderboardListView.setAdapter(leaderboardAdapter);
leaderboardListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
leaderboardtitle.get(groupPosition) + " List Expanded.",
Toast.LENGTH_SHORT).show();
}
});
leaderboardListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
leaderboardtitle.get(groupPosition) + " List Collapsed.",
Toast.LENGTH_SHORT).show();
}
});
leaderboardListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(
getApplicationContext(),
leaderboardtitle.get(groupPosition)
+ " -> "
+ leaderboardDetail.get(
leaderboardtitle.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT
).show();
return false;
}
});
}
List datasource:
List<String> cricket = new ArrayList<String>();
cricket.add("India");
cricket.add("Pakistan");
cricket.add("Australia");
cricket.add("England");
cricket.add("South Africa");
cricket.add("India");
cricket.add("Pakistan");
cricket.add("Australia");
cricket.add("England");
cricket.add("South Africa");
I tried setting layout_height=match_parent for the expandable list, but it did not work
This can happen when your ExpandableListView has wrap_content for a width and height. To fix, make it the same as the parent RelativeLayout
<ExpandableListView
android:id="#+id/leaderboard_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:transcriptMode="alwaysScroll" />
First of all: ListView is depricated, It should have been dead long ago and yet, i keep seeing post on it!!!
Second:
Move to recyclerView, here are some resources that will help ya:
1. Nice introduction to it: https://developer.android.com/training/material/lists-cards.html
2. My dialog cheetSheet app (something like demo app), one of the dialogs uses expandable recyclverview library, give it a try https://github.com/WithoutCaps/DialogsCheatSheet
Use this code, it's working fine.
This is main activity layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ExpandableListView
android:id="#+id/expandable_listview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ExpandableListView>
</LinearLayout>
Your Parent Item Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/tv_parent_item"
android:layout_marginLeft="10dp"
android:layout_gravity="center_vertical"
android:textSize="20sp"
/>
</LinearLayout>
Your child item layout:
<?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="horizontal"
>
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/iv_child_item"
android:background="#drawable/ic_launcher"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="100dp"
android:layout_marginTop="5dp" >
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/tv_child_item1"
android:layout_marginLeft="10dp"
android:textSize="15sp"
android:text="Test"
/>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:id="#+id/tv_child_item2"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:textSize="15sp"
android:text="Test"
/>
</LinearLayout>
Custom Adapter class:
import java.util.HashMap;
import java.util.List;
import com.example.expandablelistview.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
public class ExpandableAdapter extends BaseExpandableListAdapter{
private Context context;
private List<String> parentList;
private HashMap<String , List<Songs>> childList;
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options;
public ExpandableAdapter(){
}
public ExpandableAdapter(Context context,List<String> parentList,
HashMap<String,List<Songs>> childList)
{
this.context=context;
this.parentList=parentList;
this.childList=childList;
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_launcher)
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.defaultDisplayImageOptions(options)
.build();
imageLoader.getInstance().init(config);
}
#Override
public int getGroupCount() {
// TODO Auto-generated method stub
return this.parentList.size();
}
#Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return this.childList.get(this.parentList.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return this.parentList.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return this.childList.get(this.parentList.get(groupPosition)).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.parent_item, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.tv_parent_item);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
ExpandableListView eLV = (ExpandableListView) parent;
eLV.expandGroup(groupPosition);
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Songs childText = (Songs) getChild(groupPosition, childPosition);
if(convertView==null)
{
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_item , null);
}
TextView artist = (TextView) convertView.findViewById(R.id.tv_child_item1);
TextView song = (TextView) convertView.findViewById(R.id.tv_child_item2);
ImageView image = (ImageView) convertView.findViewById(R.id.iv_child_item);
artist.setText(childText.getArtist());
song.setText(childText.getSong());
String imgUrl=childText.getArtwork();
imageLoader.displayImage(imgUrl, image);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
For Main Activity OnCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
expListView = (ExpandableListView) findViewById(R.id.expandable_listview);
listParent = new ArrayList<String>();
listChild = new HashMap<String, List<Songs>>();
new GetData().execute();
listAdapter = new ExpandableAdapter(this, listParent, listChild);
expListView.setAdapter(listAdapter);
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
Toast.makeText(getApplicationContext(),
"Group Clicked " + listParent.get(groupPosition),
Toast.LENGTH_SHORT).show();
return false;
}
});
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
}
});
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
}
});
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getApplicationContext(),
listParent.get(groupPosition)
+ " : "
+ listChild.get(
listParent.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
}
In Expandable List view xml used android:nestedScrollingEnabled="true"
Android Code:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView;
rootView = inflater.inflate(R.layout.view_contact_list, container, false);
listview = (ListView) rootView.findViewById(R.id.listView1);
Log.d("Contact List", "Before read method");
ReadContacts();
Log.d("Contact List", "After Read Method");
Log.d("Before ", "Before Adapter Initialization");
adapter = new ContactListAdapter(getActivity(), contact_list);
Log.d("After",
"After Adapter Initializaiton and before listview set adapter");
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
TextView name = (TextView) arg1
.findViewById(R.id.tvContactName);
TextView phone = (TextView) arg1
.findViewById(R.id.tvContactPhone);
Toast.makeText(
getActivity(),
"Name : " + name.getText().toString() + "Phone : "
+ phone.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
The adapter is working properly and i can see the data in a listview but i cannot click on the list items. There is no response
i have set the android:clickable = "true"
The fragment is a part of a view Pager
I cannot use list fragments and want to use an adapter .. what is the error ?
I have also pasted this setonitemclick method in onActivityCreated() .. it didnt work
XML of 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="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="false"
>
</ListView>
</LinearLayout>
The Adapter I am using:
package com.example.eh;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class ContactListAdapter extends BaseAdapter
{
Context context;
List<Tuple> contact_list=new ArrayList<Tuple>();
public ContactListAdapter(Context ctx, List<Tuple> data)
{
context = ctx;
contact_list = data;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
//return contacts.size();
return contact_list.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return contact_list.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public String getName(int arg0)
{
return contact_list.get(arg0).getContactName();
}
public String getPhone(int arg0)
{
return contact_list.get(arg0).getContactPhone();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder = null;
if (convertView == null) {
view = ((Activity) context).getLayoutInflater().inflate(R.layout.row_full_contact_list, parent, false);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.name.setText(getName(position));
holder.phone.setText(getPhone(position));
return view;
}
private class ViewHolder {
public TextView name;
public TextView phone;
public Button invite;
public ViewHolder(View v)
{
name = (TextView) v.findViewById(R.id.tvContactName);
phone = (TextView) v.findViewById(R.id.tvContactPhone);
invite = (Button) v.findViewById(R.id.bInviteFriends);
}
}
}
The XML of the row item:
<?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:orientation="vertical" >
<RelativeLayout
android:id="#+id/LeftSide"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/tvContactName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="30dp"
android:maxLines="1"
/>
<TextView
android:id="#+id/tvContactPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tvContactName"
android:text="TextView" />
</RelativeLayout>
<Button
android:id="#+id/bInviteFriends"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Invite" />
</RelativeLayout>
Have you put a breakpoint inside the onItemClick method to make sure its not fired?
Try to add this line of code on your listview's XML :
android:focusable="false"
try this
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(
getActivity(),position.toString+" is the position you clicked!!",Toast.LENGTH_SHORT).show();
TextView name = (TextView) arg1
.findViewById(R.id.tvContactName);
TextView phone = (TextView) arg1
.findViewById(R.id.tvContactPhone);
Toast.makeText(
getActivity(),
"Name : " + name.getText().toString() + "Phone : "
+ phone.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
I am trying to make a chat program. My problem is that every time the background image updates(sender changes), every item in the array gets the same background. How can I change this so that outgoing messages get one type of background and incoming get another?
public class RowAdapter extends BaseAdapter {
private Context context;
private int textViewResourceId;
private final ArrayList<String> messageList;
private final ArrayList<String> senderList;
public String messageDirection;
boolean out;
public RowAdapter(Context context, int textViewResourceId, ArrayList<String> messageList, ArrayList<String> senderList) {
super();
this.textViewResourceId = textViewResourceId;
this.messageList = messageList;
this.senderList = senderList;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View rowView = convertView;
ViewHolder holder;
long timestamp = System.currentTimeMillis();
String readableTimestamp = (String)DateUtils.getRelativeTimeSpanString(timestamp);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(textViewResourceId, parent, false);
holder = new ViewHolder();
holder.label = (TextView)rowView.findViewById(R.id.label);
holder.message=(TextView)rowView.findViewById(R.id.message);
holder.time = (TextView)rowView.findViewById(R.id.textTime);
holder.RL = (RelativeLayout)rowView.findViewById(R.id.userAndMessage);
rowView.setTag(holder);
}else{
holder = (ViewHolder)rowView.getTag();
}
holder.label.setText(senderList.get(position));
holder.message.setText(messageList.get(position));
holder.time.setText(readableTimestamp);
if(out){
if (messageList.get(position)!= null) {
holder.RL.setBackgroundResource(R.drawable.yellow);
((RelativeLayout) rowView).setGravity(Gravity.RIGHT);
}
}else{
if (messageList.get(position)!= null) {
holder.RL.setBackgroundResource(R.drawable.green);
((RelativeLayout) rowView).setGravity(Gravity.LEFT);
}
}
return rowView;
}
public void setOut(boolean out){
this.out = out;
}
static class ViewHolder{
RelativeLayout RL;
TextView label;
TextView message;
TextView time;
}
#Override
public int getCount() {
return messageList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
}
Ok, try to do this
it's just an example and you have to add your process within it
Main layout 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"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="#+id/listView_Chat"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:background="#123456"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="fromMeBt"
android:text="From me" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="fromOtherBt"
android:text="From other" />
</LinearLayout>
</LinearLayout>
add a list row xml file
<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="wrap_content"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/txt_chat"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Create a new Class named ChatObject
public class ChatObject {
private String mssg;
private int from;
public ChatObject(String mssg, int from) {
super();
this.mssg = mssg;
this.from = from;
}
public String getMssg() {
return mssg;
}
public void setMssg(String mssg) {
this.mssg = mssg;
}
public int getFrom() {
return from;
}
public void setFrom(int from) {
this.from = from;
}
}
now, make some changes to your MainActivity like this
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private ArrayList<ChatObject> items = new ArrayList<ChatObject>();
ListView listView_chat;
CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new CustomAdapter(items);
listView_chat = (ListView) findViewById(R.id.listView_Chat);
listView_chat.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void fromMeBt(View v) {
ChatObject object = new ChatObject("from me :)", 0);
items.add(object);
adapter.notifyDataSetChanged();
listView_chat.setSelection(items.size());
}
public void fromOtherBt(View v) {
ChatObject object = new ChatObject("from other :)", 1);
items.add(object);
adapter.notifyDataSetChanged();
listView_chat.setSelection(items.size());
}
class CustomAdapter extends BaseAdapter {
ArrayList<ChatObject> items;
public CustomAdapter(ArrayList<ChatObject> items) {
// TODO Auto-generated constructor stub
this.items = items;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_chat, null);
TextView txt_chat = (TextView) convertView.findViewById(R.id.txt_chat);
ChatObject object = items.get(position);
txt_chat.setText(object.getMssg());
if (object.getFrom() == 0) {
convertView.setBackgroundColor(Color.BLUE);
}else {
convertView.setBackgroundColor(Color.CYAN);
}
return convertView;
}
}
}
that's it, and if you want change the padding in xml layouts or add this to your dimens.xml file
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
happy now? I hope this help you
Hi all I have custom grid view with imageButton and textView as follows
Here i have used imageButton.. The problem is the grid is not clickable.. But if i use here imageView it works fine but UI is not appropriate.
Here is my layout
<?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="fill_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="5dp"
>
<ImageButton
android:id="#+id/profilePic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/newlocation"
android:background="#drawable/btnbackground"
/>
<TextView
android:id="#+id/SpeakerName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="15sp"
android:text="Some Speaker"
/>
Here is my adapter
package com.tt.cc;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SavedConferencesGridAdapter extends ArrayAdapter<String>{
Context mContext;
List<String> confernceList;
public SavedConferencesGridAdapter(Context context, int textViewResourceId, List<String> confernceList)
{
super(context,textViewResourceId,confernceList);
this.confernceList = confernceList;
this.mContext = context;
Log.e("TAG", confernceList.size()+"");
}
int[] picIds = new int[] { R.drawable.newschedule,R.drawable.newexhibitors,
R.drawable.newsponsers, R.drawable.newlocation,
R.drawable.newfavourites, R.drawable.newreminder,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info,R.drawable.info };
#Override
public int getCount() {
// TODO Auto-generated method stub
return confernceList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v;
if(convertView==null){
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.entity, null);
TextView tv = (TextView)v.findViewById(R.id.SpeakerName);
tv.setText("tt");
/*ImageView iv = (ImageView) v.findViewById(R.id.profilePic);
iv.setImageResource(picIds[position]);*/
}
else
{
v = convertView;
}
return v;
}
}
and here is my activity
public class SavedConferencesActivity extends Activity{
GridView confereneceGridView;
ArrayAdapter<String> conferneceAdapter;
Button btnUpdate;
List<String> conferenceList;
TextView txtHeading;
Boolean result = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
protected void onStart() {
super.onStart();
setContentView(R.layout.homegridlayout);
initialize();
confereneceGridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(SavedConferencesActivity.this, conferenceList.get(position)+"", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
conferneceAdapter = new SavedConferencesGridAdapter(this, android.R.layout.simple_list_item_1, conferenceList);
confereneceGridView.setAdapter(conferneceAdapter);
}
private void initialize() {
confereneceGridView = (GridView) findViewById(R.id.gridOfConference);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
txtHeading = (TextView) findViewById(R.id.txtTag);
conferenceList = new ArrayList<String>();
conferenceList.add("AA");
conferenceList.add("BB");
conferenceList.add("CC");
if (conferenceList.size() == 0)
txtHeading.setText("No conferences saved");
else
txtHeading.setText("Selected Conferences");
}
}
Please help me in solving this problem. Or if any alternative available..
Simple. Provide this attribute for the ImageButton ,
android:focusable="false"
This problem usually occurs when there is a focussable element in the Grid.(Eg:Buttons, ImageButton etc).
Reason of this ImageButton is by Default is clickable and focusable, so Focus and click event never goes to ItemView.
Set Properties
android:focusable-"false"
and
android:clickable="false"
Your item's Layout should be:
<LinearLayout ...
android:descendantFocusability="blocksDescendants">
<ImageButton ...
android:focusable="false"
android:focusableInTouchMode="false"/>
</LinearLayout>
Don't forget setOnClickListener for ImageButton in Adapter.
in your adapter class,
before you return the view "v", add the "onClickListener" to "v"
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, position, Toast.LENGTH_SHORT).show();
}
});
I was trying a sample program to understand the behavior of the dynamic GridView. When I tried to execute the program I got a run-time exception at texts.setText(str[position]); in the .java file.
.java
package GridView_dynamic.grid;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
public class GridView_dynamic extends Activity {
/** Called when the activity is first created. */
TextView select;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
select = (TextView)findViewById(R.id.text);
GridView grid = (GridView)findViewById(R.id.grid);
grid.setAdapter(new my_Adapter(this));
}
public class my_Adapter extends BaseAdapter{
String[] str = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N"};
public Context context;
public my_Adapter(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return str.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null){
Toast.makeText(context,"convertView is NULL", Toast.LENGTH_LONG).show();
}
TextView texts;
texts = (TextView)convertView;
//texts = (TextView)findViewById(R.id.text);
texts.setText(str[position]);
return texts;
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#0000aa"
android:textColor="#00aa00"
/>
<GridView
android:id="#+id/grid"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#aaaaaa"
/>
</LinearLayout>
You get a NullPointerException because when you get a null convertView(the list is first built) you don't create a new TextView. Your getView() method should be:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView == null){
Toast.makeText(context,"convertView is NULL", Toast.LENGTH_LONG).show();
//if convertView is null is your job to make a new View
convertView = new TextView(context);
}
((TextView)convertView).setText(str[position]);
return convertView;
}
By the looks of it you never actually instantiate the TextView in getView. The following code will create a new textView if convertView is null.
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = new TextView(GridView_dynamic.this);
((TextView)convertView).setText(str[position]);
return convertView;
}
Hope this helps!