Highlight listView selection background programmatically - android

I have a ListView with a simple ArrayAdapter
dogsList.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, dogsArray));
If a user clicks on an item, the background color changes. So far so great.
Here is my problem: when the user returns, I want to pre-highlight the last selection. I have tried a number of things to pre-highlight one of the entries but it’s not working.
Assume I know the previous selection and pass it through intent or whatever, say prev=5. How do I highLight the background?
I am using a real device (Note 5) to test. And I don't understand whether this applies or not: Android ListView programmatic selection/highlight. In any case, I did it and it didn't work: no highlight.

May be this will help
View row = null;
list_view.post(new Runnable() {
#Override
public void run() {
int nPos = Prev;
list_view.setSelection(nPos);
View v = list_view.getChildAt(nPos);
if (v != null) {
option_list.performItemClick(v, nPos, list_view.getItemIdAtPosition(nPos));
v.requestFocus();
}
}
});
list_view.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
// TODO Auto-generated method stub
if (row != null) {
row.setBackgroundResource(R.color.DarkGray);
}
row = v;
v.setBackgroundResource(R.color.White);
}
});

Related

Set cursor position using setSelection on AutoCompleteTextView which is dynamically generated

I am working on a project which uses a TableLayout, and the user can add a new row to the table layout. Each new row is inflated as a new view and then the view is added to the table layout. One of the controls within the row is an AutoCompleteTextView.
The user can start typing into the AutCompleteTextView and then select one of the items in the suggestion list, when the user selects the item, the selected item is added to the text box as expected, but I want to then set the cursor position as the user can then change the value of the text. For example, the selected item might be sometext() but they can amend the text after selecting it to become sometext(25), so I am trying to set the position of the cursor within the brackets.
This is working fine for one AutoCompleteTextView in the layout but I can't figure out how to do it when its dynamically generated.
I'm finding the AutoCompleteTextView from the inflated layout and creating a set on item click listener, and using the view parameter in the OnItemClick function to ensure I am using the correct view that triggered the event handler, but on the setSelection I am getting an exception java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.AutoCompleteTextView
Below is the code I am using:
private void addRow()
{
TableRow row = (TableRow)LayoutInflater.from(this).inflate(R.layout.create_table_column_row, createTable, false);
txtColumnName = row.findViewById(R.id.txtColumnName);
txtDataType = row.findViewById(R.id.txtDataType);
txtDataType.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
txtDataType.showDropDown();
}
});
txtDataType.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = parent.getItemAtPosition(position).toString();
//Check if the string has a ( and if so, set the cursor to be just after it so the user can enter the size
int bracketPos = selectedItem.indexOf("(");
if (bracketPos > 0)
{
//Crashes on this line
((AutoCompleteTextView)view).setSelection(bracketPos+1);
}
}
});
List<String> datatypes = Arrays.asList(getResources().getStringArray(R.array.table_datatypes));
datatypeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, datatypes);
txtDataType.setAdapter(datatypeAdapter);
rowViews.add(row);
createTable.addView(row);
}
I tried casting the view to AppCompatTextView but then this doesn't have the setSelection() method.
The view in onItemClick() is the AppCompatTextView that is clicked in the drop down box for the AutoCompleteTextView. That is why you can't cast it.
Since you have multiple AutoCompleteTextViews, use a focus change listener to capture which AutoCompleteTextView is being addressed by the user. You can then use that value to set the position of the cursor.
private AutoCompleteTextView textView;
private AutoCompleteTextView mAuto;
textView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
mAuto = (AutoCompleteTextView) v;
}
});
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("MainActivity", "<<<<onItemClicked");
int bracketPos = textView.getText().toString().indexOf("(");
if (bracketPos > 0) {
mAuto.setSelection(bracketPos + 1);
}
}
});
I believe that the AutoCompleteTextView is already populated when this method is called, so you could just search for ( within that field.
Here is a slightly different way. After
txtDataType = row.findViewById(R.id.txtDataType);
add
txtDataType.setOnClickListener(new View.OnClickListener() {
private AutoCompleteTextView mAutoView;
#Override
public void onClick(View v) {
mAutoView = (AutoCompleteTextView) v;
mAutoView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("MainActivity", "<<<<onItemClicked");
int bracketPos = mAutoView.getText().toString().indexOf("(");
if (bracketPos > 0) {
mAutoView.setSelection(bracketPos + 1);
}
}
});
}
});
You can delete your other listeners.

How to make listview selected one item element?

I am working on the custom Listview using BaseAdapter. I am facing one small issue after tap on listview item that particular row gets highlighted but after that if i'll tap one another list item it's highlighted but still the older one it remains same it's not going to it's previous state.
I want to see one item should select at one time.
MainActivity.java
if (musicRealmResults.get(currentIndex).isSelected() == false) {
musicRealmResults.get(currentIndex).setIsSelected(true);
playSong(currentIndex, true);
adapter.notifyDataSetChanged();
} else {
musicRealmResults.get(currentIndex).setIsSelected(false);
adapter.notifyDataSetChanged();
}
MusicAdapter.java
if (musicRealmResults.get(position).isSelected()) {
Typeface tf = Typeface.createFromAsset(mContext.getAssets(), "fonts/fonts_bold.otf");
holder1.albumsTextView.setTypeface(tf);
holder1.equalizerView.setVisibility(View.VISIBLE);
holder1.albumsImageView.setVisibility(View.INVISIBLE);
holder1.equalizerView.animateBars();
} else {
Typeface tf = Typeface.createFromAsset(mContext.getAssets(), "fonts/fonts_regular.otf");
holder1.albumsTextView.setTypeface(tf);
holder1.equalizerView.setVisibility(View.GONE);
holder1.albumsImageView.setVisibility(View.VISIBLE);
holder1.equalizerView.stopBars();
}
Please kindly go through my post and suggest me how to do select and deselect in a listview row.
Loop through all your array elements and set check state to false, then set currentIndex to true.
MainActivity
for(int i =0 ; i < musicRealmResults.size() ; ++i){
musicRealmResults.get(i).setIsSelected(false);
}
musicRealmResults.get(currentIndex).setIsSelected(true);
playSong(currentIndex, true);
adapter.notifyDataSetChanged();
Seems that you weren't able to setSelected(false) your previous item.
Please check setChoiceMode() of ListView or you may just reset your previous item to setSelected(false).
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
musicRealmResults.get(currentSelected).setIsSelected(false); //Reset previous
currentSelected = position; //Save currentPosition to for reset later
.....todos
}
This is a good alternative too, if u dont want to loop through the rest of positions to deselect them.
int prevSelection =-1; //nothing selected
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (prevSelection==-1) //nothing selected
{
musicRealmResults.get(position).setIsSelected(true);
adapter.notifyDataSetChanged();
prevSelection = position;
}else if (prevSelection == position) //deselect previously selected
{
musicRealmResults.get(position).setIsSelected(false);
adapter.notifyDataSetChanged();
prevSelection = -1;
}else // Some other selection
{
musicRealmResults.get(prevSelection).setIsSelected(false);
musicRealmResults.get(position).setIsSelected(true);
adapter.notifyDataSetChanged();
prevSelection = position;
}
You can manage this in your model class. Just make a toggle Boolean isSelected with its getter and setter, When user tap on list item check whether its already selected or not, if not then mark it as selected and update the Boolean value in your model class.
mListLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(list.get(position).getisSelected()){
// list item is already selected.
mListLayout.setBackgroundColor(Color.WHITE); // normal color
list.get(position).setisSelected(false);
}
else{
// list item is not selected, make it selected
mListLayout.setBackgroundColor(Color.GRAY); // selected color
list.get(position).setisSelected(true);
}
notifyDataSetChanged();
}
});
Try Below Code:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if (musicRealmResults.get(position).isSelected() == false)
{
musicRealmResults.get(position).setIsSelected(true);
playSong(position, true);
adapter.notifyDataSetChanged();
}
else
{
musicRealmResults.get(position).setIsSelected(false);
adapter.notifyDataSetChanged();
}
}
});

Multiple List Views in Android

In my android app I have two List Views and two buttons.On clicking first button, first List View will be visible and on second button second List View will be visible.In one List View I will have list of items and in second List View there will be ADD button. Now clicking on ADD button my first List View will be visible and user can select items to add in second List View. I have done it successfully. But my problem is, by clicking on second button List View is appearing but there are no data which are added from First List View. Below is my code.
What am I missing?
final ListView lv = getListView();
LayoutInflater inflater = getLayoutInflater();
final View header = getLayoutInflater().inflate(R.layout.footer, null);
lv.addFooterView(header, null, false);
btnCollege.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String listItems[] = {};
final ArrayAdapter<String> string = new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1);
lv.setAdapter(string);
Button btnAdd = (Button) header.findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (j == 0)
{
lv.setVisibility(View.VISIBLE);
header.setVisibility(View.VISIBLE);
j = 1;
}
else if (j == 1)
{
lv.setVisibility(View.INVISIBLE);
header.setVisibility(View.INVISIBLE);
j = 0;
}
else {}
lv1.setVisibility(View.VISIBLE);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
String selected = lv1.getItemAtPosition(arg2).toString();
string.add(selected);
string.notifyDataSetChanged();
setListAdapter(string);
}
});
}
});
}
});
The view is not getting updated. use handlers for updating listview. That would help you solve the issue

android - How to uncheck the already selected checkedtextview in sigle choice listview

I am trying to uncheck the already selected checkedtextview in single choice list.I tried with the following code but it's not working. Please can anyone help me.
How do we know, we are trying to select the already selected one pro grammatically?
Code
lstAttribs.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView arg0, View v, int nItemPosition,long arg3)
{
if(lstAttribs.isItemChecked(nItemPosition))
{
lstAttribs.setItemChecked(nItemPosition, true);
}
else
{
lstAttribs.setItemChecked(nItemPosition, false);
}
}
});
Its too late but may help some one.
set your listview choice mode to single choice and declare global integer variable with value -1.
int cPos=-1;
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
if (cPos == position) {
if(listView.isItemChecked(cPos)){
listView.setItemChecked(position, false);
}else{
listView.setItemChecked(position, true);
}
} else {
listView.setItemChecked(position, true);
}
cPos = listView.getCheckedItemPosition();
}
});
Try lstAttribs.clearChoices().

What is the easiest way to execute code based on the item selected in a ListView?

I have a ListView with two elements. I would like to execute different code based on the item that has been selected. Until now my code looks like this (but it is not working):
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
ListView listview = (ListView) findViewById(android.R.id.list);
View root = (View) listview.getParent();
if (position == 1) {
root.setBackgroundColor(Color.parseColor("#133b96"));
} else if (position == 2) {
root.setBackgroundColor(Color.parseColor("#bdbdbd"));
}
}
I want to change the background color, and the color should be based on the selected item.
What is the simplest way to do this?
protected void onListItemClick(ListView l, View v, int position, long id) {
if (position == 1) {
v.setBackgroundColor(Color.parseColor("#133b96"));
} else if (position == 2) {
v.setBackgroundColor(Color.parseColor("#bdbdbd"));
}
}
Just look at your protected void onListItemClick() methods for parameters View v. Which is a Selected list item's View. And if you want to change background color of ListView then use
ListView l.
something like,
if (position == 1) {
l.setBackgroundColor(Color.parseColor("#133b96"));
} else if (position == 2) {
l.setBackgroundColor(Color.parseColor("#bdbdbd"));
}
So you have to remove additional code from it to get it to work.
You could switch on the position.
A more OOP approach would be to use the tag property of view, and use it to store some runnable.
e.g.
item.setTag(new Runnable() {
public void run() {
// run whatever code you want
}
}
...
((Runnable)view.getTag()).run();
ArrayAdapter<MyClass> adapter= new ArrayAdapter<MyClass>(this, R.layout.lay_item, theObjects);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
MyClass item = (MyClass) adapter.getItem(position);
}
}

Categories

Resources