Android: button showing up multiple times in list view - android

I trying to write code to highlight the selected value of the list with "Next" button at the bottom of the layout. But for some reason, after every list item, "next" button also shows up. Can someone please help me resolve this problem?
Here is the layout 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="match_parent"
android:orientation="vertical"
android:id="#+id/questionLayout"
>
<TextView android:id="#+id/txtExample"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textColor="#000000"
android:background="#FF0000"
/>
<ListView
android:id="#+id/listExample"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#CCCCCC"
android:choiceMode="singleChoice"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<Button
android:id = "#+id/next"
android:text="Next"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_gravity="center"
android:layout_weight="50"
/>
<Button
android:id = "#+id/submit"
android:text="Submit"
android:layout_width = "0dp"
android:layout_height = "wrap_content"
android:layout_weight="50"
android:layout_gravity="center"
/>
</LinearLayout>
</LinearLayout>
Java Code:
public class updateList extends Activity {
private SelectedAdapter selectedAdapter;
private ArrayList<String> list;
int correct_answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = new ArrayList<String>();
list.add("Choice One");
list.add("Choice Two");
list.add("Choice Three");
selectedAdapter = new SelectedAdapter(this,0,list);
selectedAdapter.setNotifyOnChange(true);
ListView listview = (ListView) findViewById(R.id.listExample);
listview.setAdapter(selectedAdapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {
// user clicked a list item, make it "selected"
selectedAdapter.setSelectedPosition(position);
}
});
}
}
Thanks in advance
SSP
Selected Adaptor class:
public class SelectedAdapter extends ArrayAdapter{
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public SelectedAdapter(Context context, int textViewResourceId,
List objects) {
super(context, textViewResourceId, objects);
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// only inflate the view if it's null
if (v == null) {
LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.activity_main, null);
}
// get text view
TextView label = (TextView)v.findViewById(R.id.txtExample);
// change the row color based on selected state
if(selectedPos == position){
label.setBackgroundColor(Color.CYAN);
}else{
label.setBackgroundColor(Color.WHITE);
}
label.setText(this.getItem(position).toString());
/*
// to use something other than .toString()
MyClass myobj = (MyClass)this.getItem(position);
label.setText(myobj.myReturnsString());
*/
return(v);
}
}

change your listview in xml as like this
<ListView
android:id="#+id/listExample"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"//===== set maximum heighthere
android:layout_marginBottom="50dp"// === give some space at bottom so that buttons will appear
android:background="#CCCCCC"
android:choiceMode="singleChoice"
/>

But for some reason, after every list item, "next" button also shows up.
The ListView's row layout is determined by the layout you inflate in getView() or pass to your Adapter's super class if you haven't overridden getView(). Double check this layout and remove the unwanted code.
Addition
The layout for your ListView's items only needs to be one TextView since you only want to display a phrase in each. However you are currently passing your entire main layout, this creates the Buttons, an unused ListView, and everthing else in every row...
Instead use android.R.layout.simple_list_item_1 in getView(), of course you'll need to change the id you pass to findViewById() as well:
if (v == null) {
LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(android.R.layout.simple_list_item_1, null);
}
// get text view
TextView label = (TextView)v.findViewById(android.R.id.text1);
Please watch Android's Romain Guy discuss writing an efficient adapter to speed things up.

Related

Android custom listview intents How to let it work?

I made a custom listView and custom array adapter with 1 image and 2 textviews. What I want to work is when you click on an item in the listview that it opens a new activity with an intent.
this is the mainactivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.?_main);
ListView listView = (ListView) findViewById(R.id.list);
ArrayList<Subjects> obsclassiclist = new ArrayList<Subjects>();
obsclassiclist.add(new Subjects("?", "?", R.mipmap.ic_launcher));
obsclassiclist.add(new Subjects("?", "?", R.mipmap.ic_launcher));
WordAdapter adapter = new WordAdapter(this, obsclassiclist);
listView.setAdapter(adapter);
LinearLayout listViewIntent = (LinearLayout) findViewById(R.id.intent);
listViewIntent.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
if (position==0) {
Intent tutorial = new Intent(view.getContext(),
Cl_01.class);
// Start the new activity
startActivityForResult(tutorial,0);
}
if (position==1) {
Intent requirements = new Intent(view.getContext(),
CL_02.class);
// Start the new activity
startActivityForResult(requirements,1);
}
}
});
}
}
this the custom adapter
public WordAdapter(Activity context, ArrayList<Subjects> subjects) {
// Here, we initialize the ArrayAdapter's internal storage for the context
and the list.
// the second argument is used when the ArrayAdapter is populating a single
TextView.
// Because this is a custom adapter for two TextViews and an ImageView, the
adapter is not
// going to use this second argument, so it can be any value. Here, we used
0.
super(context, 0, subjects);
}
/**
* Provides a view for an AdapterView (ListView, GridView, etc.)
*
* #param position The position in the list of data that should be displayed
in the
* list item view.
* #param convertView The recycled view to populate.
* #param parent The parent ViewGroup that is used for inflation.
* #return The View for the position in the AdapterView.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
// Get the {#link subject} object located at this position in the list
Subjects currentSubjects = getItem(position);
// Find the TextView in the list_item.xml layout with the ID subject
TextView subjectTextView = (TextView)
listItemView.findViewById(R.id.subject);
// Get the version name from the current wordadapter object and
// set this text on the subject TextView
subjectTextView.setText(currentSubjects.getObsclassicSubject());
// Find the TextView in the list_item.xml layout with the ID description
TextView descriptionTextView = (TextView)
listItemView.findViewById(R.id.description);
// Get the version number from the current wordadapter object and
// set this text on the description TextView
descriptionTextView.setText(currentSubjects.getObsclassicDescription());
// Find the Imageview in the list_item.xml layout with the ID version_number
ImageView pictureImageView = (ImageView)
listItemView.findViewById(R.id.image);
// Get the version number from the current wordadapter and
// set this image on the imageview
pictureImageView.setImageResource(currentSubjects.getObsclassicimageid());
// Return the whole list item layout (containing 2 TextViews and an
ImageView)
// so that it can be shown in the ListView
return listItemView;
}
}
here is the xml custom listview
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="#+id/intent"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/image"
android:scaleType="centerInside"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:textSize="20sp"
android:textStyle="bold"
android:id="#+id/subject"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:paddingBottom="10dp"
android:textSize="18sp"
android:textStyle="italic"
android:id="#+id/description"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
and the xml from the main activity
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list">
</ListView>
if somebody has a solution pls let me know
You are doing wrong, your are making clicklistener on linear layout, instead do it on ListView
Change this
listViewIntent.setOnItemClickListener(new
AdapterView.OnItemClickListener()
To
listView .setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Toast.makeText(SuggestionActivity.this, "" + position, Toast.LENGTH_SHORT).show();
// Now if you want to startActivity
Intent tutorial = new Intent(MainActivity.this,
Cl_01.class);
// Start the new activity
startActivityForResult(tutorial,position);
}
});

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.

getView in ArrayAdapter for ListFragment is called always with position=0

I have used a ListFragment with an ArrayAdapter to show a list of items. You can find the code below.
public class SelectRepiceFragment extends ListFragment {
private BuyRecipeActivity mActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Resources res = mActivity.getResources();
int recipeNum = res.getInteger(R.integer.recipe_number);
String[] titles = res.getStringArray(R.array.titles);
ArrayList<RecipeItem> recipeItems = new ArrayList<RecipeItem>(recipeNum);
for (int i = 0; i < recipeNum; i++) {
RecipeItem item = new RecipeItem();
item.title = titles[i];
recipeItems.add(item);
}
RecipeItemAdapter recipeItemAdapter = new RecipeItemAdapter(mActivity, recipeItems);
setListAdapter(recipeItemAdapter);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mActivity = (BuyRecipeActivity) activity;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
mActivity.onRecipeSelected(position);
}
}
The size of recipeItems is 3 (I check it with debugger). So the getView function in ArrayAdapter should be called 3 times to generate the ListFragment. Here I have copied the ArrayAdapter.
public class RecipeItemAdapter extends ArrayAdapter<RecipeItem> {
private final Activity mActivity;
static class ViewHolder {
public MyTextView title;
public ImageView image;
}
public RecipeItemAdapter(Activity context, ArrayList<RecipeItem> recipeItems) {
super(context, R.layout.recipe_list, recipeItems);
this.mActivity = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
// reuse views
if (rowView == null) {
LayoutInflater inflater = mActivity.getLayoutInflater();
rowView = inflater.inflate(R.layout.recipe_item, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.title = (MyTextView) rowView.findViewById(R.id.recipeItemTitle);
viewHolder.image = (ImageView) rowView.findViewById(R.id.recipeItemImage);
rowView.setTag(viewHolder);
}
// fill data
ViewHolder holder = (ViewHolder) rowView.getTag();
RecipeItem recipeItem = getItem(position);
holder.title.setText(recipeItem.title);
holder.image.setImageResource(R.drawable.ic_launcher);
return rowView;
}
}
The problem is that getView is actually called three times, while every time the position parameter is equal to 0. So After running the app, I just see a single row in my list instead of 3 rows.
UPDATE: I found out that I just see the first item, but if I scroll it up, then it shows the rest of items in that single row! Consequently I guessed there should be a mistake in the xml file. So I add xml files bellow.
This is my main activity xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- The main content view -->
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/fragmentView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center|top" />
</ScrollView>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#dcdcdc"
android:choiceMode="singleChoice"
android:divider="#dcdcdc"
android:dividerHeight="0.5dp" />
</android.support.v4.widget.DrawerLayout>
And this is my recipe_item xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="#+id/recipeItemTitle"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:background="#drawable/design_price_view"
android:gravity="center" />
<ImageView
android:id="#+id/recipeItemImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/app_icon" />
</LinearLayout>
UPDATE 2: I removed the DrawerLayout from my main activity xml and now I see the list. Just confusing.
You may try removing the ScrollView, take the FrameLayout out, put
layout_height="0dp"
layout_weight="1"
to the FrameLayout. You will need to manually fix the height of your navigation drawer to predefined pixel.
The above setup will make your FrameLayout & your ListView inside it take all the available space left from the navigational drawer.
The problem is, if you place a ListView inside a ScrollView - there is a rendering problem. I have not worked with ListView inside FrameLayout so cant really comment on that.
If you absolutely need to keep the ScrollView, you would need to re-render your ListView so that it spans the height it needs. Check this thread

Why is my custom SimpleCursorAdapter returning different reults when ListView is scrolling

I'm trying to implement a custom SimpleCursorAdapter in order to switch out layouts in a ListView but I'm getting very random results while scrolling.
My issue here is that when I scroll up and down, the ListView seemingly by random, mix up the layouts. For instance, a row can have the listview_item_row layout at first but when scrolling in and out of the screen it can be replaced by listview_item_reply_row and back again.
I can't say I've really understood how newView works. I have successfully been able to use bindView to determine if I'm to hide an image in the layout or not but new View is veiled in darkness to me about its implementation and why the list scrolling behaves the way it does.
My goal is to have a list with x amount of items. Depending on if the item is a reply or a new message I want to load a specific layout on that row. Depending on if the row has an image or not I want to show/hide the imageview in the row layout.
What I have omitted in the code are the imports and row layouts. I'm trying to implement this by using Fragments and SimpleCursorAdapter in the v4 support package. The row layouts for the ListFragment are visibly different but contain the same widgets.
The ListView layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/text_feed_header_random"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:padding="4dp"
android:text="Allmänt"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFF" />
<!--
The frame layout is here since we will be showing either
the empty view or the list view.
-->
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/text_feed_header_random"
android:layout_above="#+id/footer" >
<!--
Here is the list. Since we are using a ListActivity, we
have to call it "#android:id/list" so ListActivity will
find it
-->
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false" />
<!-- Here is the view to show if the list is emtpy -->
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="No items."
android:textAppearance="?android:attr/textAppearanceMedium" />
</FrameLayout>
<LinearLayout
android:id="#+id/footer"
style="#android:style/ButtonBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<Button
android:id="#+id/button_random_post"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Gör ett inlägg!" />
<Button
android:id="#+id/button_random_refresh"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Refresh list!" />
</LinearLayout>
</RelativeLayout>
A condensed Fragment using the layout above:
public class RandomFragment extends ListFragment implements LOG {
private DatabaseHelper mDbHelper;
private KarenfeedCursorAdapter mAdapter;
private Cursor mCursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "RANDOMFRAGMENT START!");
mDbHelper = new DatabaseHelper(getActivity());
mDbHelper.open();
mDbHelper.setTable(Posts.TABLE_RANDOM_POSTS);
//TODO: Replace SimpleCursorAdapter with a FragmentList instead...
mCursor = mDbHelper.getAllPostsSortedCursor();
String[] columns = { Posts.COLUMN_ID, Posts.COLUMN_CREATED, Posts.COLUMN_USER, Posts.COLUMN_COMMENT };
int[] to = { R.id.imageItemPhoto, R.id.textItemDate, R.id.textItemUser, R.id.textItemComment };
int flags = 0;
mAdapter = new FeedCursorAdapter(getActivity(), R.layout.listview_item_row, mCursor, columns, to, flags);
this.setListAdapter(mAdapter);
initFeedList(); // This call in the end executes mCursor = mDbHelper.getAllPostsSorted(); mAdapter.changeCursor(mCursor); mAdapter.notifyDataSetChanged();
}
}
The SimpleCursorAdapter that the ListFragment connects to:
public class FeedCursorAdapter extends SimpleCursorAdapter implements LOG {
private Context mContext;
private int mLayout;
public FeedCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
// TODO Auto-generated constructor stub
mContext = context;
mLayout = layout;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View view;
int id = cursor.getInt(cursor.getColumnIndex(Posts.COLUMN_ID));
int parentId = cursor.getInt(cursor.getColumnIndex(Posts.COLUMN_PARENT_ID));
Log.d(TAG, "id: " +id+ " parentId: " +parentId);
int hasImage = cursor.getInt(cursor.getColumnIndex(Posts.COLUMN_IMAGE));
if(id == parentId) {
view = inflater.inflate(R.layout.listview_item_row, parent, false);
} else {
view = inflater.inflate(R.layout.listview_item_reply_row, parent, false);
}
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
Log.d(TAG, "bindView()");
int id = cursor.getInt(cursor.getColumnIndex(Posts.COLUMN_ID));
int parentId = cursor.getInt(cursor.getColumnIndex(Posts.COLUMN_PARENT_ID));
int hasImage = cursor.getInt(cursor.getColumnIndex(Posts.COLUMN_IMAGE));
String date = cursor.getString(cursor.getColumnIndex(Posts.COLUMN_CREATED));
String user = cursor.getString(cursor.getColumnIndex(Posts.COLUMN_USER));
String comment = cursor.getString(cursor.getColumnIndex(Posts.COLUMN_COMMENT));
TextView dateView = (TextView) view.findViewById(R.id.textItemDate);
TextView userView = (TextView) view.findViewById(R.id.textItemUser);
TextView commentView = (TextView) view.findViewById(R.id.textItemComment);
ImageView imageView = (ImageView) view.findViewById(R.id.imageItemPhoto);
dateView.setText(date);
userView.setText(user);
commentView.setText(comment);
if(hasImage == 0) {
imageView.setVisibility(ImageView.GONE);
} else {
String bitmapPath = Environment.getExternalStorageDirectory().getPath() + "/feed/" + id + "_thumb.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
imageView.setImageDrawable(bitmapDrawable);
imageView.setVisibility(ImageView.VISIBLE);
}
}
}
after reading your question and the code i think you should know that whenever you scroll a listview up or down it communicates with the adapter to populate the new items that came in to focus and for the case of different row for different data you should make a arraylist that will contain the name or id of the items whose backgrounds are different and then you start making there background according to your need on every call to adapter.

Removing an Item with a Button in ListView with Custom ArrayAdapter

I have custom list_row :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content" android:baselineAligned="false">
<Button android:layout_width="30dip" android:layout_marginTop="7dip" android:gravity="right"
android:id="#+id/delete" android:layout_height="30dip" android:background="#drawable/delete"
android:layout_gravity="top"></Button>
<TextView android:textSize="20dip"
android:text="TextView" android:id="#+id/tavsiye" android:layout_marginTop="10dip"
android:layout_gravity="top" android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
I have a ListView like that:
<ListView
android:id="#+id/tavsiyeler"
android:layout_height="300dip"
android:layout_width="170dip"
android:fastScrollEnabled="true"
android:scrollbars="vertical"/>
and a custom adapter which extends ArrayAdapter :
public class HekimTavsiyeleriAdapter extends ArrayAdapter<String> {
private Context context;
private int resource;
private ArrayList<String> tavsiyeler;
public HekimTavsiyeleriAdapter(Context context, int resource,
ArrayList<String> objects) {
super(context, resource, objects);
this.context=context;
this.resource=resource;
this.tavsiyeler=objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(this.resource, null);
}
if (this.tavsiyeler.size()!=0) {
TextView tavsiye = (TextView) v.findViewById(R.id.tavsiye);
Button but= (Button) v.findViewById(R.id.delete);
if (tavsiye != null) {
String st=this.tavsiyeler.get(position);
tavsiye.setText(st);
}
if( but!=null){
but.setId(position);
but.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View v) {
int id=v.getId();
tavsiyeler.remove(id);
notifyDataSetChanged();
}
});
}
}
return v;
}
I am creating adapter and fill the list like that :
eklenecekTavsiyeler=new ArrayList<String>();
adapter= new HekimTavsiyeleriAdapter(context,
R.layout.hekim_tavsiyeleri_row, eklenecekTavsiyeler);
ListView tavsiyelerListesi = (ListView)findViewById(R.id.tavsiyeler);
tavsiyelerListesi.setAdapter(adapter);
And adding new items like that:
this.adapter.add(<some-string>);
this.adapter.notifyDataSetChanged();
and my list view is seen like that:
http://imageshack.us/photo/my-images/97/listir.jpg/
Here is my question:
I am adding new items to the list. I have fixed height for the list. When I fill the list until all height is occupied, then I add one new item to the list which requires scrolling becasue overflow in list height. The last item I added gets wrong id and when I pressed the cross button, it removes wrong item. However, when the list is not overflowed, everything works fine. After overflow, the ids of buttons are set wrongly (seems randomly). By the way, for setting the button's id, I am using getView's position argument.
Thanks in advance.
I am afraid that you have flaw in the code.
You have to stop calling but.setId(). With this you are overriding internal id of the view which is the value of R.id.delete. Probably you meant to use but.setTag() / but.getTag()?

Categories

Resources