How to make .setText() of a GridView item (textview) onItemSelected? - java

I'm a beginner in android. Here I want to change the text of the item in GridView when it is clicked, I want to know how it can be done....
Here is my code:
public class MainActivity extends Activity implements OnItemClickListener {
TextView tv;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gv = (GridView) findViewById(R.id.gridView1);
b = (Button) findViewById(R.id.button1);
gv.setAdapter(new custom(this));
gv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
}
custom class:
public class custom extends BaseAdapter {
private LayoutInflater li;
Context ctx;
Button b2;
int v = 0;
String items = "Krishna";
public custom(Context c) {
ctx = c;
li=(LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.length();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items.charAt(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup parent) {
View b1=convertview;
if(convertview==null){
b1=li.inflate(R.layout.c_layout, null);
}
b2 =(Button) b1.findViewById(R.id.button2);
b2.setText(String.valueOf(items.charAt(position)));
b2.setHeight((int) 60);
b2.setGravity(Gravity.CENTER);
b2.setClickable(true);
if ((position % 2) == 0) {
katre();
} else {
katre2();
}
return b1;
}
public void katre() {
b2.setBackgroundResource(extracted());
}
private int extracted() {
return R.color.button_material_dark;
}
public void katre2() {
b2.setBackgroundResource(R.color.material_blue_grey_900);
}
}
and activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_gravity="center_horizontal"/>
<GridView
android:id="#+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="7"
android:stretchMode="columnWidth"
>
</GridView>
</LinearLayout>
and at last c_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Button" />
</RelativeLayout>
please help me...

want to change the text of the item in gridview when it is clicked
Use view parameter of onItemClick to access Button from clicked Item:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Button clickedItem =(Button) view.findViewById(R.id.button2);
clickedItem.setText("Clicked");
}
EDIT:
Or you can do it by adding OnClickListener to Button in getView method:
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Button)v).setText("Clicked");
}
});

Related

Unable to listen to setOnItemClickListener in ListView - Android

I have a ListView in my MainActivity which has a customAdapter to it. I am implementing a slider on each of the list items. I have also attached a footerView to my listView. Now my problem is that, the setOnClickListener is not fired, and I am not able to print the position's of the listView. It only print's for the footerView alone, which I have attached.
The code for MainActivity is
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Context mContext;
private ListView mainListView;
private TextView addContact;
private EditText inputName;
private List<String> contactList = new ArrayList<String>();
private MainListAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mContext = this;
init();
}
private void init() {
mainListView = (ListView)findViewById(R.id.lv_main);
initListData();
View footerView = getLayoutInflater().inflate(R.layout.listview_item_main, null);
footerView.setBackgroundColor(getResources().getColor(R.color.gold));
addContact = (TextView)footerView.findViewById(R.id.tv_item_name);
addContact.setText(getString(R.string.plus));
mainListView.addFooterView(footerView);
mainAdapter = new MainListAdapter(mContext, contactList);
mainListView.setAdapter(mainAdapter);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "on click item " + position);
if (position == contactList.size()) {
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
}
}
});
inputName = (EditText)footerView.findViewById(R.id.et_input_name);
inputName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
String strInput = inputName.getText().toString();
contactList.add(strInput);
addContact.setVisibility(View.VISIBLE);
inputName.getText().clear();
inputName.setVisibility(View.GONE);
}
return false;
}
});
}
private void initListData() {
// temp data
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
}
}
Then the code for my CustomAdapter is
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private List<String> mList;
public MainListAdapter(Context context, List<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
currPagerView.setCurrentItem(0, true);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
itemViewPager.setCurrentItem(0, true);
notifyDataSetChanged();
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
deleteContact(currPagerView.getSelfIndex());
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
// Log.v("PagerAdapter", "curr item positon is" + position);
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
itemViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v(TAG, "onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.v(TAG, "onPageScrolled, " + "arg0=" + arg0 + ", arg1=" + arg1 + ", arg2="
+ arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
Log.v(TAG, "onPageScrollStateChanged");
}
});
// notifyDataSetChanged();
// pagerAdapter.notifyDataSetChanged();
return convertView;
}
private void fillItemData(View convertView, int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
convertView.setBackgroundColor(currColor);
TextView itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
itemName.setText(mList.get(position));
// Log.v(TAG, "item name is " + itemName.getText());
}
private void deleteContact(int postion) {
mList.remove(postion);
}
}
Then finally the ViewPagerAdapter code is
public class MyViewPager extends ViewPager {
private static final String TAG = "MyViewPager";
private float xDown;
private float xMove;
private float yDown;
private float yMove;
private boolean isScroll = false;
private int selfIndex;
public MyViewPager(Context context) {
super(context);
}
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setSelfIndex(int index) {
selfIndex = index;
}
public int getSelfIndex() {
return selfIndex;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
Log.v(TAG, "on intercept");
if (event.getAction() == MotionEvent.ACTION_UP) {
}
return super.onInterceptTouchEvent(event);
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.v(TAG, "on dispatch");
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
xDown = ev.getRawX();
yDown = ev.getRawY();
Log.v(TAG, "action down: " + xDown + ", " + yDown);
} else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
xMove = ev.getRawX();
yMove = ev.getRawY();
Log.v(TAG, "action move: " + xMove + ", " + yMove);
if (isScroll) {
getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchTouchEvent(ev);
}
if (Math.abs(yMove - yDown) < 5 && Math.abs(xMove - xDown) > 20) {
isScroll = true;
} else {
return false;
}
} else if (ev.getAction() == MotionEvent.ACTION_UP) {
isScroll = false;
}
return super.dispatchTouchEvent(ev);
}
}
The MainActivity layout is
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
</RelativeLayout>
The layout for listview_item is
<?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="fill_parent"
android:minHeight="100dp" >
<com.example.yo.view.MyViewPager
android:id="#+id/vp_list_item"
android:layout_width="fill_parent"
android:layout_height="100dp" />
</RelativeLayout>
Added all XML Layouts
listview_item_main
<?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="fill_parent"
android:gravity="center"
android:minHeight="100dp" >
<TextView
android:id="#+id/tv_item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/main_list_text"
android:textSize="48sp"
android:textStyle="bold" />
<EditText
android:id="#+id/et_input_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/add_contact_hint"
android:textColorHint="#color/main_list_text"
android:textColor="#color/main_list_text"
android:textSize="30sp"
android:textStyle="bold"
android:inputType="textCapCharacters"
android:background="#null"
android:textCursorDrawable="#null"
android:singleLine="true"
android:imeOptions="actionDone"
android:visibility="gone" />
</RelativeLayout>
listview_item_slide
<?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:minHeight="100dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_menu_cancel"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:focusableInTouchMode="true"
android:background="#color/gold"
android:gravity="center"
android:text="#string/cancel"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_menu_delete"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#color/green"
android:gravity="center"
android:text="#string/delete"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_menu_block"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#color/royalblue"
android:gravity="center"
android:text="#string/block"
android:textColor="#color/main_list_text"
android:textSize="28sp"
android:textStyle="bold" />
</LinearLayout>
Please help me to listen to the onItemClickListener in the MainActivity's list. I am not able to figure out where I went wrong. Thanks in advance.
you have to put your "setOnItemClickListener" to your Adapter class insted of MainActivity.
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
ViewHolder holder;
View iView = convertView;
if (convertView == null) {
iView = inflater.inflate(R.layout.listview_item, parent, false);
holder = new ViewHolder();
holder.txt_name = (TextView) iView.findViewById(R.id.name);
Typeface custom_fontG = Typeface.createFromAsset(
context.getAssets(), "KozGoPr6N-Regular.otf");
holder.txt_name.setTypeface(custom_fontG);
holder.txt_desc = (TextView) iView.findViewById(R.id.detail);
holder.ivProfile = (ImageView) iView.findViewById(R.id.flag);
iView.setTag(holder);
} else {
holder = (ViewHolder) iView.getTag();
}
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// Capture position and set results to the TextViews
holder.txt_name.setText(resultp.get(OurTeam.TAG_NAME));
holder.txt_desc.setText(resultp.get(OurTeam.TAG_DETAIL));
imageLoader.displayImage(TAG_IMAGEURL + resultp.get((OurTeam.TAG_IMG)),
holder.ivProfile, options);
// Capture ListView item click
iView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
// your code
}
});
return iView;
}
At a time you can handle click event either in Adapter class of in Activity. in your case you are doing both.
And to manage
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
Write above on click event of what ever is main view in listview_item layout (Do not forget to pass addContact and inputName views to your CustomAdapter).
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Context mContext;
private ListView mainListView;
private TextView addContact;
private EditText inputName;
private List<String> contactList = new ArrayList<String>();
private MainListAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mContext = this;
init();
}
private void init() {
mainListView = (ListView)findViewById(R.id.lv_main);
initListData();
View footerView = getLayoutInflater().inflate(R.layout.listview_item_main, null);
footerView.setBackgroundColor(getResources().getColor(R.color.gold));
addContact = (TextView)footerView.findViewById(R.id.tv_item_name);
addContact.setText(getString(R.string.plus));
mainListView.addFooterView(footerView);
mainAdapter = new MainListAdapter(mContext, contactList);
mainListView.setAdapter(mainAdapter);
/* mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e(TAG, "on click item " + position);
if (position == contactList.size()) {
addContact.setVisibility(View.GONE);
inputName.setVisibility(View.VISIBLE);
}
}
});*/
inputName = (EditText)footerView.findViewById(R.id.et_input_name);
inputName.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO) {
InputMethodManager imm = (InputMethodManager)mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
}
String strInput = inputName.getText().toString();
contactList.add(strInput);
addContact.setVisibility(View.VISIBLE);
inputName.getText().clear();
inputName.setVisibility(View.GONE);
}
return false;
}
});
}
private void initListData() {
// temp data
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
contactList.add("Jacob");
contactList.add("Nicolas");
contactList.add("David");
}
}
and Adapter Class was..
public class MainListAdapter extends BaseAdapter {
private static final String TAG = "MainListAdapter";
private Context mContext;
private LayoutInflater layoutInflater;
private MyViewPager itemViewPager;
private View viewMain;
private View viewSlide;
private TextView cancel;
private TextView delete;
private ArrayList<View> views;
private PagerAdapter pagerAdapter;
private List<String> mList;
public MainListAdapter(Context context, List<String> list) {
mContext = context;
layoutInflater = LayoutInflater.from(mContext);
mList = list;
}
#Override
public int getCount() {
return mList != null ? mList.size() : 0;
}
#Override
public Object getItem(int position) {
return mList != null ? mList.get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_item, null);
}
viewMain = layoutInflater.inflate(R.layout.listview_item_main, null);
viewSlide = layoutInflater.inflate(R.layout.listview_item_slide, null);
cancel = (TextView)viewSlide.findViewById(R.id.tv_menu_cancel);
delete = (TextView)viewSlide.findViewById(R.id.tv_menu_delete);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
currPagerView.setCurrentItem(0, true);
notifyDataSetChanged();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG, "on click cancel");
itemViewPager.setCurrentItem(0, true);
notifyDataSetChanged();
MyViewPager currPagerView = (MyViewPager)v.getParent().getParent();
deleteContact(currPagerView.getSelfIndex());
}
});
views = new ArrayList<View>();
views.add(viewMain);
views.add(viewSlide);
itemViewPager = (MyViewPager)convertView.findViewById(R.id.vp_list_item);
itemViewPager.setSelfIndex(position);
pagerAdapter = new PagerAdapter() {
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((MyViewPager)container).removeView(views.get(position));
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
((MyViewPager)container).addView(views.get(position));
// Log.v("PagerAdapter", "curr item positon is" + position);
return views.get(position);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public int getCount() {
return views.size();
}
};
fillItemData(convertView, position, viewMain);
itemViewPager.setAdapter(pagerAdapter);
itemViewPager.setCurrentItem(0);
itemViewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
Log.v(TAG, "onPageSelected");
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
Log.v(TAG, "onPageScrolled, " + "arg0=" + arg0 + ", arg1=" + arg1 + ", arg2="
+ arg2);
}
#Override
public void onPageScrollStateChanged(int arg0) {
Log.v(TAG, "onPageScrollStateChanged");
}
});
// notifyDataSetChanged();
// pagerAdapter.notifyDataSetChanged();
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// your code here for list item click listener...
}
})
return convertView;
}
private void fillItemData(View convertView, int position, View viewMain) {
int[] colorCollection = {
R.color.green, R.color.royalblue, R.color.violet
};
for (int i = 0; i < colorCollection.length; i++) {
colorCollection[i] = mContext.getResources().getColor(colorCollection[i]);
}
int currColor = colorCollection[position % colorCollection.length];
convertView.setBackgroundColor(currColor);
TextView itemName = (TextView)viewMain.findViewById(R.id.tv_item_name);
itemName.setText(mList.get(position));
// Log.v(TAG, "item name is " + itemName.getText());
}
private void deleteContact(int postion) {
mList.remove(postion);
}
}
add this below line in your listview_item parent layout only.
android:descendantFocusability="blocksDescendants"
actually when the list item contains a element which can get focus then list item click listener not work.
Add this to the parent of your Listview and parent of your listview_item and try again:
android:descendantFocusability="blocksDescendants"
Like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:descendantFocusability="blocksDescendants"
android:layout_height="match_parent"
android:background="#color/background"
tools:context="${packageName}.${activityClass}" >
<ListView
android:id="#+id/lv_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
and this:
<?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="fill_parent"
android:descendantFocusability="blocksDescendants"
android:minHeight="100dp" >
<com.example.yo.view.MyViewPager
android:id="#+id/vp_list_item"
android:layout_width="fill_parent"
android:layout_height="100dp" />
</RelativeLayout>
If this does not work, call isFocusable() on your EditText and TextView
addContact.isFocusable(false);
inputName.isFocusable(false);
I am guessing you made a common error. Please check/try both changes.
1) add android:descendantFocusability="blocksDescendants" into the ListView UI ("#+id/lv_main").
Note: If this and 2nd suggestion does not work, then the Listview layout may need rework.
2) mainListView.setItemsCanFocus(false);
Note: The Listview may be confused with focusing on an item in the UI.
I think the suggested code by "Nirmal Shethwala" looks good. It has the if/else block for if (convertView == null).
EDIT: I noticed you inflated 3 xml layout files in getView(). You can only have one, and that is listview_item in your code. I know this is not well documented. I have tried this in the past. The reason is getView() method has to return only one view, and your code return convertView; like me.
Sorry I know this will take some modifications in your layout.

OnItemClickListener doesn't work but OnLongItemClickListener works in Custom Listview

I have a custom listview with custom adapter. I want to click on the items of listview and do something. The OnItemClickListener does not works. But I implemented OnLongItemClickListenerand it works perfectly.
MainActivity
public class MainActivity extends Activity {
ArrayList<Product> products = new ArrayList<Product>();
Adapter listviewAdapter; //custom adapter object
ListView listview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.lvMain);
listview.setLongClickable(true);
listviewAdapter = new Adapter(this, products);
listview.setAdapter(listviewAdapter);
listview.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) { //this works
Toast.makeText(getApplicationContext(), "Long pressed", Toast.LENGTH_SHORT).show();
return false;
}
});
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) { //does not work
Toast.makeText(getApplicationContext(), " pressed", Toast.LENGTH_SHORT).show();
}
});
}
UPDATE custom adapter Adapter
public class Adapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;
TextView itemname,itemprice;
Adapter(Context context, ArrayList<Product> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
Product p = getProduct(position);
itemname= ((TextView) view.findViewById(R.id.tvDescr));
itemname.setText(p.name);
itemprice=((TextView) view.findViewById(R.id.tvPrice));
itemprice.setText(p.price + "");
CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
cbBuy.setOnCheckedChangeListener(myCheckChangList);
cbBuy.setTag(position);
cbBuy.setChecked(p.selected);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
view.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
});
return view;
}
Product getProduct(int position) {
return ((Product) getItem(position));
}
ArrayList<Product> getBox() {
ArrayList<Product> selected = new ArrayList<Product>();
for (Product p : objects) {
if (p.selected)
selected.add(p);
}
return selected;
}
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
getProduct((Integer) buttonView.getTag()).selected = isChecked;
}
};
}
custom listview item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants">
<CheckBox
android:id="#+id/cbBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >
</CheckBox>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tvDescr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" >
</TextView>
</LinearLayout>
activity_main.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/lvMain"
android:layout_width="match_parent"
android:layout_height="0dp"
android:longClickable="true">
</ListView>
to your text views and check box
android:focusable="false"
THis is because of your CheckBox. You can solve like this:
Add an id to your Linearlayout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants"
android:id="#+id/main_layout">
And in your getView
LinearLayout main_layout = (LinearLayout)view.findViewById(R.id.main_layout));
main_layout.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
listview .performItemClick(view,
listview.getPositionForView(view),
listview.getPositionForView(view));
}
});
Edit:
Use following code for long click
main_layout.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
listview.performLongClick();
return true;
}
});
You can give android:onClick attribute in xml :
<CheckBox
android:id="#+id/cbBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" android:onClick="onCheckboxClicked" />
This will work when you check or uncheck Checkbox.
Reason why onClick do not work, but onLongClick works :
You have applied onListItemClickListener over your list view row so when you were clicking on checkbox, the event was consumed by this listener
listview.setOnItemClickListener(new OnItemClickListener() {
Update :
in getView() :
// for list row
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.d("onClick","row click");
}
});
// for list row check box
view.cbBuy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.d("onClick","checkbox click");
}
});
In MainActivity :
Remove this part :
/* listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) { //does not work
Toast.makeText(getApplicationContext(), " pressed", Toast.LENGTH_SHORT).show();
}
}); */
Whether checkbox has property android:focusable="true" or false this code will run
This is working compiled and run code
Thank you
#Amsheer your code works. But for that you had to change the custom adapter and write the actions for onClick events in it. I wanted to write the onClick events in the ManiActivity. I found a workaround. I removed this from custom adapter
view.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
});
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});

Phone call on textview tap

I have this fragment with a two columns list view, the second of which has phone numbers in it. I'm trying to make those numbers clickable, in order to make a phone call (using an Intent). Problem is when I run the app, nothing happens on tapping the text.
(Note that i've already set the
<uses-permission android:name="android.permission.CALL_PHONE" />
in the manifest).
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
ListView lview = (ListView)view.findViewById(R.id.contact_list);
populateList();
listviewAdapter adapter = new listviewAdapter(getActivity(), list);
lview.setAdapter(adapter);
final TextView tv= (TextView)LayoutInflater.from(getActivity()).inflate(R.layout.rows, null).findViewById(R.id.number);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String phone_no=tv.getText().toString().trim();
callIntent.setData(Uri.parse("tel:"+phone_no));
startActivity(callIntent);
}});
return view;
}
rows.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:paddingTop="4dip"
android:paddingBottom="6dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:id="#+id/name"
android:layout_width="100dip"
android:layout_height="wrap_content"
/>
<TextView android:id="#+id/number"
android:layout_width="50dip"
android:layout_height="wrap_content"
android:clickable="true"
/>
</LinearLayout>
listviewAdapter.java
public class listviewAdapter extends BaseAdapter
{
public static final String FIRST_COLUMN = "Column 1";
public static final String SECOND_COLUMN = "Column 2";
public ArrayList<HashMap<String,String>> list;
Activity activity;
public listviewAdapter(Activity activity, ArrayList<HashMap<String,String>> list) {
super();
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtFirst;
TextView txtSecond;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.rows, null);
holder = new ViewHolder();
holder.txtFirst = (TextView) convertView.findViewById(R.id.name);
holder.txtSecond = (TextView) convertView.findViewById(R.id.number);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map = list.get(position);
holder.txtFirst.setText(map.get(FIRST_COLUMN));
holder.txtSecond.setText(map.get(SECOND_COLUMN));
return convertView;
}
}
fragment_my.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listview"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
</LinearLayout>

Gridview onclick listener its not working

I am using gridview of layout,its not working after the grid view items in the list,it shows "throwIndexOutOfBoundsException" in logcat error.without onclick function if i use toast its working,if i give an onlcick function for next activity its not working
Gridviewadapter.java
public class GridviewAdapter extends BaseAdapter
{
private ArrayList<String> listginfy;
private ArrayList<Integer> listimage;
private Activity activity;
public GridviewAdapter(GinfyActivity ginfyActivity,ArrayList<String> listginfy, ArrayList<Integer> listimage) {
super();
this.listginfy = listginfy;
this.listimage = listimage;
this.activity = (Activity) ginfyActivity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listginfy.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listginfy.get(position);
}
public int getItemId() {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public ImageView imgViewGinfy;
public TextView txtViewTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.gridview_row, null);
view.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
view.imgViewGinfy = (ImageView) convertView.findViewById(R.id.imageView1);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtViewTitle.setText(listginfy.get(position));
view.imgViewGinfy.setImageResource(listimage.get(position));
return convertView;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
}
Mainactivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_ginfy);
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(this,listginfy, listimage);
// Set custom adapter to gridview
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
mAdapter = results.get(position);
switch(mAdapter.getItemId())
{
case 1:
Intent newActivity = new Intent(GinfyActivity.this,MainActivity.class);
startActivity(newActivity);
break;
case 2:
Intent new1Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity.class);
startActivity(new1Activity);
break;
default:
Toast.makeText(GinfyActivity.this, "Wrong Input", Toast.LENGTH_LONG).show();
}
}
});
}
public void prepareList()
{
listginfy = new ArrayList<String>();
listginfy.add("Prayers");
listginfy.add("Poojaroom");
listimage = new ArrayList<Integer>();
listimage.add(R.drawable.ginfyprayer);
listimage.add(R.drawable.poojaroom1);
}
}
Onclick function of gridview is not working
here i post my xml layout also.
<?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:background="#drawable/border"
android:padding="5dp">
<ImageView
android:layout_height="64dp"
android:id="#+id/imageView1"
android:layout_width="64dp"
android:src="#drawable/icon"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:clickable="True">
</ImageView>
<TextView
android:text="TextView"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_marginTop="2dp"
android:layout_centerHorizontal="true"
android:textSize="18sp"
android:ellipsize="marquee"></TextView>
</RelativeLayout>
home_ginfy.xml
<?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">
<GridView
android:layout_height="wrap_content"
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:numColumns="auto_fit"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:clickable="True">
</GridView>
</LinearLayout>
you have a lot of error in your code.. (like android:clickable="True" in your layout >> remove that)
just for test, replace your code with:
// Implement On Item click listener
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
switch(position)
{
case 1:
Intent newActivity = new Intent(GinfyActivity.this,MainActivity.class);
startActivity(newActivity);
break;
case 2:
Intent new1Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity.class);
startActivity(new1Activity);
break;
default:
Toast.makeText(GinfyActivity.this, "Wrong Input", Toast.LENGTH_LONG).show();
}
}
});
The getItemId for your adapter always return 0..
replace
mAdapter = results.get(position);
switch(mAdapter.getItemId())
by
switch(position)
I have been using something like this. In your case this should work.
public class GridviewAdapter extends BaseAdapter
{
private ArrayList<String> listginfy;
private ArrayList<Integer> listimage;
private Activity activity;
public GridviewAdapter(GinfyActivity ginfyActivity,ArrayList<String> listginfy, ArrayList<Integer> listimage) {
super();
this.listginfy = listginfy;
this.listimage = listimage;
this.activity = (Activity) ginfyActivity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listginfy.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listginfy.get(position);
}
public int getItemId() {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public ImageView imgViewGinfy;
public TextView txtViewTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.gridview_row, null);
view.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
view.imgViewGinfy = (ImageView) convertView.findViewById(R.id.imageView1);
convertView.setTag(view);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (position){
case 1:
Intent newActivity = new Intent(GinfyActivity.this,MainActivity.class);
startActivity(newActivity);
break;
case 2:
Intent new1Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity.class);
startActivity(new1Activity);
break;
default:
Toast.makeText(GinfyActivity.this, "Wrong Input", Toast.LENGTH_LONG).show();
}
}
}
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtViewTitle.setText(listginfy.get(position));
view.imgViewGinfy.setImageResource(listimage.get(position));
return convertView;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
}

listview onclick android

I am creating an app that has a contacts list inside it. Currently the list works and displays all of my contacts just the way i want it. However i need to add a click function to them. I want to call them once i press one of them. How can i do that? I already have an onListItemClick method in the same activity due to an rss reader. How can i filter it out? Take a look at my code:
//Load contacts into ListView on people screen
contactListView = (ListView) findViewById(R.id.contactsListView);
contactstock = new ArrayList<ContactStock>();
mCursor = managedQuery(ContactsContract.Data.CONTENT_URI, null, Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'", null,
ContactsContract.Data.DISPLAY_NAME + " ASC");
int number = mCursor.getColumnIndex(Phone.NUMBER);
int name = mCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME);
while (mCursor.moveToNext()) {
String phName = mCursor.getString(name);
String phNumber = mCursor.getString(number);
contactstock.add(new ContactStock(phName, phNumber));
}
contactListView.setAdapter(new ContactListAdapter(MainActivity.this,
contactstock));
ContactStock.java:
public class ContactStock {
private String name;
private String number;
public ContactStock(String name, String number) {
this.name = name;
this.number = number;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return this.name;
}
public String getNumber() {
return this.number;
}
}
ContactListAdapter.java:
public class ContactListAdapter extends ArrayAdapter {
private final Activity activity;
private final List stocks;
public ContactListAdapter(Activity activity, List objects) {
super(activity, R.layout.listview_detail_tab_contact_list, objects);
this.activity = activity;
this.stocks = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ContactStockView sv = null;
if (rowView == null) {
// Get a new instance of the row layout view
LayoutInflater inflater = activity.getLayoutInflater();
rowView = inflater.inflate(
R.layout.listview_detail_tab_contact_list, null);
// Hold the view objects in an object,
// so they don't need to be re-fetched
sv = new ContactStockView();
sv.name = (TextView) rowView.findViewById(R.id.contact_name);
sv.number = (TextView) rowView.findViewById(R.id.contact_number);
// Cache the view objects in the tag,
// so they can be re-accessed later
rowView.setTag(sv);
} else {
sv = (ContactStockView) rowView.getTag();
}
// Transfer the stock data from the data object
// to the view objects
ContactStock currentStock = (ContactStock) stocks.get(position);
sv.name.setText(currentStock.getName());
sv.number.setText(currentStock.getNumber());
// TODO Auto-generated method stub
return rowView;
}
protected static class ContactStockView {
protected TextView name;
protected TextView number;
}
}
My current listview code(for rss viewer):
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Uri uri = Uri.parse(links.get(position).toString());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
ListView row 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="horizontal" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:src="#drawable/defaultavatar" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/contact_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:text="Who am I"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/contact_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="000000000" />
</LinearLayout>
</LinearLayout>
I got the phone number from the contact i tapped by using this code:
contactstock.get(arg2).getNumber()
You should set both listviews and set onItemClickListener for each one.
ListView l1 = (ListView)findViewById(R.id.list1);
ListView l2 = (ListView)findViewById(R.id.list2);
// listener for the first one
l1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
// listener for the other
l2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
I think what you say is you are having 2 listview.
You can use setOnItemClickListener to the listview instead of using onListItemClick.
contactListView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}});

Categories

Resources