onItemClickListener not firing on custom ArrayAdapter - android

I have an Activity that retrieves data from a web service. This data is presented in a ListView via an ArrayAdapter which inflates a RelativeLayout with three TextViews inside, nothing fancy and it work fine.
Now I want to implement a Details Activity that should be called when a user clicks an item in the ListView, sounds easy but I can't for the life of me get the onItemClickListener to work on my ArrayAdapter.
This is my main Activity:
public class Schema extends Activity {
private ArrayList<Lesson> lessons = new ArrayList<Lesson>();
private static final String TAG = "Schema";
ListView lstLessons;
Integer lessonId;
// called when the activity is first created.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// can we use the custom titlebar?
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
// set the view
setContentView(R.layout.main);
// set the title
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
// listview called lstLessons
lstLessons = (ListView)findViewById(R.id.lstLessons);
// load the schema
new loadSchema().execute();
// set the click listeners
lstLessons.setOnItemClickListener(selectLesson);
}// onCreate
// declare an OnItemClickListener for the AdapterArray (this doesn't work)
private OnItemClickListener selectLesson = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int i, long l) {
Log.v(TAG, "onItemClick fired!");
}
};
private class loadSchema extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
// ui calling possible
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Schema.this,"", "Please wait...", true);
}
// no ui from this one
#Override
protected Void doInBackground(Void... arg0) {
// get some JSON, this works fine
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
// apply to list adapter
lstLessons.setAdapter(new LessonListAdapter(Schema.this, R.layout.list_item, lessons));
}
My ArrayAdapter code:
// custom ArrayAdapter for Lessons
private class LessonListAdapter extends ArrayAdapter<Lesson> {
private ArrayList<Lesson> lessons;
public LessonListAdapter(Context context, int textViewResourceId, ArrayList<Lesson> items) {
super(context, textViewResourceId, items);
this.lessons = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
Lesson o = lessons.get(position);
TextView tt = (TextView) v.findViewById(R.id.titletext);
TextView bt = (TextView) v.findViewById(R.id.timestarttext);
TextView rt = (TextView) v.findViewById(R.id.roomtext);
v.setClickable(true);
v.setFocusable(true);
tt.setText(o.title);
bt.setText(o.fmt_time_start);
rt.setText(o.room);
return v;
}
}// LessonListAdapter
The main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="#+id/main"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent" android:layout_width="fill_parent"
android:screenOrientation="portrait"
>
<!-- student name -->
<TextView
android:id="#+id/schema_view_student"
android:text="Name" android:padding="4dip"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center_vertical|center_horizontal"
style="#style/schema_view_student"
/>
<!-- date for schema -->
<TextView
android:id="#+id/schema_view_title"
android:layout_height="wrap_content"
android:layout_margin="0dip"
style="#style/schema_view_day"
android:gravity="center_vertical|center_horizontal"
android:layout_below="#+id/schema_view_student"
android:text="Date" android:padding="6dip"
android:layout_width="fill_parent"
/>
<!-- horizontal line -->
<View
android:layout_width="fill_parent"
android:layout_height="1dip"
android:background="#55000000"
android:layout_below="#+id/schema_view_title"
/>
<!-- list of lessons -->
<ListView
android:id="#+id/lstLessons"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_below="#+id/schema_view_title"
/>
</RelativeLayout>
The 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="60px"
android:padding="12dip">
<TextView
android:id="#+id/timestarttext"
android:text="09:45"
style="#style/LessonTimeStartText"
android:layout_width="60dip"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_height="fill_parent" android:gravity="center_vertical|right" android:paddingRight="6dip"/>
<TextView
android:id="#+id/titletext"
android:text="Test"
style="#style/LessonTitleText"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_toRightOf="#+id/timestarttext"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true" android:gravity="center_vertical|center_horizontal"/>
<TextView
android:id="#+id/roomtext"
android:text="123"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
style="#style/LessonRoomText"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:gravity="center_vertical" />
</RelativeLayout>
Been messing with this for the last couple of hours and I can't seem to get my head around what the problem is. My problem looks very similar to this question, but I'm not extending ListActivity, so I still don't know where my onListClickItem() should go.
UPDATE: Now I've puzzled with this for several days and still can't find the issue.
Should I rewrite the activity, this time extending ListActivity instead of Activity? Because it provides the onItemClick method itself and is probably easier to overwrite.
Or, should I bind a listener directly in each getView() in my ArrayAdapter? I believe I have read this is bad practice (I should do as I tried and failed in my post).

Found the bug - it seems to be this issue. Adding android:focusable="false" to each of the list_item.xml elements solved the issue, and the onclick is now triggered with the original code.

I've encountered the same issue and tried your fix but couldn't get it to work. What worked for me was adding android:descendantFocusability="blocksDescendants" to the <RelativeLayout> from the item layout xml, list_item.xml in your case. This allows onItemClick() to be called.

What worked for me :
1) Adding android:descendantFocusability="blocksDescendants" to Relative Layout tag.
The result is shown below :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants" >
2) Adding android:focusable="false" to every element in in list_item.xml
example :
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:focusable="false" />

Once I had a similar problem. Every list item had a text view and a checkbox, and just because the checkbox, the whole listitem wasn't 'enabled' to fire the event. I solved it by making a little trick inside the adapter when I was getting the view.
Just before returning the view I put:
v.setOnClickListener(listener);
(The object listener is an onItemClickListener I gave to the Adapter's constructor).
But I have to tell you, the problem is because the platform, it is a bug.

I had the same problem and I tried to solve it by adding
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
to my item.xml but it still doesn't work !!! Infact I found the issue in the relative layout witch contains
android:focusableInTouchMode="true" android:focusable="true"
And when I removed it All things is ok

protected void onPostExecute(Void result) {
progressDialog.dismiss(); stLessons.setAdapter(new LessonListAdapter(Schema.this, R.layout.list_item, lessons));
//add this
ListView lv = getListView(); lv.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
//do stuff
}
});
}

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.

Can the main activity be able to grab elements from two XML files?

UPDATE WITH CODE (Sorry for crappy formatting of my code, some reason it had problems allowing me to post it so I had to mess with the lines for a whole to get it to allow me to save thisedit)
Here is the idea. I have an app that works with Clarifia's image recognition. I generated the app using Google's pre built navegation bar, so there is extra xml files and code for that, but it can be ignored the two needed for this is activity_main.xml and content_main.xml. anyways in content_main.xml it is a linear layout that has an imageview and a listview. My goal is to dynamically generate the listview with a list of BUTTONS. each button will have setText() done to it to give it a tag, so for example if a image selected is a dog, and the tags are dog, animal, etc, then that many buttons will be generated, with a setText() of one button being dog, the other button being animal, etc . now Since I have to do a network call, the network call is done in asynctask. After it is done, the method onPostExecute() is called and from there I get the tags. NOW since i got the tags, I want to call set an adapter that will hold an array of buttons, and loop geting the ID for each button and doing settext() on each button with the tags. from there i want to set the adapter to the list view..
Problems:
way to many to count, but I THINK i narrowed it down to me not knowing how to get the "views" from the second xml file to have the elements be used on the first xml file, because everything comes out NULL. I tried googling it but i just keep running into road blocks. I just want to name each button with a tag and put them into listview, but like i said, since these elements are in a different xml file than main_activity, I think this is the problem. so here is the code per request.
MainActivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
{
private static final String CLASS = MainActivity.class.getSimpleName();
private Button selectButton;
private Toolbar toolbar;
private NavigationView navigationView;
private Clari
faiData cdata = null;
private ImageView imageview;
private ListView listview;
private TagAdapter adapter;
private List<Button> data;
protected Context context;
private GoogleApiClient client;
protected LinearLayout main;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// THIS IS MY ATTEMPT TO DO THIS
// http://www.java2s.com/Code/Android/UI/UsingtwolayoutxmlfileforoneActivity.htm
super.onCreate(savedInstanceState);
context = MainActivity.this;
main = new LinearLayout (this);
setContentView(R.layout.activity_main);
// AUTO GENERATED stuff left out for nav bar, just showing this line*********
selectButton = (Button) findViewById(R.id.select_button);
selectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent media_intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// START API OVER NET
startActivityForResult(media_intent, cdata.getOKCode());
}
});
// MY STUFF********************************************************
cdata = new ClarifaiData(this);
imageview = (ImageView) findViewById(R.id.image_view);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == cdata.getOKCode() && resultCode == RESULT_OK)
{
Uri image = intent.getData();
if (image != null) {
// LEFT OUT STUFF FOR IMAGE RESIZING***************************
//************************************************** START LOOKING HERE***************************************
new AsyncTask<Uri, Void, RecognitionResult>()
{
#Override
protected RecognitionResult doInBackground(Uri... image)
{
// SO API CALL OVER INTERNET, SO NEEDED ASYNC
return cdata.recognizeBitmap(image[0]);
}
#Override
protected void onPostExecute(RecognitionResult result)
{
super.onPostExecute(result);
if (cdata.getTags(result))
{
selectButton.setEnabled(true);
selectButton.setText("Select a photo");
// MY ATTEMPT TO GET THE
// http://www.java2s.com/Code/Android/UI/UsingtwolayoutxmlfileforoneActivity.htm
LayoutInflater inflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout taglayout = (LinearLayout) inflate.inflate(R.layout.tag_list_item_trio_item, null);
LinearLayout.LayoutParams parm = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
listview = (ListView) main.findViewById(R.id.tagview);
main.addView(taglayout, parm);
// this is a arraylist of tags that hold strings
List tags = cdata.getMapTags();
// data is a array of buttons, each button will be labled by each value in tags
data = new ArrayList<Button>();
for (int i = 0; i < tags.size(); i++)
{
// GET ID FOR EACH BUTTON AND PUT IT INTO ARRAY THEN SETTEXT
String loc = "button_item_" + i;
int ID = getResources().getIdentifier(loc, "id", getPackageName());
Button temp = (Button) main.findViewById(R.id.button_item_0);
temp.setText("TEST " + i);
}
// HERE IS THE PROBLEM, I NEED A WAY TO GET THE LAYOUT STUFF FROM MAIN ACTIVITY
adapter = new TagAdapter(MainActivity.this, getResources().getIdentifier("tag_list_item_trio_item", "id", getPackageName()), data);
listview.setAdapter(adapter);
}
else
bottomToast(cdata.getRecError());
}
}.execute(image);
} else {
bottomToast(cdata.getLoadError());
}
}
}
tagAdapter.java
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class TagAdapter extends ArrayAdapter<Button> {
private Context context;
private List<Button> taglist;
public TagAdapter(Context context, int resource, List<Button> objects) {
super(context, resource, objects);
Log.i("Test", "constructor " );
this.context = context;
this.taglist = objects;
}
#Override
public int getCount()
{
return taglist.size();
}
getView(int, android.view.View, android.view.ViewGroup)
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.tag_list_item_dual_item, parent, false);
final Button tag = taglist.get(position);
View view = null;
view = layoutInflater.inflate(R.layout.tag_list_item_trio_item, parent, false);
else
{
view = layoutInflater.inflate(R.layout.tag_list_item_dual_item, parent, false);
Button nameTextView = (Button) view.findViewById(R.id.first_button_dual_item);
nameTextView.setText("test");
Button nameTextView2 = (Button) view.findViewById(R.id.second_button_dual_item);
nameTextView2.setText("test2");
}
return view;
}
}
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
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"
android:gravity="center|bottom"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<ImageView
android:layout_width="match_parent"
android:layout_height="0dp"
android:adjustViewBounds="true"
android:id="#+id/image_view"
android:background="#653fff"
android:layout_weight="0.5"
android:padding="1dp" />
<ListView
android:id="#+id/tagview"
android:layout_width="match_parent"
android:layout_weight="0.35"
android:layout_height="0dp"
android:padding="5dp"
android:background="#68343f"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal"
android:textAlignment="center" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_gravity="center_horizontal"
android:textAlignment="center"
/>
<Button
android:id="#+id/select_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sel_image"
android:layout_marginTop="8dp"
android:layout_marginBottom="16dp"
android:paddingLeft="24dp"
android:paddingRight="24dp"
android:background="#3d88ec" />
</LinearLayout>
tag_list_item_trio.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAlignment="center"
android:layout_centerInParent="true"
android:orientation="horizontal">
<Button
android:id="#+id/button_item_0"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#000000"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:text="TEST 1"
android:textColor="#ffffff"
/>
<Button
android:id="#+id/button_item_1"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#000000"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:text="TEST 2"
android:textColor="#ffffff"
/>
<Button
android:id="#+id/button_item_2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#000000"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:text="TEST 3"
android:textColor="#ffffff"
/>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAlignment="center"
android:layout_centerInParent="true"
android:orientation="horizontal">
<Button
android:id="#+id/button_item_0"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#000000"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:text="TEST 1"
android:textColor="#ffffff"
/>
<Button
android:id="#+id/button_item_1"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#000000"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:text="TEST 2"
android:textColor="#ffffff"
/>
<Button
android:id="#+id/button_item_2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#000000"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:text="TEST 3"
android:textColor="#ffffff"
/>
</LinearLayout>
One thing you should know is a Listview and its items are virtualized or recycled/reused or duplicated if i should say. so from how i see it i think your approach is off.
This is how i suggest you rectify it, before i get to that i want to clarify the way i understood a portion of your requirement
My goal is to dynamically generate the listview with a list of BUTTONS. each button will have setText() done to it to give it a tag, so for example if a image selected is a dog, and the tags are dog, animal, etc, then that many buttons will be generated, with a setText() of one button being dog
so you are saying you want a listView with 4 buttons on each row.
Do this, _i am taking relevant portions.
private ListView listview; //your listview
private TagAdapter adapter; // your adapter
//we are in oncreate
//i have no knowledge on cdata so bare with me here
//now remove List<Button> data; from your code
we have jumped to the TagAdapter class
private Context context;
//private List<Button> taglist; remove this also
private ArrayList<TheClassThatContainsTags> myTags;//i am assuming this will be cdata or?
//but this list should contain what setText() for a button will get its text
public TagAdapter(Context context) { //this is how your constructor will look
super(context);
Log.i("Test", "constructor " );
this.context = context;
//here you start your async task and put your async task logic here
//if the async task requires some objects or items which is not in this class
// since this is a separate class, you can inject them, when i say inject
// put them in the constructor of TagAdapter like you inject the Context
//object instance, so it might change to
// public TagAdapter(Context context,OneMoreClassIfIWant omciiw) {
// here you aysnc task will execute, now when onPostExecute is triggered/
//called you will do the following, but so remove all the code lines
// you currently have under onPostExecute
// onPostExecute has triggered
myTags = // the tag items result from onpostExecute
//now your myTags Arraylist of type TheClassThatContainsTags has been
//instantiated
}
we are now moving to getCount still in your custom adapter
#Override
public int getCount() {
return (myTags == null) ? 0 : myTags.size();
}
we are now moving to getView still in your custom adapter
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//in your posted getview, did you edit that too? if not does it give you errors?
//nevermind
// what you do here is check if convertView is null and instantiate it
// the position here in your method parameter is the index in your myTags
// list
if(convertView == null){
//guess you know how to do this. it should be the same as your old
//getview minus this final Button tag = taglist.get(position);
// and the line below it.
}
//here we are still in the getview - what you do is ,
you find what particular button you want by convertView.findViewById()
//my understanding as i pointer out is you want to have 4 buttons in a row
//it should be something like this
Button b = convertView.findViewById(R.id.button1);
b.setText(getItem(position));//getItem() is an instance method for the
//class you are extending, and it returns an Object of Type T, which in my
//example is TheClassThatContainsTags.class;
// and you can do the same for the next 3 buttons
}
we are out of your getview and custom adapter class , and we are in your oncreate .
here set when you need your tags then you do
tagAdapter = new TagAdapter(context,anyIfDesired_OtherInjections);
listview.setAdatper(tagAdapter);
now you are done. Hope it helps, also please read listview and Arraylist Adapter so you get a foresight of what you are doing and what i have posted here. it will help you trim down the hours you waste, if you spend 12 hours on the docs your will spend 5 minutes writing this and the next time you want to replicate it will be the same 5 minutes.
Be good sir and wish you success.

Dynamic questionnaire in Android

i want to make a questionnaire with Android Studio. Each question can be answered with yes or no. The problem is, that i have some follow-up questions (f.e. if question 1 answered with yes, then i have 3 follow-up questions to answer). Maybe it is important to know, that there are only follow-up questions if the user is clicking on the yes Button for some questions (there are never follow-up questions if he is clicking no)
I am an absolute beginner, so tell me if you have other ideas to solve this problem.
My idea is to make a custom listview and if the user is clicking on the first answer, i want to update the list and add questions if they are needed now (would be ok if the new questions are getting to the end of the list).
That's my Code till now:
questions_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/questionsListView"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:descendantFocusability="blocksDescendants"/>
</RelativeLayout>
itemView.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/question"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<RadioGroup
android:orientation="horizontal"
android:id="#+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/question">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yes"
android:id="#+id/yesButton"
android:layout_marginLeft="135dp" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No"
android:id="#+id/noButton"
android:layout_marginRight="50dp"/>
</RadioGroup>
</RelativeLayout>
LoggedInActivity.java:
public class LoggedInActivity extends Activity {
public List<Questions> myquestions = new ArrayList<Questions>();
public List<Integer> answerList = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questions_activity);
populateQuestions();
populateListView();
registerClickCallback();
}
private void registerClickCallback(){
ListView list = (ListView) findViewById(R.id.questionsListView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
boolean clickedQuestion = myquestions.get(position).getAnswer();
}
});
}
private void populateQuestions() {
myquestions.add(new Questions("Question1"));
myquestions.add(new Questions("Question2"));
myquestions.add(new Questions("Question3"));
}
private void populateListView() {
ArrayAdapter<Questions> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.questionsListView);
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<Questions> {
public MyListAdapter() {
super(LoggedInActivity.this, R.layout.item_view, myquestions);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
Questions currentQuestion = myquestions.get(position);
TextView question = (TextView) itemView.findViewById(R.id.question);
question.setText(currentQuestion.getQuestion());
RadioGroup answers = (RadioGroup) itemView.findViewById(R.id.radioGroup);
return itemView;
}
}
The OnClickListener doesn't work at all. I know, i need to do something with the RadioGroup in getView, but i don't know how (already tried to progress with solutions from here(Customized ListView with TextView, TextView, RadioGroup in Android) but it doesn't worked.
Is it even possible to add new questions and delete them if he is changing his opinion or are there better solutions?
I would offer you solutions on the onClick Listener part
Try any of the following steps
1. Try making use of your onClick listener in the onCreate method directly
2 You can implement View.OnClickListener, after that you create an onclick method. Inside the onclick method you can now perform any action you wish to perform

Android Custom ListView Rows: Text Style not being applied

Trying to create custom rows in my listview (to look like this). I've created a custom row layout & derived adapter class. The data loads and shows fine, but the text is not using any format/style specified in my custom row .xml layout file. It's all just the default size/weight, etc.
Here's the custom row layout (listview_desc.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#222222">
<TextView
android:id="#+id/name"
android:text="Name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_margin="10dip"
android:textStyle="bold"
android:textSize="20dip"
/>
<TextView
android:id="#+id/description"
android:text="Description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_margin="10dip"
android:textSize="13dip" />
</LinearLayout>
Here's my main layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:theme="#android:style/Theme.NoTitleBar"
android:minWidth="25px"
android:minHeight="25px"
android:background="#drawable/gradient_darkbg">
<ListView
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView1" />
</LinearLayout>
My adapter code (I'm using Xamarin, but I don't think that's the problem...)
public class ListViewFormAdapter : BaseAdapter<Form>
{
List<Form> mForms;
Activity context;
public ListViewFormAdapter(Activity context, List<Form> items)
: base()
{
this.context = context;
this.mForms = items;
}
public override long GetItemId(int position)
{
return position;
}
public override Form this[int position]
{
get { return mForms[position]; }
}
public override int Count
{
get { return mForms.Count; }
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = mForms[position];
View view = convertView;
if (view == null) // no view to re-use, create new
view = context.LayoutInflater.Inflate(Resource.Layout.listview_desc, null);
view.FindViewById<TextView>(Resource.Id.name).Text = item.Name;
view.FindViewById<TextView>(Resource.Id.description).Text = item.Description;
return view;
}
}
And finally the main activity where I load and use the adapter:
public class HomeScreenActivity : Activity
{
List<Form> mForms;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create your application here
SetContentView (Resource.Layout.Home);
// Load all forms and populate the main menu
mForms = Utils.FormLoader.LoadForms("Forms");
ListView listView = FindViewById<ListView>(Resource.Id.listView1);
listView.Adapter = new ListViewFormAdapter(this, mForms);
}
}
Sorry for all the code, maybe it'll help someone in the future... thanks for any help.
I'm not sure that this is the problem, but you inflating the views incorrectly. it should be
view = inflater.inflate(R.layout.listview_desc, parent, false);
instead of
view = context.LayoutInflater.Inflate(Resource.Layout.listview_desc, null);
using the 3 parameter version of inflate
What styles aren't showing correctly? I'm not sure what you're expecting or what you're seeing from the question. If it is to do with alignment, you should bear in mind that android:layout_alignParentLeft="true" is not valid in a LinearLayout
Thanks for the response guys. Turns out it was some problem with Git/Xamarin. I committed my sources at another machine, came home, synced up and all my formatting in the row layout xml were gone. Who knows... maybe a cached version was being used or something. I actually had to use the code posted on this page to get it to work (since it was lost), so maybe someone can use this as example code. It works.

Why does ListView stays above TextView in ListPreference dialog?

I need to create a custom ListPreference dialog so that I can add some header text (a TextView) above the List (ListView).
I've created MyListPreference class that extends ListPreference and overrides onCreateDialogView():
#Override
protected View onCreateDialogView() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = (View) inflater.inflate(R.layout.dialog_preference_list, null);
return v;
}
My XML layout dialog_preference_list.xml contains:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:scrollbarAlwaysDrawVerticalTrack="true" />
</LinearLayout>
Problem: The TextView is displayed below the ListView instead of above. I need the TextView to be above. I've tried both with LinearLayout and RelativeLayout (using "below" or "above" attributes) with no success: I can't find a way to put the TextView above the ListView... The layout is pretty simple and I cannot see why the list stays above...
Also, note that the problem occurs on both a real device (Nexus 4, Android 4.2.2) and the emulator. However, when looking at the layout rendered in Eclipse's graphical layout, the layout is correct! See both attached pictures.
Any idea on how to solve this?
Layout rendered on the device (incorrect):
Layout rendered on Eclipse (correct):
Edit with solution 10.07.2013
As suggested by the accepted answer, the problem comes from the use of builder.setSingleChoiceItems() in ListPreference's onPrepareDialogBuilder().
I've fixed it by extending ListPreference and overriding onCreateDialogView() to build the Dialog without the builder so that I can create a custom View showing the header text above the list items.
GPListPreference.java:
public class GPListPreference extends ListPreference {
...
#Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
builder.setNegativeButton(null, null);
builder.setPositiveButton(null, null);
}
private int getValueIndex() {
return findIndexOfValue(getValue());
}
#Override
protected View onCreateDialogView() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ListView lv = (ListView) inflater.inflate(R.layout.dialog_preference_list, null);
TextView header = (TextView) inflater.inflate(R.layout.dialog_preference_list_header, null);
header.setText(getDialogMessage()); // you should set the header text as android:dialogMessage in the preference XML
lv.addHeaderView(header);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(), R.layout.dialog_preference_list_singlechoice, getEntries());
lv.setAdapter(adapter);
lv.setClickable(true);
lv.setEnabled(true);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setItemChecked(getValueIndex() + 1, true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setValueIndex(position - 1);
getDialog().dismiss();
}
});
return lv;
}
}
dialog_preference_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:scrollbarAlwaysDrawVerticalTrack="true" />
dialog_preference_list_singlechoice.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:ellipsize="marquee"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:paddingBottom="2dip"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="2dip"
android:textAppearance="?android:attr/textAppearanceMedium" />
dialog_preference_list_header.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dip"
android:textAppearance="?android:attr/textAppearanceSmall">
</TextView>
I think the problem is with the way ListPreference works. ListPreference uses Builder.setSingleChoiceItems() to create the rows with the RadioButtons, and it has preference over the custom layout you are trying to add (in your case a TextView and a ListView inside a LinearLayout. The solution is extending DialogPreference instead. Here is a link to a GitHub where I created a custom DialogPreference that does what you need. I haven't coded the RadioButton logic.
I guess it's a theming issue. Try changing the theme of your dialog inside the constructor make it something like setStyle(STYLE_NO_TITLE, R.style.AppTheme). Your base app theme with no_title style.
If this is not the issue than it might be related with the ListPreference class itself. It might be overriding your layout for consistency in theming the preference views. However, I have not used ListPreference before, so its just a guess.
Can you reproduce the same result by playing with the themes in XML graphical layout preview?
Another option you can try is to add the TextView as a header to the ListView like this:
TextView textView = new TextView(getActivity());
ListView listView = new ListView(getActivity());
listView.addHeaderView(textView);
The addHeaderView takes a View so you theoretically have anything you want to be the header, but I have only used a TextView.
The link above is broken. On this solution the idea is overriding the ListPreference, and inflating your own listview, with the data defined on the ListPreference.
#Override
protected View onCreateDialogView() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ListView lv = new ListView(getContext());
// Inflate the view into the header only if a message was set
if (getDialogMessage() != null && ! getDialogMessage().equals("") ) {
TextView header = (TextView) inflater.inflate(R.layout.dialog_preference_list_header, null);
header.setText(getDialogMessage());
lv.addHeaderView(header, null, false);
}
// Create a new adapter and a list view and feed it with the ListPreference entries
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(),
R.layout.custom_dialog_single_choice_list_adapter, getEntries());
lv.setAdapter(adapter);
lv.setClickable(true);
lv.setEnabled(true);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setItemChecked(getValueIndex() + 1, true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setValueIndex(position - 1);
getDialog().dismiss();
}
});
return lv;
}
Another important thing is to call onPrepareDialogBuilder and not calling super in it. This will avoid that the listview appears twice.
#Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
// Not calling super, to avoid having 2 listviews
// Set the positive button as null
builder.setPositiveButton(null, null);
}
private int getValueIndex() {
return findIndexOfValue(getValue());
}
Where dialog_preference_list_header is in my case only a TestView, but it could be a more complex view, and custom_dialog_single_choice_list_adapter could be something like this:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checkMark="?android:attr/listChoiceIndicatorSingle"
android:ellipsize="marquee"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:paddingBottom="2dip"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="2dip"
android:textAppearance="?android:attr/textAppearanceMedium" />

Categories

Resources