I have the following class in my program:
public class RZoom extends Activity {
private ArrayList<FItem> m_FItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fchooser);
TextView tvName = (TextView)findViewById(R.id.txtTitleShow);
m_fItems = ((ArrayList<FItem>)this.getIntent().getSerializableExtra("fItems"));
tvName.setText(this.getIntent().getExtras().getString("RName"));
ListView lv = (ListView)findViewById(R.id.listView1);
FItemAdapter adapter = new FItemAdapter(this, R.layout.row, m_FItems);
lv.setAdapter(adapter);
}
}
This class displays a custom Listview and everything works fine. My questions are:
How do I capture an item click on the Listview? All the examples I've seen seem to inherit ListActivity instead of Activity, like I'm doing.
Is there a way to iterate through the items in the listview and set the background color of the item to Red, depending on the actual item? (In other words, I want to programmically highlight an item depending on the actual item)
Any help would be appreciated!
lv.setOnItemClickListener()
Override FItemAdapter's getView() to change colors depending on the item/position
For your first question you need to grab the ListView from its ID, as you are inheriting from Activity and not from ListActivity:
ListView lv_GetViewList = (ListView)findViewById(R.id.myListView);
lv_GetViewList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
// Your Code here
}
});
2 . You can override the getView() function and then grab the desired control of the row depending upon the conditions you want to use for a particular Control or all of the controls, say, a TextView. And you can set its background color:
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
TextView tv_Text = (TextView) v.findViewById(R.id.myRowTextView);
if(tv_Text != null)
{
tv_Text.setBackgroundColor(Color.RED);
}
return v;
}
Related
I have a listview that is populated via an adapter. I need one of the items (which are just bits of text) in the listview to have a different background compared to the others (to mark it as the currently selected one).
I have all of the background logic, I just need a way to say listview.setBackgroundById(int position)
or something like that.
How do I do this?
This needs to be as simple as possible, 'cause all of the other things done in the Activity are currently working perfectly. :)
As asked, this is my Adapter that I'm using:
public class SampleAdapter extends ArrayAdapter<SampleItem> {
private String title;
public SampleAdapter(Context context) {
super(context, 0);
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_station, null);
}
TextView title = (TextView)convertView.findViewById(R.id.station_name);
font.setFont(title, 2, getActivity());
title.setText(getItem(position).title);
RelativeLayout info = (RelativeLayout)convertView.findViewById(R.id.info_relative_button);
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity.setCurrentTab(41);
MainActivity.setBackDisabled(true);
Log.e("current tab:",String.valueOf(MainActivity.getCurrentTab()));
Fragment fragment = new StationInfo();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
UserManager.getInstance().setStationId(getItem(position).id);
}
});
return convertView;
}
}
The SampleItem has 2 String fields, title and id, it's very simple.
You need to use a custom list adapter and have it return views with your desired background. Create a class extending ListAdapter or any of the existing SimpleAdapter etc and override getView to inflate a suitable view for your element, and add any logic you need to set the background of that view.
There is no way to tell the listview itself to decorate some of its elements by id or position.
Update: I just noticed you added the list adapter code.
Since you are already implementing getView, to change the background of your element simply call convertView.setBackgroundColor, or have two different views inflated depending on the situation.
(BTW it's really bad practice to call static methods on your activity like in your onClickListener.)
In ListView adapter:
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
if(view==null)
....
//for example every even list item to be grey, every odd to be white
if(((position+1)%2)==0)
view.setBackgroundColor(mContext.getResources().getColor(R.color.grey));
else view.setBackgroundColor(mContext.getResources().getColor(android.R.color.white));
Hope you get an idea...
I have been developing an android application and i am stuck in the middle.
The problem is i am using SimpleAdapter to do the adapter stuff and show items in the Listview and as far as i know i cannot override the getView() method of SimpleAdapter class to bound click listeners to the items.
There is a other way to handle click events of sub items like using XML, you can write in the XML like android:clickable="true"and android:onClick="clicklistenr", using this i can get the item but my problem is if i use this then i cannot get the position of the adapter which i need to get adapter item values and handle other tasks. So i am stuck here any help would be appreciable. thanks.
For example i have a ListView which contains one image, TextView, like Button, share Button in each of its items. And there is no way i can find that either its image or button clicked using setOnItemClickListener. So i need a way to handle click events of these sub items of a ListView, i am using SimpleAdapter.
Just call listView.setOnItemClickListener() with your implementation of the listener.
and use like
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
Where list=(ListView)findViewById(R.id.list); and list.setAdapter(your_adapter);
For More details Follow: http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
Hope It Will Help You.. :)
You can use like
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, Object> obj = (HashMap<String, Object>) adapter.getItem(position);
String result= (String) obj.get("name");
Log.d("Yourtag", name);
}
});
First of all your problem is how to handle the items of a custom listview.. not sub. Anyways...
If you are using SimpleAdapter , you may use getView().But if you are using SimpleAdapter you don't need to use the getView() as the it handles the mapping of data to your layout via the resource. For inforamtion check the SimpleAdapter in developer site.
Another thing is there is not mandatory for using any particular adapter. You can create any adapter class which will extends the BaseAdapter which will implement the getView().
Inside getView() you can able to inflate your custom layout(which contains the image,button etc..) to your view or convertview.something like:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.yourcustomlayout, null);
//Initialize your custom views here
TextView someText= (TextView) vi.findViewById(R.id.tvSometext);
Button likeButton = (Button ) vi.findViewById(R.id.btnLike);
//put data or call onclicklistener or
//whatever you want to do with custom views
likeButton .setOnClickListener(...){
//on click
}
}
Ans simply call this through your constructor with some data and appropriate context.
Amir,
I am not sure you found the solution or not. You can do this way:
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
//for each subitem, set click listener & set tag having position as
// value.
ImageView imv = (ImageView)view.findViewById(R.id.live_view);
imv.setTag(i);
imv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("INFO","Live view clicked");
//This will give you position in listview.
int position = (int) v.getTag();
}
});
}
I hope it will help you and others looking to find relevant answer.
May be there is some other solution too, but it will surely work.
Question
I have a listView inside a DialogFragment and I want to fire certain callbacks only when certain particular items inside a row are fired. How can I do that?
Basically, I want to do something like this
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final int viewId = view.getId();
if ((viewId == R.id.textView1) || (viewId == R.id.textView2)) {
// do something...
}
which I can't. Read further if you don't know why.
What I tried
I tried to look into the documentation, but the OnItemClickListener callback doesn't offer as a parameter the exact clicked view (the View you can see in the signature is the whole row).
Also, I tried to set a simple onClick callback on the single view in the adapter, but this overrides the listSelector and other behavior a list should have. Reading in the documentation, I found it's explicitly written that we should set callbacks via the onListItemClick(...) method (not via onClick(...)), so I'm looking for a way to do that, using this method, not to override any default list behavior.
I was trying to get this done by working on the xml. To my surprise, I found that if I set a view android:clickable property to true, the onListItemClick callback won't fire (I thought it was the opposite),
so a partial solution would be to set to android:clickable=true every view in the row apart from the one I want to fire the callback, but that is not a solution because if the user clicks where there is padding or white space, the callback will fire. Also, I found that if I set the parent of the row's view to android:clickable=true and the child views I want to handle with the callback to android:clickable=false, this won't work, because apparently the property is not overwritten.
EDIT Sorry for the really bad title this question had before, I didn't even noticed I submitted the question.
new Answer, hope I understood now :)
In your adapters getView, attach an OnClickListener to any view in your layout you want to fire. (more pseudocode)
public class Adapter extends ArrayAdapter<XYZ> {
private int resource;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null) convertView = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(this.resource, parent, false);
((Button)convertView.findViewById(R.id.YOUR_BUTTON_IN_LAYOUT)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DOSTUFF();
}
});
return convertView ;
}
}
old Answer:
The position indicates where you are in the list (pseudocode).
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, final int position,long arg3) {
YOUR_ITEM_BACKED_BY_ADAPTER item = listView.getItemAtPosition(position);
if(item==THE_FIRST_ITEM_IN_LIST) doSomething();
else if(item == THE_LAST_ITEM_IN_LIST) doSomethingElse();
}
});
You can set listeners for other views inside the adapter's getView
public class MyAdapter extends ArrayAdapter<MyItem> implements View.OnClickListener {
public View getView(int position, View convertView, ViewGroup parent) {
// setup the converView inflating it, for simplicity I've removed that code
MyItem item = getItem(position);
text1 = (TextView)convertView.findViewById(R.id.text1);
text2 = (TextView)convertView.findViewById(R.id.text2);
text1.setOnClickListener(this);
// pass the item to use when clicked
text1.setTag(item);
text2.setOnClickListener(this);
text2.setTag(item);
}
public void onClick(View v) {
MyItem item = v.getTag();
switch (v.getId()) {
case R.id.text1:
download(item);
break;
case R.id.text2:
upload(item);
break;
}
}
}
Instead of hardcoding action (eg download) inside the adapter you can pass to it an interface and for example the calling activity can implement that interface
I need to change color on selected item in list view, i know how to do that in click method, but the thing is that I want to set it then i load new activity. In that activity I'm creating listview and then I want to change one item background color from that list.
I have tried
this.slideMenuList = (ListView) findViewById(R.id.listSlideMenu);
ArrayAdapter<String> adapter2 =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.menuListResut);
this.slideMenuList.setAdapter(adapter2);
this.slideMenuList.getChildAt(0).setBackgroundColor(R.color.red);
but I get NullPointer
You need a custom adapter; you're probably getting a NPE because the views aren't rendered until they're needed, and you can't do that reliably as-is. Write your own adapter class and set the background color after the view has been inflated, like so:
public class MyAdapter extends BaseAdapter {
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
convertView = mInflater.inflate(your layout); // Pseudo-code!
if (i == 0) {
convertView.setBackgroundColor(R.color.red);
}
}
}
I have a ListView with a TextView and a Checkbox on every row. I'm trying to create a sequence where the user has to click on the Checkbox of the first row to enable the next row and remove a grayed out effect. Clicking on the Checkbox in this row will do the same to the next row and so on.
Is this possible? and how?
Create a custom Object to keep the state of your row. For example:
class Row {
private TextView text;
private CheckBox box;
private boolean grayedOut;
//implementation...
}
Inside your Activity you make an ArrayList<Row>() and give it as source to the Adapter of your ListView.
onCreate(..){
mArrayList = new ArrayList<Row>();
// fill arraylist
Adapter mAdapter = new CustomAdapter(... , ... , mArrayList);
ListView lv = findView..
lv.setAdapter(mAdapter);
}
The Adapter for your ListView is custom. You can follow the example found here. In your case some adjustments will be as followed:
public class CustomAdapter extends ArrayAdapter<Row>{
public CustomAdapter(...) {
// do stuff
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// ....
if (item at position has gray state){
set layout to gray
} else {
set layout to active
}
// ....
return row;
}
Now we have a Listview, a CustomAdapter and for each item in the list we have an Row which provides a certain state. Default all the states will be set to gray-state except the first item. Using the onItemClickedListener, we can unlock other items..
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v, int position, Long id){
// do stuff...
mArrayList.get(position+1).setGrayedOut(false);
}
}
Good luck!