I have a list view every item in list contains textviews and button what I want is when I click on the button of any item in list I want to printout the position of button if i clicked the button in first line i want to print out 0 and go on but it doesn't work
this is my method to display view
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCountries();
// The desired columns to be bound
String[] columns = new String[] {
PhonesDbAdapter.KEY_NAME,
PhonesDbAdapter.KEY_CONTINENT,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.continent,
R.id.name
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.phone_layout,
cursor,
columns,
to,
0);
listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
public void print(View v)
{
}
and here how my item look like
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip"
android:background="#f0f0f0" >
<TextView
android:id="#+id/continent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="#275a0d"/>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="TextView"
android:textColor="#000"/>
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/ic_launcher"/>
<Button
android:id="#+id/call"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/button1"
android:background="#drawable/ic_launcher"
android:onClick="print"/>
</RelativeLayout>
and this the layout that contain the listview
<?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="#f0f0f0">
<EditText android:id="#+id/myFilter" android:layout_width="match_parent"
android:layout_height="wrap_content" android:ems="10">
</EditText>
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
i spent alot of time with this problem and i hope that u can help me and im really sorry for my bad english
Are you implementing the method getView() on your adapter?
That's where you want to add the OnClickListener to your Button
Once you do that you can set the position as the tag of the Button and retrieve it on the onClick method.
Something like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.your_item_layout, parent, false);
Button myButton = (Button) row.findViewById(R.id. call);
myButton.setOnClickListener(new OnClickListener {
#Override
public void onClick(View view) {
int position = (int)view.getTag();
//Do whatever you want with the position here
}
});
myButton.setTag(position);
return row;
}
From last 3 three years I am not working on android so I am not sure my suggestion is correct or not. You need to test it for you purpose.
In your above case you cannot use onItemClickListner because it can only be used when you are tracking your complete list row. What I think is you can create a custom adapter and override its getView method. In getView method you will have your position and you can set button click listner for you button in getview. So In this way you can get your button position.
You try it once if you need some code then I can try to write it for you...
THIS IS HOW YOU CAN CREATE CUSTOM ADAPTER.
public class my_custom_adapter extends ArrayAdapter<String> {
private Context context = null;
ArrayList<String> elements = null;
public my_custom_adapter(Context context, int type, ArrayList<String> elements)
{
super(context, type, elements);
this.elements = elements;
this.context = context;
}
//THIS IS SIMPLY A CLASS VIEW WILL HOLD DIFFERENT VIEWS OF YOUR ROW.
static class ViewHolder
{
public TextView tv;
public Button cb;
}
#Override
public View getView (final int position, View convertView, ViewGroup parent)
{
View rowView = convertView;
ViewHolder holder = null;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
// HERE I AM INFLATING LISTVIEW LAYOUT.
rowView = inflater.inflate(R.layout.inflated_layout, null, false);
holder = new ViewHolder();
holder.cb = (Button) rowView.findViewById(R.id.checkBox1);
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
if (holder != null) {
holder.cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// IF YOUR BUTTON TAG HERE AND YOU CAN HAVE POSITION USING "position" PARAMETER
}
});
}
return rowView;
}
}
Related
I'm using a ListView with ArrayAdapter. There is a Button along with TextView in the listview.xml. I want to retrieve data from that TextView by Clicking over corresponding buttons.
My listview.xml is as follows:
<?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:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="90dp"
android:id="#+id/btConfirmfriend"
android:text="Confirm Friend"
/>
</RelativeLayout>
My PendingRequest Class is as follows:
public class PendingRequest extends AddFriend {
TextView tvPending;
Button btConfirmfriend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pendingrequest);
final String[] s= getIntent().getExtras().getStringArray("pending");
System.out.println(s[1]);
final ListAdapter adapter = new ArrayAdapter<String>(this,R.layout.listview,R.id.label,s);
final ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
final View inflatedView = getLayoutInflater().inflate(R.layout.listview, null);
btConfirmfriend = (Button) inflatedView.findViewById(R.id.btConfirmfriend);
btConfirmfriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ServerConnection sc = new ServerConnection();
//here I want to retrieve the value from List
//System.out.println(s[adapter.]);
int status = sc.confirmRequest(s[listView.getSelectedItemPosition()]);
AlertDialog.Builder alert = new AlertDialog.Builder(PendingRequest.this);
if (status == 1) {
alert.setMessage("Friend has been Added");
alert.show();
} else {
alert.setMessage("Sorry for inconvinient!!Try Again");
alert.show();
}
}
});
}
}
My pendingrequest.xml file is:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#drawable/background"
android:layout_height="match_parent">
<Button
android:layout_marginTop="50dp"
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="100dp"
android:background="#e9abab"
android:id="#+id/btSend"
android:text="Pending Requests"
/>
<ListView
android:id="#+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
On clicking over the button nothing happening.onClick() method is not executing.Please help.
Since you need a click listener on a view inside your list item, you need to write your own adapter for that -
class CustomAdapter extends ArrayAdapter<String> {
public CustomAdapter(Context context, String[] list) {
super(context, 0, list);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// Get the data item for this position
String item = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
// Lookup view for data population
TextView label = (TextView) convertView.findViewById(R.id.label);
Button btConfirmfriend = (Button) convertView.findViewById(R.id.btConfirmfriend);
// Populate the data into the template view using the data object
label.setText(item);
btConfirmfriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getItem(position); //Get your selected text
}
});
return convertView;
}
}
And this is how you will set the adapter -
final CustomAdapter adapter = new CustomAdapter(this,s);
final ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
i have created Custom listview and i add a onclick listener to it but it was not working.the below is my code
This is my MainActivity Class:
public class MainActivity extends Activity {
public boolean[] status;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
// Attach the adapter to a ListView
listView = (ListView) findViewById(R.id.lvUsers);
populateUsersList();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {
Toast.makeText(getBaseContext(),"Hello", Toast.LENGTH_SHORT).show();
}
});
}
private void populateUsersList() {
// Construct the data source
ArrayList<User> arrayOfUsers = User.getUsers();
// Create the adapter to convert the array to views
CustomUsersAdapter adapter = new CustomUsersAdapter(this, arrayOfUsers);
listView.setAdapter(adapter);
}
}
this is my adapter class:
public class CustomUsersAdapter extends ArrayAdapter<User> {
public CustomUsersAdapter(Context context, ArrayList<User> users) {
super(context, 0, users);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
ToggleButton tgbtn = (ToggleButton) convertView.findViewById(R.id.toggleButton1);
// Populate the data into the template view using the data object
tvName.setText(user.name);
tvHome.setText(user.hometown);
// Return the completed view to render on screen
return convertView;
}
}
i want to get the value from listview when the appropriate toggle button is checked .and want to save the value of toggle button and the appropriate text in arraylist.
this my xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lvUsers"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
This is my second 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"
android:padding="10dp"
>
<TextView
android:id="#+id/tvName"
android:layout_alignBaseline="#+id/ivUserIcon"
android:layout_toRightOf="#+id/ivUserIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="6dp"
android:text="Sarah"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvHometown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tvName"
android:layout_below="#+id/tvName"
android:text="San Marco"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ToggleButton
android:id="#+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/tvName"
android:layout_marginRight="15dp"
android:text="ToggleButton" />
</RelativeLayout>
Change your RelativeLayout to
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:descendantFocusability="blocksDescendants"
>
This view will block any of its descendants from getting focus, even if they are focusable.
You must set the button on clicklistener.
tgbtn.setOnClickListener(new OnClickListener(position));
Dont know it it works but try anything like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_main, parent, false);
}
// Lookup view for data population
TextView tvName = (TextView) convertView.findViewById(R.id.tvName);
TextView tvHome = (TextView) convertView.findViewById(R.id.tvHometown);
ToggleButton tgbtn = (ToggleButton) convertView.findViewById(R.id.toggleButton1);
// Populate the data into the template view using the data object
tvName.setText(user.name);
tvHome.setText(user.hometown);
tgbtn.setOnClickListener(new OnButtonClickListener(position));
// Return the completed view to render on screen
return convertView;
}
then a class for the ButtonClick:
private class OnButtonClickListener implements OnClickListener {
int _postion;
// constructor
public OnButtonClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
}
}
below of your code that there is a ListView and you wanna able clicked function to the list item, write this code.
public void onListItemClick(ListView parent, View v, int position, long id){
// do something here
// Example below make a toast message
Toast.makeText(getApplicationContext(), "I clicked item of list number " + position,Toast.LENGTH_SHORT).show();
}
I am trying to make a specific (selected by user) row of a ListView checkbox to become visible. But the problem is,I have dynamically added 10 rows in my list view using class that extends ArrayAdapter and when I select the 1st row then along with my 1st row , 3rd , 5th and so on check box is becoming visible. Similar with 2nd, 4th and so on row.
I just want that particular row (eg position 0) that I selected to show up the check box and rest shoulb be invisible.
public class LazyAdapter extends ArrayAdapter<RowItem> {
Context context;
public LazyAdapter(Context context, int resourceId, List<RowItem> items){
super(context, resourceId, items);
this.context = context;
}
public class ViewHolder{
CheckedTextView checkbox;
TextView title;
TextView description;
LinearLayout card;
}
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null){
convertView = mInflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.card = (LinearLayout) convertView.findViewById(R.id.card);
holder.checkbox = (CheckedTextView)convertView.findViewById(R.id.deliverychecktext);
holder.title = (TextView)convertView.findViewById(R.id.title);
holder.description = (TextView)convertView.findViewById(R.id.description);
convertView.setTag(holder);
} else
holder = (ViewHolder)convertView.getTag();
//holder.image.setImageResource(rowItem.getImageId());
holder.title.setText(rowItem.getTitle());
holder.description.setText(rowItem.getDesc());
Animation animation = AnimationUtils.loadAnimation(context, R.anim.card_animation);
holder.card.startAnimation(animation);
return convertView;
}
}
MainActivity class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Intialize and set the Action Bar to Holo Blue
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#33b5e5" )));
ListView lv = (ListView) findViewById(R.id.myList);
rowItems = new ArrayList<RowItem>();
String[] titles = {"Address1","Address2","Address3","Address4","Address5","Address6","Address7","Address8"};
String[] descriptions = {"First Address","Second Address","Third Address","Fourth Address","Fifth Address",
"Sixth Address","Seventh Address","Eighth Address"};
//Populate the List
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem("Delivery Address :", descriptions[i]);
rowItems.add(item);
}
// Set the adapter on the ListView
LazyAdapter adapter = new LazyAdapter(getApplicationContext(), R.layout.list_row, rowItems);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
CheckedTextView check = (CheckedTextView) view.findViewById(R.id.deliverychecktext);
if (check.getVisibility() == 4)
check.setVisibility(1);
else
check.setVisibility(4);
Toast.makeText(getApplicationContext(), "h u clicked : "+position,
Toast.LENGTH_LONG).show();
}
});
list_row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#drawable/card_no_border"
android:orientation="vertical"
android:padding="2dp"
android:id="#+id/card">
<CheckedTextView
android:id="#+id/deliverychecktext"
android:layout_width="fill_parent"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:paddingTop="2dp"
android:layout_height="wrap_content"
android:checkMark="#drawable/ic_launcher"
android:visibility="invisible"
/>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:text="Dog Tag"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#040404"
android:textStyle="bold"
android:typeface="sans" />
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e5e5e5">
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Your Saved Address"
android:textSize="20sp"
android:padding="5dp"/>
<ListView
android:id="#+id/myList"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="1"
android:divider="#android:color/transparent"
android:dividerHeight="10dp"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:paddingTop="1dip"/>
</LinearLayout>
First one RowItem as class varible to store the selected items.
private RowItem mSelectedItem = null;
ex
public class LazyAdapter extends ArrayAdapter<RowItem> {
Context context;
private RowItem mSelectedItem = null;
After that add the below listener to your LazyAdapter adapter class.
/**
* On Click Listener for the view.
*/
protected class OnViewClickListener implements
android.view.View.OnClickListener {
private RowItem mItem;
public OnViewClickListener(RowItem item) {
mItem = item;
}
#Override
public void onClick(View v) {
mSelectedItem = mItem;
notifyDataSetChanged();
}
}
call this listener from your getView method in LazyAdapter before return view and add logic for the show and hid the view.
ex :
if(mSelectedItem != null && mSelectedItem == rowItem) {
holder.checkbox.setVisibility(View.VISIBLE);
} else {
holder.checkbox.setVisibility(View.INVISIBLE);
}
convertView.setOnClickListener(new OnViewClickListener(rowItem));
return convertView;
}
And remove click lister in ur activity.
on your activity its working because while rendering the adapter view it will reuse the object, so it was happening like that. Now we are checking and updating every time while view rendering.
In need of assistance, I have a listview activity which I want to display couple of textfields per item plus 2 buttons (like contacts app having a call button and a text message button. Reading tutorials I found out how to get the buttons to be clickable, but now my textviews (all except 1) don't display any data other then the stock text I've left in the layout file. The 1 text view does display the data I require it to. No where in my custom SCA do I feed it specific data so I'm assuming it happens in the background.
My R.id.company_address_details_phone loads the needed data without any manipulation on my part, but non of the other TextViews in my ViewHolder display any data. My For loop attached to my call button does output data from my cursor so I know it's not that I'm missing data. Any and all help is appreciated.
As a side note, when first wrote the code and did not use a custom SimpleCursorAdapter all my text views populated as expected (i just couldnt click buttons). This leads me to assume that my CompanyActivity class has no errors but that I'm missing something in my CompanyDetailsCursroAdapter class.
*EDIT***
So I'm answering my own question after I looked back and tried something. non of my views where being populated, I just had one of my views set with default text that made it appear as if it was pulled from my DB. I'm now populating my views with data from the cursor adapter passed to my custom cursor adapter using the below code. I would like to know if this is the best way of doing it or is there a more streamlined or android approved method.
viewHolder.addressTextView.setText(companyDetailsCursor.getString(companyDetailsCursor.getColumnIndex("AddressStreet")));
viewHolder.cityTextView.setText(companyDetailsCursor.getString(companyDetailsCursor.getColumnIndex("AddressCity")));
viewHolder.stateTextView.setText(companyDetailsCursor.getString(companyDetailsCursor.getColumnIndex("AddressState")));
viewHolder.zipTextView.setText(companyDetailsCursor.getString(companyDetailsCursor.getColumnIndex("AddressZip")));
viewHolder.phoneTextView.setText(companyDetailsCursor.getString(companyDetailsCursor.getColumnIndex("AddressPhone")));
CompanyDetailsCursorAdapter.java
public class CompanyDetailsCursorAdapter extends SimpleCursorAdapter implements Filterable{
private final Context context;
private int layout;
Cursor companyDetailsCursor;
public CompanyDetailsCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.context = context;
this.layout = layout;
this.companyDetailsCursor = c;
}
static class ViewHolder {
protected TextView addressTextView;
protected TextView cityTextView;
protected TextView stateTextView;
protected TextView zipTextView;
protected TextView phoneTextView;
protected ImageButton callButton;
protected ImageButton mapButton;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
final LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.company_address_details, null);
convertView.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
viewHolder = new ViewHolder();
viewHolder.addressTextView = (TextView) convertView.findViewById(R.id.company_address_details_street);
viewHolder.cityTextView = (TextView) convertView.findViewById(R.id.company_address_details_city);
viewHolder.stateTextView = (TextView) convertView.findViewById(R.id.company_address_details_state);
viewHolder.zipTextView = (TextView) convertView.findViewById(R.id.company_address_details_zip);
viewHolder.phoneTextView = (TextView) convertView.findViewById(R.id.company_address_details_phone);
viewHolder.callButton = (ImageButton) convertView.findViewById(R.id.company_address_details_call_button);
viewHolder.callButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
companyDetailsCursor.moveToPosition(position);
if (RouteTrackerGlobal.APP_DEBUG) { Log.d(RouteTrackerGlobal.APP_TAG,"getview position set to " + String.valueOf(position));}
for (int i = 0; i < companyDetailsCursor.getColumnCount();i++){
Log.i(RouteTrackerGlobal.APP_TAG, companyDetailsCursor.getString(i));
}
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
return convertView;
}
CompanyActivity.java
public class CompanyActivity extends ListActivity {
DbAdapter dbAdapter;
int companyID;
Context context = this;
Cursor companyDetailsCursor;
#Override
public void onCreate(Bundle savedInstanceBundle) {
super.onCreate(savedInstanceBundle);
dbAdapter = new DbAdapter(this);
setContentView(R.layout.company_activity);
Bundle companyActivityBundle = getIntent().getExtras();
companyID = companyActivityBundle.getInt("CompanyID");
ListView list = getListView();
list.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
return false;
}
});
}
#Override
public void onPause() {
dbAdapter.close();
super.onPause();
}
#Override
public void onResume() {
dbAdapter.open();
super.onResume();
loadDetails();
}
#Override
protected void onListItemClick (ListView l, View v, int position, long id){
//TODO: When item in list clicked, call activity to display address and directions
}
public void loadDetails() {
TextView companyLabel = (TextView) findViewById(R.id.company_activity_company_label);
companyDetailsCursor = dbAdapter.getCompanyDetails(companyID);
startManagingCursor(companyDetailsCursor);
companyDetailsCursor.moveToFirst();
companyLabel.setText(companyDetailsCursor.getString(companyDetailsCursor.getColumnIndex("CompanyName")));
String[] columns = new String[] {"AddressPhone", "AddressStreet", "AddressCity", "AddressState", "AddressZip"};
int[] to = new int[] {R.id.company_address_details_phone, R.id.company_address_details_street, R.id.company_address_details_city, R.id.company_address_details_state, R.id.company_address_details_zip};
CompanyDetailsCursorAdapter companyDetailsAdapter = new CompanyDetailsCursorAdapter(context, R.layout.company_address_details, companyDetailsCursor, columns, to);
setListAdapter(companyDetailsAdapter);
}
}
Company_Address_Details.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" >
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/company_address_details_phone"
style="#style/company_address_listview"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="#string/company_address_details_phone_default" />
<ImageButton android:id="#+id/company_address_details_call_button"
style="#style/company_address_listview"
android:layout_alignParentRight="true"
android:layout_centerInParent="true"
android:background="#android:color/transparent"
android:src="#android:drawable/sym_action_call"
android:contentDescription="#string/company_address_details_phone_hint"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/company_address_details_call_button1"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/company_address_details_street"
style="#style/company_address_listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/company_address_details_street_default" />
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/company_address_details_city"
style="#style/company_address_listview"
android:layout_width="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="#string/company_address_details_city_default" />
<TextView
android:id="#+id/company_address_details_state"
style="#style/company_address_listview"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:text="#string/company_address_details_state_default" />
<TextView
android:id="#+id/company_address_details_zip"
style="#style/company_address_listview"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="#string/company_address_details_zip_default" />
</RelativeLayout>
</LinearLayout>
<ImageButton
android:id="#+id/company_address_details_call_button1"
style="#style/company_address_listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="false"
android:layout_centerInParent="false"
android:layout_centerVertical="true"
android:background="#android:color/transparent"
android:contentDescription="#string/company_address_details_phone_hint"
android:paddingLeft="20dp"
android:src="#android:drawable/ic_dialog_map" />
</RelativeLayout>
</LinearLayout>
This may not be the correct approach, if there is a better way pleas tell me.
I've created a class of Custom Adapter & in my getView method I inflate the view I want to use
public View getView(int position, View convertView, ViewGroup parent)
{
View v = mInflater.inflate(R.layout.wherelayout, null);
if (convertView != null)
{
v = convertView;
}
HashMap<String, Object> whereHash = (HashMap<String, Object>) this.getItem(position);
if (whereHash != null)
{
TextView whereId = (TextView) v.findViewById(R.id.tvWhere);
TextView whereDetails = (TextView) v.findViewById(R.id.tvWhereDetails);
ImageButton ibDelWhere = (ImageButton) v.findViewById(R.id.ibDelWhere);
whereId.setText((CharSequence) whereHash.get("where"));
whereDetails.setText((CharSequence) whereHash.get("details"));
if (ibDelWhere != null)
{
ibDelWhere.setId(position);
ibDelWhere.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//do stuff when clicked
}
}
);
}
}
return v;
}
The view consists of 2 TextView aligned to the left & an ImageButton aligned to the right, I want to be able to delete the item from the ListView when the button is clicked. the layout is like this -
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="horizontal" android:clickable="true">
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textSize="25sp" android:id="#+id/tvWhere" android:textColor="#00FF00" android:text="TextView" android:gravity="top|left" android:layout_alignParentTop="true" android:layout_alignParentLeft="true"></TextView>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="#+id/tvWhereDetails" android:textColor="#0000FF" android:text="TextView" android:textSize="18sp" android:layout_below="#+id/tvWhere" android:gravity="bottom|left" android:layout_alignParentLeft="true"></TextView>
<ImageButton android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="#drawable/eraser" android:id="#+id/ibDelWhere" android:layout_alignParentRight="true" android:layout_alignParentTop="true"></ImageButton>
</RelativeLayout>
The problem is that when the ImageButton is in the layout, I can click it & the onClick() fires as expected, but I can't click the actual list item itself, i.e. click on the TextView items to fire the ListView.onItemClick that was assigned to it already. If I remove the ImageButton from the layout, then the ListView.onItemClick event fires when I click the item. Is there any way I can enable clicking both the ListView item & the button within the layout ?
Thanks guys & gals.
You have to set the imagebutton as non focusable and non focusableInTouchMode (clickable is ok).
Please note, as opposed as other views, you can't do that in xml because the android:focusable gets overwritten in ImageButton's constructor.
To be more precise, that's one of the few differences between ImageView and ImageButton. See for yourself, this is the complete source of ImageButton.
#RemoteView
public class ImageButton extends ImageView {
public ImageButton(Context context) {
this(context, null);
}
public ImageButton(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.imageButtonStyle);
}
public ImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
}
#Override
protected boolean onSetAlpha(int alpha) {
return false;
}
}
To solve, just call setFocusable(false) from java. Or use an ImageView :)
myImageButton.setFocusable(false);
Hope it helps.
You can make both clickable, but it's not really supported and Romain Guy will yell at you. Also, you won't be able to focus/press the button with the trackball. With that said, you can add the following properties to the button, which should make both clickable:
android:focusable="false"
android:focusableInTouchMode="false"
Just make sure you can live with the consequences.
Try to set
android:clickable="false" on the relative Layout.
I had the same problem with a LinearLayout inside another Linearlayout.
The outer LinearLayout was clickable=true, result:
The ListView.OnItemClickListener does not fire.
After setting it to clickable=false it works.
i.e. click on the TextView items to fire the ListView.onItemClick that was assigned to it already.
What happens when you click on the TextView while the ImageButton is there? Does it register a click on the button? or do nothing at all?
How much space in the row does the ImageButton take up? It could be that it is large enough that you can't click in the row outside of it.
I had this same problem. My solution was to set the onClick method for the view inside the adapter instead of using onItemClick.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
LayoutInflater inflater = context.getLayoutInflater();
v = inflater.inflate(R.layout.list_item, parent, false);
}
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//This should replace the onListItemClick method
}
});
v.findViewById(R.id.someinnerview).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Write one of these for each of your inner views
}
});
return v;
}
Hope that helps! Depending on the rest of your program, this might force you into handing more data to the adapter (which I had to do) but it works.
here is example of the custom adapter in list view.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="5dip">
<ImageView
android:layout_width="50dip"
android:layout_height="50dip"
android:id="#+id/imgViewLogo"
android:src="#drawable/icon"
android:layout_alignParentLeft="true"
android:layout_centerInParent="true"
android:scaleType="center">
</ImageView>
<TextView
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/txtViewTitle"
android:layout_toRightOf="#+id/imgViewLogo"
android:layout_marginLeft="2dip">
</TextView>
<TextView
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/txtViewDescription"
android:layout_toRightOf="#+id/imgViewLogo"
android:layout_below="#+id/txtViewTitle"
android:layout_marginLeft="2dip">
</TextView>
<TextView
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/txtViewMobile"
android:layout_toRightOf="#+id/imgViewLogo"
android:layout_below="#+id/txtViewDescription"
android:layout_marginLeft="2dip">
</TextView>
and make java file On The BaseAdapter
public class ListViewCustomAdapter extends BaseAdapter {
Context context;
String[] mobile;
String[] month;
String[] number;
public LayoutInflater inflater;
public ListViewCustomAdapter(Context context,String[] month, String[] number, String[] mobile) {
// TODO Auto-generated constructor stub
super();
this.context = context;
this.month=month;
this.number=number;
this.mobile=mobile;
Log.i("88888888888888888","*******333********");
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//ADC71C 95AA1F
public int getCount() {
// TODO Auto-generated method stub
return month.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
ImageView imgViewLogo;
TextView txtViewDescription;
TextView txtViewMobile;
}
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
Log.i("88888888888888888","*******444********");
ViewHolder holder;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if (convertView == null)
{
Log.i("88888888888888888","*******555********");
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.imgViewLogo = (ImageView) convertView.findViewById(R.id.imgViewLogo);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitle);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescription);
holder.txtViewMobile = (TextView) convertView.findViewById(R.id.txtViewMobile);
convertView.setTag(holder);
}
else
{
Log.i("88888888888888888","*******666********");
holder = (ViewHolder) convertView.getTag();
}
Log.i("888888888888","Display the value of the textbox like(9856321584)other wise (TextView)");
holder.txtViewTitle.setText(month[position]);
holder.txtViewDescription.setText(number[position]);
holder.txtViewMobile.setText(mobile[position]);
return convertView;
}
}