How to get a TextView value of a ListViewItem - java

I am using a ListView to build a music playlist such as :
I want to get the value of the textView in green corresponding to the the item whom button (i.e. the star on the right) was clicked. Any idea please?
activity_row_item.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:id="#+id/rowItem_layout"
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="com.RowItemActivity" >
<TextView
android:id="#+id/songName_text"
android:layout_width="40dp"
android:layout_height="fill_parent"
android:layout_gravity="left"
android:layout_weight="1"
android:background="#8800FF00"
android:text="TextView" />
<TextView
android:id="#+id/score_text"
android:layout_width="5dp"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:layout_weight="0.3"
android:background="#88FF0000"
android:text="TextView" />
<ImageButton
android:id="#+id/button_like"
android:layout_width="7dp"
android:layout_height="fill_parent"
android:layout_gravity="right"
android:layout_weight="0.20"
android:src="#android:drawable/btn_star" />
</LinearLayout>
activity_list_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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="com.PlayListActivity" >
<ListView
android:id="#+id/playlist_listView"
android:layout_width="372dp"
android:layout_height="394dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1.42" />
</RelativeLayout>
PlayListAdapter.java
public class PlayListAdapter extends ArrayAdapter<Song> {
Context context;
int layoutResourceId;
Song[] data = null;
SongHolder holder = null;
ConnectionWrapper connectionWrapper;
public PlayListAdapter(Context context, int layoutResourceId, Song[] data) {
super(context, layoutResourceId, data);
this.context = context;
this.layoutResourceId = layoutResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row == null)
{
LayoutInflater inflater = LayoutInflater.from(context);
row = inflater.inflate(layoutResourceId, parent, false);
holder = new SongHolder();
holder.songName = (TextView)row.findViewById(R.id.songName_text);
holder.score = (TextView)row.findViewById(R.id.score_text);
holder.likeButton = (ImageButton)row.findViewById(R.id.button_like);
holder.likeButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
Runnable r = new Runnable() {
public void run() {
try {
//get the SongHolder#songName of the item to which belongs the clicked button
} catch (IOException e) {
e.printStackTrace();
}
}
};
new Thread(r).start();
}
});
row.setTag(holder);
}
else
{
holder = (SongHolder)row.getTag();
}
Song song = data[position];
holder.songName.setText(String.valueOf(song.getSongName()));
holder.score.setText(String.valueOf(song.getScore()));
return row;
}
class SongHolder{
TextView songName;
TextView score;
ImageButton likeButton;
}
}

No need to use Thread inside ClickListenerSimply use -
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row == null)
{
LayoutInflater inflater = LayoutInflater.from(context);
row = inflater.inflate(layoutResourceId, parent, false);
holder = new SongHolder();
holder.songName = (TextView)row.findViewById(R.id.songName_text);
holder.score = (TextView)row.findViewById(R.id.score_text);
holder.likeButton = (ImageButton)row.findViewById(R.id.button_like);
row.setTag(holder);
}
else
{
holder = (SongHolder)row.getTag();
}
Song song = data[position];
holder.songName.setText(String.valueOf(song.getSongName()));
holder.score.setText(String.valueOf(song.getScore()));
holder.likeButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
// TextView
TextView tvSongName = holder.songName;
// if you want to get song name
String songName = String.valueOf(song.getSongName());
Log.v("SongName", "" +songName);
}
});
return row;
}

Related

list view inside list View in android

I am Using a list view inside a listview and both listview share same list item.
It is working fine but if height of the item increases in inside list view it doesn't wrap the content and put a scrollview which is not as per requirement.
Please see the codes below
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<ListView
android:id="#+id/list_comments"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:divider="#android:color/transparent"
android:dividerHeight="5dp" />
</RelativeLayout>
comments_for_topic.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:background="#fafafa">
<RelativeLayout
android:id="#+id/commentsRelLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:paddingLeft="7dp"
android:background="#d5d5d5"
android:orientation="vertical">
<TextView
android:id="#+id/UserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text="User name"/>
<TextView
android:id="#+id/Comment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/UserName"
android:textSize="12sp"
android:padding="5dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/showRep"
android:text="Comment test 1"/>
<TextView
android:id="#+id/showRep"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2Replies"
android:layout_toLeftOf="#+id/Reply"
android:layout_marginRight="3dp"
android:textSize="12dp"
android:textColor="#android:color/holo_blue_dark"
android:layout_below="#+id/UserName"/>
<TextView
android:id="#+id/Reply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reply"
android:textSize="12dp"
android:textColor="#android:color/holo_blue_dark"
android:layout_below="#+id/UserName"
android:layout_alignParentRight="true"/>
</RelativeLayout>
<ListView
android:id="#+id/list_commentsLevel1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/commentsRelLayout"
android:layout_alignLeft="#+id/commentsRelLayout"
android:layout_marginLeft="34dp"
android:background="#d5d5d5"
android:layout_marginTop="2dp"
android:scrollbars="none"
android:divider="#android:color/white"
android:dividerHeight="1dp"
></ListView>
<TextView
android:id="#+id/showmorebtn"
android:layout_alignParentBottom="true"
android:layout_marginBottom="4dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/show_more"
android:layout_below="#+id/list_commentsLevel1"
android:layout_alignLeft="#+id/list_commentsLevel1"
android:textColor="#android:color/holo_blue_dark"
/>
</RelativeLayout>
AdapterComments.java
public class AdapterComments extends BaseAdapter {
private Activity activity;
private ArrayList<CommentListModel> itemsArrayList = new ArrayList<CommentListModel>();
private ArrayList<CommentListModel> Comments = new ArrayList<CommentListModel>();
CommentListModel tempValues=null;
private static LayoutInflater inflater=null;
ArrayList<AdapterComments> adapterCommentsArrayList = new ArrayList<AdapterComments>();
ViewHolder holder = new ViewHolder();
ViewHolder viewHolder;
ArrayList<String> list =new ArrayList<String>();
private int currentID=0;
boolean isChild =false;
FragmentDiscussinTopic fragmentDiscussinTopic;
public AdapterComments() {
}
public AdapterComments(Activity context, FragmentDiscussinTopic fragmentDiscussinTopic, ArrayList<CommentListModel> itemsArrayList) {
this.activity = context;
this.itemsArrayList = itemsArrayList;
this.isChild = false;
this.fragmentDiscussinTopic = fragmentDiscussinTopic;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0 ; i<itemsArrayList.size();i++){
AdapterComments adapterComments1 = new AdapterComments();
adapterCommentsArrayList.add(adapterComments1);
}
}
public AdapterComments(Activity context, ArrayList<CommentListModel> itemsArrayList) {
this.activity = context;
this.itemsArrayList = itemsArrayList;
this.isChild = true;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0 ; i<itemsArrayList.size();i++){
AdapterComments adapterComments1 = new AdapterComments();
adapterCommentsArrayList.add(adapterComments1);
}
}
#Override
public int getCount() {
if(itemsArrayList.size()<=0)
return 1;
return itemsArrayList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return position;
}
public static class ViewHolder{
public TextView UserName;
public TextView Comment;
public TextView showRep;
public TextView Reply;
public TextView showmorebtn;
public ListView list_commentsLevel1;
}
#Override
public View getView(final int position, View rowView, ViewGroup parent) {
View v1 = rowView;
if(rowView==null){
v1 = inflater.inflate(R.layout.comments_for_topic,null);
viewHolder =new ViewHolder();
viewHolder.UserName=(TextView)v1.findViewById(R.id.UserName);
viewHolder.Comment=(TextView)v1.findViewById(R.id.Comment);
viewHolder.showRep=(TextView)v1.findViewById(R.id.showRep);
viewHolder.showmorebtn=(TextView)v1.findViewById(R.id.showmorebtn);
viewHolder.Reply=(TextView)v1.findViewById(R.id.Reply);
viewHolder.list_commentsLevel1=(ListView)v1.findViewById(R.id.list_commentsLevel1);
v1.setTag( viewHolder );
}
else
viewHolder=(ViewHolder)v1.getTag();
if(itemsArrayList.size()<=0)
{
Log.e("data", " no data found");
}
else {
tempValues = itemsArrayList.get(position);
if (tempValues.isVisible()){
viewHolder.list_commentsLevel1.setAdapter(adapterCommentsArrayList.get(position));
viewHolder.list_commentsLevel1.setVisibility(View.VISIBLE);
ObjectAnimator anim = ObjectAnimator.ofFloat(viewHolder.list_commentsLevel1, "alpha", 0f, 1f);
anim.setDuration(1000);
anim.start();
setListViewHeightBasedOnChildren(viewHolder.list_commentsLevel1);
// scrollMyListViewToBottom();
}else {
Animation animation = new TranslateAnimation(0,0,0,1000);
animation.setDuration(1000);
viewHolder.list_commentsLevel1.startAnimation(animation);
viewHolder.list_commentsLevel1.setVisibility(View.GONE);
}
viewHolder.UserName.setText(tempValues.getUserName());
viewHolder.Comment.setText(tempValues.getComment());
int subcmntcount = tempValues.getSubCommentCount();
if (subcmntcount>=1){
viewHolder.showRep.setVisibility(View.VISIBLE);
if (subcmntcount==1){
String repText=new String("1Reply");
SpannableString content = new SpannableString(repText);
content.setSpan(new UnderlineSpan(), 0, repText.length(), 0);
viewHolder.showRep.setText(content);
}else {
String repText=new String(subcmntcount+"Replies");
SpannableString content = new SpannableString(repText);
content.setSpan(new UnderlineSpan(), 0, repText.length(), 0);
viewHolder.showRep.setText(content);
}
viewHolder.showmorebtn.setVisibility(View.GONE);
}else {
viewHolder.showRep.setVisibility(View.GONE);
viewHolder.list_commentsLevel1.setVisibility(View.GONE);
viewHolder.showmorebtn.setVisibility(View.GONE);
}
if (tempValues.isChild()){
viewHolder.Reply.setVisibility(View.GONE);
viewHolder.showRep.setVisibility(View.GONE);
}else {
viewHolder.Reply.setVisibility(View.VISIBLE);
String repText=new String("Reply");
SpannableString content = new SpannableString(repText);
content.setSpan(new UnderlineSpan(), 0, repText.length(), 0);
viewHolder.Reply.setText(content);
}
v1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0;i<itemsArrayList.size();i++){
CommentListModel commentListModel = ( CommentListModel ) itemsArrayList.get( i );
if (i==position){
isChild =true;
if (commentListModel.getSubCommentCount()>0){
commentListModel.setVisible(true);
itemsArrayList.remove(i);
itemsArrayList.add(i,commentListModel);
new getDiscussionForumComments(commentListModel.getDiscussionCommentID(),position).execute();
}
}else {
commentListModel.setVisible(false);
itemsArrayList.remove(i);
itemsArrayList.add(i,commentListModel);
}
}
}
});
viewHolder.Reply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Configuration.currentDiscussID = itemsArrayList.get(position).getDiscussionCommentID();
fragmentDiscussinTopic.requestEditPop();
}
});
}
return v1;
}
public static void setListViewHeightBasedOnChildren(ListView listView)
{
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight=0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++)
{
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth,
ViewGroup.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + ((listView.getDividerHeight()) * (listAdapter.getCount()));
listView.setLayoutParams(params);
listView.requestLayout();
}
}
please see the highlighted area of image listview height is not proper to wrap the content
any help would be appericiated
The problem is you can't get the scroll of both listview at a time. if you what you both at the same time. you need to create a custom list view try something like this instead of your list view (inside list).
public class NonScrollListView extends ListView {
public NonScrollListView(Context context) {
super(context);
}
public NonScrollListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
ViewGroup.LayoutParams params = getLayoutParams();
params.height = getMeasuredHeight();
}
}
Their are some points you need to fix.
Give a proper height to your ListView so that it can scroll within that boundry, wrap_content is never recommended for ListView. So better to put some height to your ListView.
Listview inside a ListView will not give the user experience good. Try a work around or better to Use RecyclerView. RecyclerView is better in performance in case of nested list.
Hope it will help :)

How to use buttons from different xml files in one class

I have a listview with multiple items and one button to start a new activity. I'm getting Null Pointer Exception when I run my app. How and where shoud I set the OnClickListener to run properly?
Also, how can I pass with Intent the arraylist named listaIngrediente?
Here is my code
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.radu.fridgecheck.MainActivity"
android:orientation="vertical">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/find_recipies"
android:id="#+id/find"
android:layout_weight="0"/>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false"/>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox"
android:layout_alignBottom="#+id/checkBox"
android:layout_toRightOf="#+id/checkBox"
android:text="TextView" />
</RelativeLayout>
Adapter
public class Adapter extends ArrayAdapter<Ingredient> {
public LayoutInflater inflater;
public ArrayList<Ingredient> listaIngrediente;
ArrayList<String> ingredienteDisponibile;
private Activity activity;
public Adapter(Activity activity, int textResourceId, ArrayList<Ingredient> ingrediente) {
super(activity, textResourceId, ingrediente);
this.activity=activity;
this.listaIngrediente=ingrediente;
try {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
} catch (Exception e) {
e.printStackTrace();
}
}
public int getCount() {
return listaIngrediente.size();
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (convertView == null) {
v = inflater.inflate(R.layout.list_item, null);
}
final Ingredient ingredients = getItem(position);
final TextView display_ingredients = (TextView) v.findViewById(R.id.name);
display_ingredients.setText(ingredients.getNameI());
final CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox);
ListView listView = (ListView) v.findViewById(R.id.listView1);
Button button = (Button) v.findViewById(R.id.button);
listView.addFooterView(button);
Button find = (Button) v.findViewById(R.id.find);
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getContext(), ShowRecipes.class);
Bundle args = new Bundle(); /// nu reusesc sa transfer obiectele
args.putSerializable("ARRAYLIST",listaIngrediente);
i.putExtra("BUNDLE",args);
activity.startActivity(i);
}
});
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!ingredients.isSelected()) {
checkBox.setChecked(true);
ingredients.setSelected(true);
}
else{
checkBox.setChecked(false);
ingredients.setSelected(false);
}
}
});
return v;
}
}
You have to write that in MainActivity class, because your button is in main_activity.xml
In MainActivity, write this method
public void showRecipes(View view) {
Intent i = new Intent(getContext(), ShowRecipes.class);
Bundle args = new Bundle(); /// nu reusesc sa transfer obiectele
args.putSerializable("ARRAYLIST",listaIngrediente);
i.putExtra("BUNDLE",args);
startActivity(i);
}
In Xml add onClick
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/find_recipies"
android:id="#+id/find"
android:onClick="showRecipes"
/>`
More Information on click Events
http://developer.android.com/guide/topics/ui/controls/button.html#HandlingEvents

setOnItemClickListener is not working for ArrayAdapter<ImageView>

When i try to click on items in the list it doesnt go through the onItemClick method.
GridViewAdapter.java
public class GridViewAdapter extends ArrayAdapter<ImageItem>{
private Context context;
private int layoutResourceId;
private ArrayList<ImageItem> data = new ArrayList<ImageItem>();
public GridViewAdapter(Context context, int layoutResourceId,
ArrayList<ImageItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
}
MainActivity.java
public class MainActivity extends Activity {
private GridView gridView;
private GridViewAdapter customGridAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridView);
customGridAdapter = new GridViewAdapter(this, R.layout.row_grid, getData());
gridView.setAdapter(customGridAdapter);
Log.d("yyoyoyoyo", "jhgvkbkhbjkhbj");
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(MainActivity.this, position + "#Selected",
Toast.LENGTH_SHORT).show();
}
});
}
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<ImageItem>();
// retrieve String drawable array
TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);
for (int i = 0; i < imgs.length(); i++) {
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
imgs.getResourceId(i, -1));
imageItems.add(new ImageItem(bitmap, "Image#" + i));
}
return imageItems;
}
}
row_grid.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="vertical"
android:padding="5dp"
android:clickable="true"
android:background="#drawable/grid_color_selector"
android:focusable="false"
android:focusableInTouchMode="false"
android:descendantFocusability="blocksDescendants"
>
<ImageView
android:id="#+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:focusable="false"
android:focusableInTouchMode="false"
>
</ImageView>
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:textSize="12sp"
android:focusable="false"
android:focusableInTouchMode="false"
>
</TextView>
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"
android:background="#f0f0f0"
android:clickable="false"
android:descendantFocusability="blocksDescendants"
tools:context=".MainActivity" >
<GridView
android:id="#+id/gridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:columnWidth="100dp"
android:gravity="center"
android:numColumns="auto_fit"
android:verticalSpacing="5dp"
android:drawSelectorOnTop="true"
android:stretchMode="columnWidth"
android:descendantFocusability="blocksDescendants"
>
</GridView>
</RelativeLayout>
I have tried most of the solutions regarding this topic on StackOverFlow none of them worked for me. This app lists all the images but when you click onItemClick isnt fired. Probably there is something wrong with my code.
Thank you!!
Remove android:clickable="true" in row_grid.xml. and add android:clickable="true" in activity_main.xml
Also remove the
android:focusable="false"
android:focusableInTouchMode="false"
As row_grid.xml is clickable, it blocks the grid's onclick listener from responding.

Android ListView based in custom BaseAdapter is not shown in my code

I've working on ListView with a custom BaseAdapter which I've watched on the Slidenerd tutorial series here:(It's not important to watch to understand my question)
http://www.youtube.com/watch?v=_l9e2t4fcfM&list=PLonJJ3BVjZW6hYgvtkaWvwAVvOFB7fkLa&index=91
After running the code on the virtual device there is no error but not ListView too.
Is it possible to tell me what's the problem of my code?
public class List extends Activity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(new EhsanAdapter(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.list, menu);
return true;
}
}
class SingleRow{
String title;
String description;
int image;
public SingleRow(String title,String description,int image) {
this.title = title;
this.description=description;
this.image=image;
}
}
class EhsanAdapter extends BaseAdapter{
ArrayList<SingleRow> list;
Context context;
public EhsanAdapter(Context c) {
list = new ArrayList<SingleRow>();
context = c;
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
String[] descriptions = res.getStringArray(R.array.descriptions);
int[] images = {R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4,R.drawable.image5};
for(int i=0;i<10;i++){
list.add(new SingleRow(titles[i], descriptions[i], images[i]));
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, viewGroup,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView description = (TextView) row.findViewById(R.id.txtDescription);
ImageView image = (ImageView) row.findViewById(R.id.imgPic);
SingleRow temp = list.get(i);
title.setText(temp.title);
description.setText(temp.description);
image.setImageResource(temp.image);
return row;
}
}
The layout of activity:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android: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=".List" >
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
The layout of single row:
<?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" >
<ImageView
android:layout_margin="10dp"
android:id="#+id/imgPic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/image1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Title"
android:id="#+id/txtTitle"
android:layout_alignTop="#+id/imgPic"
android:layout_toRightOf="#+id/imgPic"
android:layout_alignParentRight="true">
</TextView>
<TextView
android:id="#+id/txtDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imgPic"
android:layout_marginLeft="25dp"
android:layout_toRightOf="#+id/imgPic"
android:layout_marginTop="20dp"
android:text="Description"
android:ems="10">
</TextView>
</RelativeLayout>
Remove the line LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); from getView() method and instead add it in the constructor of EhsanAdapter class.
I see different issues:
The layout of single row contains a relative layout which the android:layout_height="match_parent" should be android:layout_height="wrap_content"
Then inside the Adapter you are neither recycling the views nor using the ViewHolder pattern:
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
About ViewHolder pattern implementation optimisation in ListView
http://www.jmanzano.es/blog/?p=166
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){ //The row view is not created, let's do it:
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, viewGroup,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView description = (TextView) row.findViewById(R.id.txtDescription);
ImageView image = (ImageView) row.findViewById(R.id.imgPic);
// Here we add the title, description and image inside the ViewHolder
....
}else{
//With the View holder pattern we get the views inside the row view to fill it later
....
}
// Now we get the SingleRow and we fill it using the ViewHolder pattern
SingleRow temp = list.get(i);
....
return row;
}
You only have 5 images and you wrote i<10 you should've wrote i<5 the amount of "titles" and "descriptions" and "images" must be the same.
for(int i=0;i<5;i++){
list.add(new SingleRow(titles[i], descriptions[i], images[i]));
}

UnsupportedOperationException in creating custom ListView in Android

i wanted to have a custom listView so I did this:
Created an Activity:
public class PRS_MainList_Act extends ListActivity {
MainListAdapter mladp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prs__main_list_);
ArrayList<MainMenuItem> menuItems = new ArrayList<MainMenuItem>();
menuItems.add(new MainMenuItem(getResources().getString(R.string.main_list_connectivity), getResources().getString(R.string.main_list_connectivityDesc)));
this.mladp = new MainListAdapter(this, R.layout.man_list_item, R.id.textView1, menuItems);
setListAdapter(mladp);
}
}
Create a class for menu items:
public class MainMenuItem {
private String itemText;
private String itemDescription;
private String itemIMG;
private int itemWeight;
private String itemAssociatedActivity;
public MainMenuItem(String itemText, String itemDescription) {
this.itemText = itemText;
this.itemDescription = itemDescription;
}
public String getItemText() {
return itemText;
}
public void setItemText(String itemText) {
this.itemText = itemText;
}
public String getItemIMG() {
return itemIMG;
}
public void setItemIMG(String itemIMG) {
this.itemIMG = itemIMG;
}
public int getItemWeight() {
return itemWeight;
}
public void setItemWeight(int itemWeight) {
this.itemWeight = itemWeight;
}
public String getItemAssociatedActivity() {
return itemAssociatedActivity;
}
public void setItemAssociatedActivity(String itemAssociatedActivity) {
this.itemAssociatedActivity = itemAssociatedActivity;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
}
Custom array adapter:
public class MainListAdapter extends ArrayAdapter<MainMenuItem> {
ArrayList<MainMenuItem> menuItems;
public MainListAdapter(Context context, int resource,
int textViewResourceId, ArrayList<MainMenuItem> menuItems) {
super(context, resource, textViewResourceId, menuItems);
this.menuItems = menuItems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.man_list_item, parent);
}
MainMenuItem it = menuItems.get(position);
if (it != null) {
TextView titleTV = (TextView) view.findViewById(R.id.textView1);
TextView descriptionTV = (TextView) view.findViewById(R.id.textView2);
ImageView iconIV = (ImageView)view.findViewById(R.id.imageView1);
if (titleTV != null) {
titleTV.setText(it.getItemText());
}
if(descriptionTV != null){
descriptionTV.setText(it.getItemDescription());
}
if(iconIV != null){
if(it.getItemText().equals(getContext().getResources().getString(R.string.main_list_connectivity)))
iconIV.setImageResource(R.drawable.network_connections);
}
}
return view;
}
}
and here are my activity layout and item layout:
<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=".PRS_MainList_Act" >
<ListView android:id="#android:id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</LinearLayout>
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="horizontal" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
I got this error saying: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
Thanks in advance for your help.
You can't use this version of the inflate method:
view = vi.inflate(R.layout.man_list_item, parent);
because this will add the inflated View to the parent, which isn't allowed in a ListView. Instead use this version:
view = vi.inflate(R.layout.man_list_item, parent, false);
which will inflate the view but will not add it to the parent. This version is important because it will provide the proper LayoutParams for your inflated view.

Categories

Resources