Dynamically hiding text in ListView - Not always working - android

I'm trying to set a TextView object to disappear in a ListView row if the TextView object has no text inside it.
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
final LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.members, parent, false);
}
final TextView header = (TextView) row.findViewById(R.id.listHeader);
header.setText(parsedList.get(position).header);
final TextView footer = (TextView) row.findViewById(R.id.listDescription);
if(parsedList.get(position).footer.length() == 0) {
footer.setVisibility(View.GONE);
} else {
footer.setText(parsedList.get(position).footer);
}
return row;
}
Manifest:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/listHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" android:layout_marginLeft="12dp" android:layout_marginRight="12dp" android:layout_marginTop="6dp" android:layout_marginBottom="6dp"/>
<TextView
android:id="#+id/listDescription"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall" android:layout_marginBottom="6dp" android:layout_marginLeft="24dp" android:layout_marginRight="12dp"/>
</LinearLayout>
When the Activity loads, everything displays as it should (Most of the time). However when I rotate the screen, some of the footer TextView objects disappear from the screen. This is even though when I run the debugger, footer.setVisibility(View.GONE); is never called.
Also in my manifest I have android:configChanges="orientation|keyboardHidden" set for the Activity.
EDIT: This issue also rarely occurs when the Activity is created. However it always occurs on screen rotation.

Replace With This.
if(parsedList.get(position).footer.length() == 0) {
footer.setVisibility(View.GONE);
} else {
footer.setText(parsedList.get(position).footer);
footer.setVisibility(View.VISIBLE);
}

Override this method in Activity:
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}

Have you tried using getText().length() in the if statement?
if(parsedList.get(position).footer.length() == 0)

Related

Android - OnItemClickListener only *sometimes* not working

I have a ListView in one of my activities that I have bound to an ArrayList using a custom ArrayAdapter. I have set an OnItemClickListener to the ListView which should call a method that starts another activity. However, I find that when I click on the ListView items, it only sometimes works. Sometimes it will start the activity as it should; other times it seems to detect the click (the ripple effect appears on the list item) but does nothing; other times it doesn't even appear to detect the click (the ripple effect doesn't appear).
I've tried all the usual suggestions that I've come across: blocking descendants on the parent view item, setting clickable and focusable to false on all the components of the item views, setting isEnabled to return true in the custom adapter, etc, but the behavior remains the same. Any help appreciated. Here is the relevant code:
Activity containing the ListView:
public class ViewCollectionActivity extends AppCompatActivity {
private final String className = this.getClass().getSimpleName();
private CollectionHandler collectionHandler;
private Context context;
private ArrayList<Game> displayedCollection;
private GameCollectionAdapter collectionAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_collection);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
context = this;
collectionHandler = CollectionHandler.getInstance(this);
TextView view = null;
if (collectionHandler.getDisplayedCollection().size() > 0) {
view = (TextView) findViewById(R.id.no_items_textview);
view.setVisibility(View.GONE);
}
String currentDate = collectionHandler.getDateLastSynchronised();
view = (TextView) findViewById(R.id.last_updated_textview);
view.setText("Last synchronised: " + currentDate + " Total games: " + String.valueOf(collectionHandler.getDisplayedCollection().size()));
collectionAdapter = collectionHandler.getCollectionAdapter();
ListView listView = (ListView) findViewById(R.id.collection_list_view);
listView.setAdapter(collectionAdapter);
AdapterView.OnItemClickListener collectionItemClickListener = new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
launchGameDetailsActivity(position);
}
};
listView.setOnItemClickListener(collectionItemClickListener);
}
public void launchGameDetailsActivity(int position){
Log.d(className,"Starting lauchGameDetailsActivity method");
collectionHandler.setSelectedGame(position);
Intent intent = new Intent(this,ViewGameDetailsActivity.class);
startActivity(intent);
Log.d(className, "Ending lauchGameDetailsActivity method");
}
The XML for the activity:
<?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: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="com.bleachedlizard.ludome.viewcollection.ViewCollectionActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Synchronise Collection"
android:onClick="synchroniseCollection"/>
<TextView
android:id="#+id/last_updated_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Last synchronised: "
android:textAlignment="center"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Display Collection"
android:visibility="gone"
android:onClick="displayCollection"/>
<ListView
android:id="#+id/collection_list_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</ListView>
<TextView
android:id="#+id/no_items_textview"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="You have no items in your collection."
android:textAlignment="center"
android:textSize="20sp"/>
</LinearLayout>
The XML for the item views:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/collection_item_layout"
android:layout_width="match_parent"
android:layout_height="75dp"
android:orientation="horizontal"
android:clickable="false"
android:descendantFocusability="blocksDescendants"
android:focusable="false"
android:focusableInTouchMode="false">
<ImageView
android:id="#+id/collection_item_image"
android:layout_width="75dp"
android:layout_height="75dp"
android:src="#drawable/testimage"
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
/>
<TextView
android:id="#+id/collection_item_name"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_vertical"
android:padding="16dp"
android:singleLine="false"
android:textColor="#android:color/darker_gray"
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
android:textIsSelectable="false"/>
<TextView
android:id="#+id/collection_item_plays"
android:layout_width="100dp"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:padding="8dp"
android:textColor="#android:color/darker_gray"
android:text="Plays: 0"
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
android:textIsSelectable="false"/>
</LinearLayout>
The code for the custom adapter:
public class GameCollectionAdapter extends ArrayAdapter<Game> {
private ArrayList<Game> collection;
public GameCollectionAdapter(Context context, int resource, ArrayList<Game> collection){
super(context, resource, collection);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout gameView = (LinearLayout) convertView;
LayoutInflater mInflater = LayoutInflater.from(getContext());
if (gameView == null) {
gameView = (LinearLayout) mInflater.inflate(R.layout.collection_item_view, null);
}
//Game game = collection.get(position);
Game game = super.getItem(position);
if (game != null) {
// This is how you obtain a reference to the TextViews.
// These TextViews are created in the XML files we defined.
TextView gameTitle = (TextView) gameView.findViewById(R.id.collection_item_name);
TextView numOfPlays = (TextView) gameView.findViewById(R.id.collection_item_plays);
ImageView thumbnail = (ImageView) gameView.findViewById(R.id.collection_item_image);
// check to see if each individual textview is null.
// if not, assign some text!
if (gameTitle != null){
gameTitle.setText(game.getTitle());
}
if (numOfPlays != null){
numOfPlays.setText("Plays: " + String.valueOf(game.getNumOfPlays()));
}
if (thumbnail != null){
thumbnail.setImageBitmap(game.getThumbnail());
}
}
// the view must be returned to our activity
return gameView;
}
#Override
public boolean isEnabled(int position) {
return true;
}
}
I discovered what was causing the problem: the way I had set up the array that backed the ListView meant that it was downloading and storing the Bitmaps for every element in the array all the time. Once I changed the implementation so that it only downloaded the images as the ListView required them, then that seemed to improve performance and the onClickListener started to work fine.
The implementation I used was the exact same one shown here:
http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
I think the issue is due to the position of the item selection whenever you click you have an list position which is passed to your method launchGameDetailActivity(int position) check with log or toast on item click what all the position you are getting do the needful.
Here is my code try this like this if it helps.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(RecipeClass.this, "Position is" + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RecipeClass.this, RecipeIngredients.class)
intent.putExtra("position", position);
startActivity(intent);
}
Check your arraylist value also whether they are not null.

Android ExpandableListView item images disappear

I have to display a list of football players in a list. No problem about that, everything works fine but the little flags for the nationality are disappearing while I scroll down my list.
Here is what it should look like : list item player OK
And here is the result I have after some scrolling : list item player NOK
I also have an Image for the portrait of the player and another one to show the shirt which are working fine.
Here is some part of my code (I only put some parts of it to reduce the size and to put away what's working but feel free to ask for more if you need) :
My item list layout (partial layout, you won't get the same result as the image show) :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="3dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="3dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/portrait"
android:layout_width="32dp"
android:layout_height="32dp"
android:background="#drawable/portrait_default" />
<LinearLayout
android:id="#+id/nationalityLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal" >
<ImageView
android:id="#+id/logoNationality"
android:layout_width="13dp"
android:layout_height="13dp"
android:layout_marginRight="3dp" />
<TextView
android:id="#+id/nationality"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="13dp" />
</LinearLayout>
<LinearLayout
android:id="#+id/shirt"
android:layout_width="40dp"
android:layout_height="32dp"
android:gravity="center_horizontal" >
<TextView
android:id="#+id/number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="5dp" />
</LinearLayout>
</LinearLayout>
I have a holder for my items :
private class ChildViewHolder {
public ImageView portrait;
public ImageView logoNationality;
public TextView nationality;
public LinearLayout nationalityLayout;
public LinearLayout shirt;
public TextView number;
public void reset() {
portrait.setImageBitmap(null);
portrait.setBackgroundResource(R.drawable.portrait_default);
nationalityLayout.setVisibility(View.VISIBLE);
nationality.setText("");
number.setText("");
}
}
And the getChildView from my adapter (with flags being a map filled while putting items in the adapter list and playerShirt a BitmapDrawable loaded before) :
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
ChildViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.liste_item, null);
holder = new ChildViewHolder();
holder.portrait = (ImageView) convertView.findViewById(R.id.portrait);
holder.nationalityLayout = (LinearLayout) convertView.findViewById(R.id.nationalityLayout);
holder.logoNationality = (ImageView) convertView.findViewById(R.id.logoNationality);
holder.nationality = (TextView) convertView.findViewById(R.id.nationality);
holder.shirt= (LinearLayout) convertView.findViewById(R.id.shirt);
holder.number = (TextView) convertView.findViewById(R.id.number);
convertView.setTag(holder);
} else {
holder = (ChildViewHolder) convertView.getTag();
holder.reset();
}
FootPlayer player = children.get(groupPosition).get(childPosition);
// Doing nothing with portrait for now
if (player.getNationality() != null) {
holder.nationalityLayout.setVisibility(View.VISIBLE);
holder.nationality.setText(player.getNationality());
if (player.getNatImg() != null) {
holder.logoNationality.setImageDrawable(flags.get(player.getNatImg()));
} else {
holder.logoNationality.setVisibility(View.INVISIBLE);
}
} else {
holder.nationalityLayout.setVisibility(View.GONE);
}
holder.shirt.setBackgroundDrawable(playerShirt);
holder.number.setText(String.valueOf(player.getNumber()));
return convertView;
}
Right now, flags are appearing at the beginning of the list, proving me that the flags map is correctly filled with my images, but while I scroll down they start to disappear randomly and in the end none of them show up anymore.
So important points are :
My flags map is correctly filled with BitmapDrawable (and correct keys)
My playerShirt is also a BitmapDrawable but doesn't disappear as flags do
I already tried to use setBitmapImage instead of setBitmapDrawable to set the flag image (and also set the background as I'm currently doing with the shirt)
I tried with drawable res images and I have the same result
I know that I go through my if condition to show the flag correctly
Any help about this issue would be greatly appreciated.
You are not setting logoNationality visibility back to VISIBLE, as you are doing with nationalityLayout. So I guess once it's gone for the first time, it remains invisible, even if you later reuse the view setting a drawable to it.
Have a look to the fixed code:
if (player.getNationality() != null) {
holder.nationalityLayout.setVisibility(View.VISIBLE); // <- SET VISIBLE, Well done!
holder.nationality.setText(player.getNationality());
holder.logoNationality.setVisibility(View.VISIBLE); // <- Missing line: SET VISIBLE as before.
if (player.getNatImg() != null) {
holder.logoNationality.setImageDrawable(flags.get(player.getNatImg()));
} else {
holder.logoNationality.setVisibility(View.INVISIBLE); // <- OK, no logo, so hide it.
}
} else {
holder.nationalityLayout.setVisibility(View.GONE); // No nationality, hides entire layout.
}

How to inflate a ListView to a View

I'm new here so i will try to explain my problems as good as i can.
I am trying to inflate a ListView into a View in my main activity. My main activity has some buttons and texts on the top of the Activity and there is enough space left for the listView. The listview is consisted of categories, represented as an imageView and a textview.
The problem im facing is that when i inflate the category_list_activity, the activity i created for the category list, two things happen:
The ListView takes over all the screen, which means i cannot touch neither the buttons nor the edittext, and also the ListView is empty.
I have created the Adapters needed and i have searched for some info here in stackof but i couldn't find any right answer.
Edit: due to solving the problem when the list was taking over the whole screen i remove the parts of code that is not needed.
The solution was to change the inflated activity's (activity_category_list.xml) height from "fill_parent" to "wrap_content". I also restricted the show code to the parts i think there is the problem about not loading the categories.
here is the parts of code i wrote:
MainActivity.java
public class MainActivity extends ActionBarActivity {
Activity a;
Button toogle_button;
Button go_button;
Button login_button;
EditText search_text;
View inflating_view;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
a = this;
inflating_view = findViewById(R.id.inflating_view);
ViewGroup parent =(ViewGroup) inflating_view.getParent();
int index = parent.indexOfChild(inflating_view);
parent.removeView(inflating_view);
inflating_view = getLayoutInflater().inflate(R.layout.activity_category_list, parent, false);
parent.addView(inflating_view, index);
inflating_view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast t = Toast.makeText(getApplicationContext(), "ListView clicked", Toast.LENGTH_SHORT);
t.show();
}
});
}
CategoryAdapter.java
private class Viewholder{
TextView category_text;
ImageView image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Viewholder holder = null;
Category category = categories.get(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = (View) inflater.inflate(R.layout.activity_category, null);
holder = new Viewholder();
holder.category_text = (TextView) convertView.findViewById(R.id.category_text);
holder.image = (ImageView) convertView.findViewById(R.id.category_image);
convertView.setTag(holder);
}else{
holder = (Viewholder) convertView.getTag();
}
holder.category_text.setText(category.getName());
holder.image.setImageURI(category.getImageUri());
return convertView;
}
}
CategoryListActivity.java
public class CategoryListActivity extends ActionBarActivity {
ListView category_list_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_list);
Log.d("Category List View", "Category list view is called");
category_list_view = (ListView) findViewById(R.id.category_list_view);
CategoryAdapter ca = new CategoryAdapter(getApplicationContext(),
TestValues.categories);
category_list_view.setAdapter(ca);
category_list_view.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Clicked Category" + parent.getItemIdAtPosition(position), Toast.LENGTH_LONG);
toast.show();
}
});
Log.d("Category List View", "Everything is loaded");
}
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="#000000"
style="#android:style/Theme.Black.NoTitleBar"
tools:context="com.example.aggro.activities.MainActivity" >
<Button
android:id="#+id/toggle_button"
android:layout_width="50dp"
android:layout_height="30dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:text="#string/toogle_list_en"
android:textSize="10dp"
/>
<TextView
android:id="#+id/search_text_view"
android:layout_toRightOf="#+id/toggle_button"
android:layout_alignParentTop="true"
android:text="#string/search_text_en"
android:layout_height="30dp"
android:paddingTop="7dp"
android:textSize="10dp"
android:textColor="#FFFFFF"
android:layout_width="wrap_content"/>
<EditText
android:id="#+id/search_text"
android:layout_width="150dp"
android:layout_height="30dp"
android:layout_alignParentTop="true"
android:textColor="#FFFFFF"
android:textSize="15dp"
android:background="#000000"
android:layout_toLeftOf="#+id/search_go"
android:layout_toRightOf="#+id/search_text_view" />
<Button
android:id="#+id/search_go"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_toLeftOf="#+id/login_button"
android:layout_alignParentTop="true"
android:text="#string/search_go_en"
android:textSize="10dp" />
<Button
android:id="#+id/login_button"
android:layout_width="50dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/login_en"
android:textSize="10dp" />
<View
android:id="#+id/inflating_view"
android:layout_below="#+id/toggle_button"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</RelativeLayout>
I have checked the CategoryListActivity.java alone and it works as it was supposed to, so i think the adapter works right.
If you need any other information please let me know.
Thanks in advance.
Why are you using View instead of ListView in your activity_main.xml?
Change this part of activity_main.xml
<View
android:id="#+id/inflating_view"
android:layout_below="#+id/toggle_button"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
by
<ListView
android:id="#+id/category_list_view"
android:layout_below="#+id/toggle_button"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
In your adapter replace
convertView = (View) inflater.inflate(R.layout.activity_category, null);
by
convertView = inflater.inflate(R.layout.activity_category, null);
No need to cast it.
Remove activity_category_list.xml and CategoryListActivity.java.
Initialize & use ListView & Adapter in MainActivity.java
Try this it will surely work.
In this case what you can do is, create a empty layout in your main activity xml. Set a ID for that. While inflating the listview, inflate it to that layout.
In activity_main.xml include a relative layout as follows. Your parent layout is relative_layout. Add another layout like this.
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/login_button" > //make sure you use this property to tell where you want to place the view in the screen. This should be below your last button.
</RelativeLayout>
Since login_button is last button in your view, i have recommended,
android:layout_below="#+id/login_button"

How to change color of arraylist item in custom listview based on positive or negative value

Im new to android and Im building an app to show stock prices from an XML feed.
I have got an array list containing 3 items. However, I want to change the color of one of the items in the array list to red if its -ve or green if its +ve.
I dont know how to do this or where in my code is best to do it.
Please help....
My Adapter class:
public class TheAdapter extends ArrayAdapter<TheMetal>{
public TheAdapter(Context ctx, int textViewResourceId, List<TheMetal> sites) {
super(ctx, textViewResourceId, sites);
}
#Override
public View getView(int pos, View convertView, ViewGroup parent){
RelativeLayout row = (RelativeLayout)convertView;
Log.i("StackSites", "getView pos = " + pos);
if(null == row){
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = (RelativeLayout)inflater.inflate(R.layout.row_metal, null);
}
TextView dispNameTxt = (TextView)row.findViewById(R.id.displayNameText);
TextView spotPriceTxt = (TextView)row.findViewById(R.id.spotPriceText);
TextView changeTxt = (TextView)row.findViewById(R.id.changeText);
dispNameTxt.setText (getItem(pos).getDisplayName());
spotPriceTxt.setText(getItem(pos).getSpotPrice());
changeTxt.setText(getItem(pos).getChange());
return row;
}
My row_metal layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" >
<TextView
android:id="#+id/displayNameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_marginLeft="20dp" />
<TextView
android:id="#+id/spotPriceText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/displayNameText"
android:textSize="19sp"
android:textStyle="bold"
android:gravity="right"
android:layout_alignParentRight="true"
android:layout_marginRight="30dp" />
<TextView
android:id="#+id/changeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/spotPriceText"
android:layout_toRightOf="#+id/displayNameText"
android:textSize="16sp"
android:gravity="right"
android:layout_alignParentRight="true"
android:layout_marginRight="20dp"
/>
It is so simple. You just need to place these line within your getView() method:
if (Double.parseDouble(getItem(pos).getChange())>=0) {
row.setBackgroundColor(Color.parseColor("#00FF00");
changeTxt.setTextColor(Color.parseColor("#00FF00"));
} else {
row.setBackgroundColor(Color.parseColor("#FF0000");
changeTxt.setTextColor(Color.parseColor("#FF0000"));
}
Change your getView() method to this
#Override
public View getView(int pos, View convertView, ViewGroup parent){
if(convertView == null)
convertView = getLayoutInflater().inflate(R.layout.row_metal, null);
TextView dispNameTxt = (TextView) convertView .findViewById(R.id.displayNameText);
TextView spotPriceTxt = (TextView) convertView .findViewById(R.id.spotPriceText);
TextView changeTxt = (TextView) convertView .findViewById(R.id.changeText);
dispNameTxt.setText(getItem(pos).getDisplayName());
spotPriceTxt.setText(getItem(pos).getSpotPrice());
changeTxt.setText(getItem(pos).getChange());
if( Double.parseDouble(getItem(pos).getSpotPrice()) >= 0 )
convertView.setBackgroundColor(Color.GREEN);
else
convertView.setBackgroundColor(Color.RED);
return convertView;
}

listview item with button not responding to onListItemClick

I am working on an app where the list item are complex, TextView and two ImageButtons. I have looked at the around for a solution, and tried all that I have seen, still nothing.
The list is part of the ListFragment on I have Override onListItemClick.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF" >
<TextView
android:id="#+id/medcine_info_txt"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="3dp"
android:textColor="#color/black" />
<ImageButton
android:id="#+id/item_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/medcine_info_txt"
android:layout_alignParentLeft="true"
android:contentDescription="#string/item_edit"
android:focusable="false"
android:focusableInTouchMode="false"
android:src="#android:drawable/ic_menu_edit" />
<ImageButton
android:id="#+id/item_history"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/medcine_info_txt"
android:layout_centerHorizontal="true"
android:contentDescription="#string/item_history"
android:focusable="false"
android:focusableInTouchMode="false"
android:src="#android:drawable/btn_star" />
</RelativeLayout>
This my adapter getView where I have on handle the buttons click, and it implements OnClickListener
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflator = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View listItem = inflator.inflate(R.layout.medcince_list_item, null);
ImageButton mEdit = (ImageButton)listItem.findViewById(R.id.item_edit);
mEdit.setOnClickListener(this);
mEdit.setTag(getItem(position));
ImageButton mHistory = (ImageButton)listItem.findViewById(R.id.item_history);
mHistory.setOnClickListener(this);
mHistory.setTag(getItem(position));
return listItem;
}
Any thoughts on why the onListItemClick is not handling the click?
I think your ImageButton is stealing away the onItemClickLister event. Add this attribute to your layout
android:descendantFocusability="blocksDescendants"
<TextView
android:id="#+id/medcine_info_txt"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:padding="3dp"
android:textColor="#color/black" />
<ImageButton
android:id="#+id/item_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
.......
Thanks
This is common question for ListView. I read source code about this.
Question: why onListItemClick not be called?
Answer:
AbsListView class override onTouchEvent method.
Snip code come from onTouchEvent method.
if (inList && !child.hasFocusable()) {
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
.....
}
PerformClick will be call if child.hasFocusable() return false which child is you ListView item view;
Snip code come from hasFocusable method.
#Override
public boolean hasFocusable() {
if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {return false; }
if (isFocusable()) {return true;}
final int descendantFocusability = getDescendantFocusability();
if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
final int count = mChildrenCount;
final View[] children = mChildren;
for (int i = 0; i
So solution:
Solution A,set ListView item descendantFocusability property, let its getDescendantFocusability() is not equal FOCUS_BLOCK_DESCENDANTS.
Solution B, ListView item all child views is not hasFocusable( hasFocusable() return false).
you can create View.OnClickListner object which can listen your imagebutton click in getView. onListItemClick generally used to handle row click event not items in rows.
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflator = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View listItem = inflator.inflate(R.layout.medcince_list_item, null);
ImageButton mEdit = (ImageButton)listItem.findViewById(R.id.item_edit);
mEdit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// HERE YOU CAN HANDLE BUTTON CLICK. POSITION YOU CAN HAVE FROM getView already.
}
});
mEdit.setTag(getItem(position));
ImageButton mHistory = (ImageButton)listItem.findViewById(R.id.item_history);
mHistory.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// HERE YOU CAN HANDLE BUTTON CLICK. POSITION YOU CAN HAVE FROM getView already.
}
});
mHistory.setTag(getItem(position));
return listItem;
}
Make the ListFragment implement the View.OnClickListener interface, and implement the code you want to be called when the button are pressed in the method OnClick(View view), which is #Override

Categories

Resources