Is it possible to make a listview item both clickable and selectable?
If i set
android:textIsSelectable = "true"
My onitemclicklistener does not work. Or is it possible to highlight the textview in the listview without using textIsSelectable? Cause i used the xml code below to create the highlight in my textview
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selected -->
<item
android:state_focused="true"
android:state_selected="false"
android:drawable="#drawable/focused"/>
<item android:drawable="#color/black" /> <!-- default -->
</selector>
i think you need to do a custom listview.
<ScollView><Linearlayout android:id="#+id/listview"> the as a listview of rootView</LinearLayout></ScollView>
LinearLayout listView = (LinearLayout) findViewById(R.id.listview);
add sub item view into the listView.
so now you can add selector and clicklistener on the sub item view.
it is my wertherApp code:
public class MainListAdapter extends BaseAdapter :
public void change(ArrayList<MainListInfo> mainWether) {
if (mainWether == null)
this.mainWether = new ArrayList<MainListInfo>();
else
this.mainWether = mainWether;
this.notifyDataSetChanged();
}
public void setcurtentitem(int curentitem) {
this.curentitem = curentitem;
this.notifyDataSetChanged();
}
public class MainListAdapter extends BaseAdapter {
……
if (position == curentitem) {
convertView.setBackgroundResource(R.drawable.bg_01_down);
} else {
convertView.setBackgroundResource(R.drawable.bg_01_up);
}
……
}
then in the activity:
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
adapter.setcurtentitem(arg2);
}
});
Related
I am using a list fragment to in a customized navigation drawer. I want to change the color of a text view in the list item while pressing. I am passing item click position to adapter and notify the adapter. But it is not working. but when i set the adapter again it is working. But the movement is not smooth . What should i do to overcome this issue?
Following is the ListItem click of fragment,
#Override
public void onListItemClick(ListView lView, View v, final int position, long id) {
super.onListItemClick(lView, v, position, id);
adapter.setSelectedIndex(position);
adapter.notifyDataSetChanged();
lView.setAdapter(adapter);
}
and the adapter having the following code,
public void setSelectedIndex(int ind)
{
selectedIndex = ind;
notifyDataSetChanged();
}
my onactivity created
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
menuitemlist=new ArrayList<MenuItem>();
menuitemlist.clear();
for(int i=0;i<menulist.length;i++){
MenuItem item=new MenuItem();
item.icon=iconlist[i];
item.menuText=menulist[i];
item.status=0;
menuitemlist.add(item);
}
adapter=SlidingListAdapter.newInstance(myActivity, menuitemlist);
setListAdapter(adapter);
}
Method 1
Set your list adapter outside `onListItemClick()`
lView.setAdapter(adapter);
#Override
public void onListItemClick(ListView lView, View v, final int position, long id) {
super.onListItemClick(lView, v, position, id);
adapter.setSelectedIndex(position);
adapter.notifyDataSetChanged();
}
Method 2
View lastSelectedView = null;
#Override
public void onListItemClick(ListView lView, View v, final int position, long id) {
super.onListItemClick(lView, v, position, id);
if(lastSelectedView != null){
TextView txtView = (TextView)lastSelectedView.findViewById(R.id.x);
txtView.setTextColor(defaultColor);
}
TextView txtView = (TextView) v.findViewById(R.id.x);
txtView.setTextColor(pressedColor);
lastSelectedView = v;
}
Method 3
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#ff0000"/>
<item android:state_selected="true" android:color="#00ff00"/>
<item android:color="#000000"/>
</selector>
and set this selector file as textColor for TextView
By default i need to show one item as highlighted in horizontal list view and when the user selected another item in the horizontal list view i want to highlight that item(removing the earlier and highlight the currently selected) for that i'm trying with the following code,in my adapter
Adapter:-
int selectedIndex;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.hlist_rowitem, null);
if (position == selectedIndex) {
v.setBackgroundColor(Color.parseColor("#abcdef"));
}
}
and after selecting another item from activity in from the list view what to do in activity to change highlighting position of the item.
Activity:-
int sIndex;
sIndex = getIntent().getIntExtra("POSITION", 0);
hlAdapter = new HSelectedAdapter(InsuranceCard.this, rowItems, sIndex);
hListView.setAdapter(hlAdapter);
hListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
//other code goes here
}
});
I'd would use a color state list resource and have the ListView handle the selection with setSelection(position).
The color list would look something like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#aabbcc"/> <!-- pressed -->
<item android:state_activated="true"
android:color="#fedcba"/> <!-- selected -->
<item android:color="#abcdef"/> <!-- default -->
</selector>
and it should be set as background of the R.layout.hlist_rowitem or as listSelector on the listview.
Edit:
To change the selection when receiving a click event:
hListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
hListView.setSelection(position);
}
});
The ListView will deselect the old/default item and selects the new item at the specified position.
Edit 2: By default the ListView don't have a choice mode set so make sure you either set it in xml or in code: listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
you can achieve this in two ways.
manually clear all item and set selected in onItemClick()
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
for (int i = 0; i < adapter.getCount(); i++) {
View item = listview.getChildAt(i);
if (item != null) {
item.setBackgroundResource(R.drawable.unselected);
}
arg1.setBackgroundResource(R.drawable.selected);
}
}
});
use selector and let listview do itself.
/drawable/selector_list.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/selected" android:state_selected="true"/>
<item android:drawable="#drawable/selected" android:state_activated="true"/>
<item android:drawable="#drawable/unselected"/>
</selector>
and add android:listSelector="#drawable/selector_list" to your listview
add listitemclick.xml
in your drawblw folder this is the code.
2)then in your hlist_rowitem.xml set background="#drawable/listitemclick"
follow these steps:
1)declare one boolean array.
public static boolean ClickItem[];
2)inside oncreate
ClickItem=new boolean[your array size];
Arrays.fill(ClickItem, false);
in your adapter write this code
a)
if ClickItem[pos]
{
v.setBackgroundColor(Color.parseColor("#abcdef"));
}else
a)
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Arrays.fill(ClickItem, false);
ClickItem[pos]=true;
adapter1.notifyDataSetChanged();
}
});
What is happening i have a listview on which i putting background color change on selection.As well as by default i am putting the first listview item selected as
public class OneWayFlightResult extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public OneWayFlightResult(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return 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 vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.row, null);
TextView flightTime = (TextView)vi.findViewById(R.id.flightTime); // title
TextView flightCompanyName = (TextView)vi.findViewById(R.id.flightCompanyName); // title
TextView flightNumber = (TextView)vi.findViewById(R.id.flightNumber); // title
ImageView flightLogo = (ImageView)vi.findViewById(R.id.flightLogo);
HashMap<String, String> flight = new HashMap<String, String>();
flight = data.get(position);
flightTime.setText(flight.get(TestActivity.FlightTime));
flightCompanyName.setText(TestActivity.FlightCompanyName);
flightNumber.setText(TestActivity.FlightNumber);
if(position == 0){
vi.setBackgroundResource(R.drawable.selection_effect);
vi.setSelected(true);
}
return vi;
}
This is XML file i am using in this selection_effect.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true">
<shape>
<solid android:color="#ffffff" />
</shape>
</item>
<item>
<shape>
<solid android:color="#00a7eb" />
</shape>
</item>
</selector>
So by default this the first list view is selected.Now when the user select the another listview item the first one remains selected and the other one also got the same effect.So how could change the effect on click of the listview item dynamically .Means by default first item comes up selected when the user selects other item other one get selected the effect from the default one get removed
I got solution for your problem. Do as following.
1) open your main layout file where ListView you have created.
Add android:choiceMode="singleChoice". This will look like below.
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:choiceMode="singleChoice" >
</ListView>
2) Open your list_item.xml layout file. In which, to your root view, add android:background="?android:attr/activatedBackgroundIndicator". In my sample project, its look like below.
<?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:background="?android:attr/activatedBackgroundIndicator"
android:orientation="vertical" >
//your views
</LinearLayout>
3) Open your activity file. After setting adapter to your ListView, add list.setSelector(R.drawable.selection_effect);. This will look like below.
ListView ls = (ListView) findViewById(R.id.listView1);
ListAdapter adapter = new ListAdapter(this, data);
ls.setAdapter(adapter);
ls.setSelector(R.drawable.selection_effect);
Here, selection_effect is drawable file which you have created in drawable directory.
I tested my code. Which is working fine.
4) To select first view by default, remove your code in BaseAdapter and put following code after completing 3rd step.
ls.setItemChecked(0,true);
You need to put it after above code like below.
ListAdapter adapter = new ListAdapter(data);
ls.setAdapter(adapter);
ls.setSelector(R.drawable.selection_effect);
ls.setItemChecked(0, true);
Explanation
ls.setSelector(R.drawable.selection_effect);
This will select row item based on selector you have defined in drawable directory.
ls.setItemChecked(0, true);
This will select first item by default at first time run. After you can select other items by clicking on them.
You could just declare an int for item clicked which defaults to the first item that starts clicked, then in onclick update accordingly.
int selected = <default>;
set in oncreate etc.
Then you can have onItemClicked listener and do this,
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (selected != i){
<listView>.getChildAt(selected).setBackgroundColor(getResources().getColor(android.R.color.background_dark));
<listView>.getChildAt(i).setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));
selected = i;
}
}
This will change the background colour of the previously selected item back to (in my case) the default android dark theme colour, set the newly selected one to a nice highlighted light blue, and update the selected int to reflect the newly selected item.
You can try like this:
after setting adapter for ListView set position to 0 for default selection i.e. listView.setSelection(0); and in onItemClick you get selected position (3rd parameter) of item, so inside onItemClick write listView.setSelection("that 3rd param");
I have had similar problem with ListView all you do is when item is clicked call a method on adapter, adadpter.SetPosition(position) {mSelectedPsoiton = position; notifyDataSetChanged();}, and in your getView function check if the position is equal to selectedPosition, then set background accordingly this never fails, focus does not work as ur in touch mode always
//adapter class
public override View GetView(int position, View convertView, ViewGroup parent) { TextView view = null; int lookupPos = position; if (null == convertView) { view = new TextView(_context); view.SetTextSize(ComplexUnitType.Sp, 20); view.SetPadding(_pixels, _pixels, _pixels, _pixels); } else { view = convertView as TextView; }
if (position == mSelectedPos )
{
view.SetBackgroundResource(Android.Resource.Color.HoloBlueDark);
}
else
{
view.SetBackgroundResource(Resource.Drawable.listItemSelector);
}
return view;
}
public void SetSelectedPosition(int position) { mSelectedPos = position;
}
private int mSelectedPos = -1;
// ListView code, _adapter is adapter of listview
listView.SetOnItemClickListener (new OnItemClickListener() { #Override public void onItemClick(AdapterView adapter, View view, int pos, long id) { _adapter.SetSelectionPostion(pos); }
}
I'm building a simple app with a listmenu from a video tutorial by The new Boston
http://www.youtube.com/watch?v=zjHYyAJQ7Vw&list=EC2F07DBCDCC01493A And in that lesson you create this listmenu without any layout. It's all working for me, almost, the menu is in the activity, but I can't see any text in the menu. The text is visible just when i press on one of the menues option. The background is always white when I run my apps on the AVD or my phone.
Is there a way to change the background color and the color of the text, when you create an listmenu in an activity without the layout.xml? Or could there be something else that is wrong? Preciate som help. Thanks!
EDIT: I'm not sure if it's the background color of the activity or the buttons in the menu?It's all white and the text is also white, but there is a gray line between the options in the menu. I'm not sure the answers below will work, since I don't use any xml layout file with a listview? Perhaps it's better to do it with a xml lyaout file instead? Preciate some further help!
EDIT: Added some code:
public class Menu extends ListActivity{
String classes[] = {"MainActivity", "Example1", "Example2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this,android.R.layout.simple_dropdown_item_1line, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String selectedClass = classes[position];
try{
Class ourClass = Class.forName("com.test.theNewBoston." + selectedClass);
Intent ourIntent = new Intent(Menu.this, ourClass);
startActivity(ourIntent);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
try like this by applying selector. It will helps you to change background color.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/pink" android:state_pressed="true"/>
<item android:drawable="#android:color/transparent"/>
</selector>
In my opinion it is better to use a normal Activity than ListActivity.
ListView list = (ListView)findViewById(R.id.listView1);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
//ListView parent, View v, int position, long id
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
arg1.setBackgroundColor(Color.RED);
}
});
and you can set the background color like this:
list.setBackgroundColor(Color.BLUE);
public class HttpEx extends ListActivity {
String options[] = {"BasicConnect","ConnectToSql","TBA","TBA",
"TBA","TBA"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, options));
getListView().setBackgroundColor(Color.BLACK); //add this code into the onCreate
}
This is how I got the background color to change for my ListActivity.
getListView().setBackgroundColor(Color.BLACK); //add this code into the onCreate
you can change the background for listview on java like this
yourlistview.setBackgroundColor(color)
For click on each item in you ListView you can change the BG in two ways:
First. add on item click listener to your ListView list this:
list.setOnItemClickListener(new OnItemClickListener() {
#Override
//ListView parent, View v, int position, long id
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
arg1.setBackgroundColor(Color.Black);
}
});
Second. Use Adapter to your ListView and then add clicklistener on the GetView for each item
I think the first way is better
I got an app that include listview and i want the first line of the listview in blue.
i did the listview from an array xml here is the code&XML:
JAVA:
public class MainActivity extends Activity implements OnItemClickListener {
ListView list;
ArrayAdapter<String> adaptr;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView1);
adaptr = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1
, getResources().getStringArray(R.array.list_view));
list.setAdapter(adaptr);
list.setOnItemClickListener(this);
list.setFastScrollEnabled(true);
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Dialog dialog1 = new Dialog(this, R.style.PauseDialog);
dialog1.setContentView(R.layout.dialog1);
TextView text = (TextView) dialog1.findViewById(R.id.tv1);
dialog1.setTitle(R.string.Title);
if(position == 1) {
text.setText("First Dialog");
dialog1.show();
}
if(position == 2) {
text.setText("Second Dialog");
dialog1.show();
return;
}
if(position == 3) {
text.setText("Third Dialog");
dialog1.show();
return;
}
}
here is the XML:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="list_view">
<item>All Rights Saved to XXX</item>
<item>Line 1</item>
<item>Line 2</item>
<item>Line 3</item>
</array>
</resources>
i want the first item("All Rghits....") will be in blue(color)
(and the other will be regular(black))
You could programmatically add a HeaderView using listView.addheaderView .
You can change the View color to blue
write your own Adapter that extends ArrayAdapter. then you can return whatever View you need in your getView() method implementation.