How can I change view of item in drop down navigation list in action bar on click?
After click, I want that displayed item shows another view (in layout it is set as invisible).
I've got onNavigationItemSelected method from ActionBar.OnNavigationListener but it does not pass view of the item clicked but just position of item in navigation spinner. Or in other words, why can I not get reference to selected view from actionbar spinner? (like I can get view with listview onItemClick from OnItemClickListener())
ActionBar's Spinner resource id is : android:id/action_bar_spinner
Get the Spinner resource id:
int resId = getResources().getIdentifier("action_bar_spinner", "id", "android");
Get the reference to Spinner widget using the resource id:
final Spinner spinner = (Spinner) getWindow().getDecorView().findViewById(resId);
Now you will be able to get access to the selected view:
CheckedTextView v = (CheckedTextView) spinner.getSelectedView();
You can modify the selected view right away in OnNavigationListener:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new MyFragment())
.commit();
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.action_list, android.R.layout.simple_spinner_dropdown_item);
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
int resId = getResources().getIdentifier("action_bar_spinner", "id", "android");
final Spinner spinner = (Spinner) getWindow().getDecorView().findViewById(resId);
this.getActionBar().setListNavigationCallbacks(mSpinnerAdapter, new ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition,
long itemId) {
CheckedTextView v = (CheckedTextView) spinner.getSelectedView();
// Modify selected view.
return true;
}
});
}
I was just trying to figure this out and managed to track it down.
Use setSelectedNavigationItem to do this.
With your navigationListener, you can try this :
OnNavigationListener navigationListener = new OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
View convertView = null;
View view = adapter.getView(itemPosition, convertView, null);
TextView myTextView = (TextView) view
.findViewById(R.id.my_textView);
Toast.makeText(getBaseContext(), myTextView.getText(),
Toast.LENGTH_LONG).show();
return true;
}
You are then retrieving the item via the adapter. My only problem is now modifying the retrieved reference content. I can't seem to have it working.
I Hope it helps
Related
I am using below code to setcolor of a selected item of a listview. The rule is only one should be colored. But with below code if I select 2 views both get colored. Can you please help me get all other views in the listview so that when I click on certain view all other views i set to different color and the selected view i set a different color(Green in this case).
Please let me know if any other solution?
lv = (ListView) view.findViewById(R.id.listf);
lv.setAdapter(text![enter image description here][1]Adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView v = (TextView) view.findViewById(R.id.template_text);
view.setBackgroundColor(Color.GREEN);
}
});
I resolved the problem using the below:
I put a loop where only the selected list item is set in RED whereas all others were set in Green, in this way only only one list item will be colored on selected.
lv = (ListView) view.findViewById(R.id.listf);
lv.setAdapter(Adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for (int i = 0; i < 3; i++)
{
if (position == i)
{
parent.getChildAt(i).setBackgroundColor(Color.RED);
}
else
{
parent.getChildAt(i).setBackgroundColor(getResources().getColor(R.color.Dark_Green);
}
}
TextView v = (TextView) view.findViewById(R.id.template_text);
view.setBackgroundColor(Color.GREEN);
}
});
As you told you are not able to change adapter code, you can prefer solution 2.
Solution 1: Create one variable int selectedPosition and method setSelected in your adapter class
int selectedPosition = -1;
public void setSelected(int position)
{
selectedPosition = position;
notifyDatasetChanged();
}
Edit getView() of the adapter class and include following code
if(selectedPosition==position)
{
templateTextView.setBackgroundColor(Color.GREEN);
}
else templateTextView.setBackgroundColor(Color.BLUE);// default textView color
Solution 2: keep reference of previously selected textView as well each time change the color of currently selected textview to green andd previous one to blue
TextView previousSelected = null;
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(previousSelected!=null)
previousSelected.setBackgroundColor(Color.BLUE);
TextView v = (TextView) view.findViewById(R.id.template_text);
view.setBackgroundColor(Color.GREEN);
previousSelected = v;
}
});
I'm a beginning Android developer and I want to learn how to implement dropdown navigation in my app. Essentially, I would like a different layout to show on the screen when the user selects an item in a spinner in the action bar.
I created a new activity with the Dropdown navigation template in Android Studio but I don't know how to proceed. How would I go about accomplishing this?
To have a different view in the action bar spinner than in the spinner list, you can use a BaseAdapter or an ArrayAdapter and override some methods:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Return a view which appears in the action bar.
return yourCustomView..;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
// Return a view which appears in the spinner list.
// Ignoring convertView to make things simpler, considering
// we have different types of views. If the list is long, think twice!
return super.getView(position, null, parent);
}
More specific details can be found from here: https://stackoverflow.com/a/15293471/1650683
==== EDIT ====
You can find how to integrate dropdown in ActionBar in This article, follow the instruction, you will get it done.
As to bring to a different layout after selecting an item on the spinner, you should set fragment after user clicks on the dropdown item. Sample code:
mOnNavigationListener = new OnNavigationListener() {
// Get the same strings provided for the drop-down's ArrayAdapter
String[] strings = getResources().getStringArray(R.array.action_list);
#Override
public boolean onNavigationItemSelected(int position, long itemId) {
// Create new fragment from our own Fragment class
ListContentFragment newFragment = new ListContentFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment container with this fragment
// and give the fragment a tag name equal to the string at the position
// selected
ft.replace(R.id.fragment_container, newFragment, strings[position]);
// Apply changes
ft.commit();
return true;
}
};
Use spinner for dropdown.This may help you.
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, array_name);
adapter.setDropDownViewResource(R.layout.spinner_layout);
final Spinner s1 = (Spinner) findViewById(R.id.spinner1);
s1.setPrompt("Your Title");
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3)
{
--enter your code here--
}}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
(Android API version 9)I created a spinner with a custom adapter and overrided getView() to inflate it with my xml file which has a text view. But now, my spinner is not closing the dropdown list after user selects an item. Is there anyway to close the spinner dropdown upon selecting an item?
Code
//Code in onCreate function
Spinner list = (Spinner) findViewById(R.id.spn_purchaseList);
listAdapter = new ItemListAdapter(this, new MyItemList());
list.setAdapter(listAdapter);
listAdapter.item_list.addItem(new MyItem("Test", "Test Item"));
listAdapter.notifyDataSetChanged();
//onCreate end
//the class below is inside "MainActivity extends Activity"
class ItemListAdapter extends BaseAdapter
{
Context context;
MyItemList item_list;
MyItem selectedItem;
ItemListAdapter(Context con,MyItemList k)
{
super();
this.context=con;
this.item_list=k;
selectedItem=null;
}
#Override
public int getCount() {
return item_list.getCount();
}
#Override
public MyItem getItem(int arg0) {
return this.item_list.getList().get(arg0);
}
#Override
public long getItemId(int arg0) {
return this.item_list.getPosition(this.item_list.getList().get(arg0));
}
#Override
public View getView(int position, View arg1, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View spinner_item = inflater.inflate(R.layout.spinner_layout, parent, false);
TextView tx = (TextView)spinner_item.findViewById(R.id.txt_spinner);
tx.setId((int) item_list.getPosition(item_list.getList().get(position)));
tx.setText(this.item_list.getList().get(position).name.toString());
tx.setBackgroundResource(R.drawable.spinner_item);
tx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectedItem = item_list.getItem(v.getId());
list.setSelection(v.getId());
}
});
return spinner_item;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
return getView(position,convertView,parent);
}
}
Calling setVisibility(View.GONE) works to hide the dropdown but it seems to cause issues with the Spinner state, i.e. you will be unable to reopen the dropdown after it has been closed.
The preferred way is to get a handle to the Spinner and call its onDetachedFromWindow() from your onClick() listener.
#Override
public void onClick(View v) {
// code here to get selected item and do something with it
// hide the spinner dropdown
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
if (spinner != null) {
try {
Method method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
method.setAccessible(true);
method.invoke(spinner);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Too late, but for my case I had a custom layout for spinner items. The clickable="true" or adding onClickListeners, onItemSelectedListeners didn't work because I was adding them to root layout.
When I changed my code as following, I added android:background="?attr/selectableItemBackground" to child of parent layout, and set OnItemSelectedListener() on Spinner, and it worked. Spinner dialog or dropdown hides when item is tapped.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground">
<!-- your custom spinner item view -->
</LinearLayout>
</LinearLayout>
just call spinner.dismissDropDown() method of spinner, inside on item click of spinner. Your problem will be solved.
So, this might be a simple question, or I may be doing things totally off here, but here's what I have:
public class SetPrefsActivity extends ListActivity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.radiolist);
ArrayList<Hall> listItems = new ArrayList<Hall>();
ArrayAdapter<Hall> ar = new ArrayAdapter<Hall>(this, android.R.layout.simple_list_item_single_choice, listItems);
setListAdapter(ar);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener()
{
boolean somethingChecked = false;
int lastChecked;
public void onItemClick(AdapterView arg0, View arg1, int arg2,
long arg3) {
if(somethingChecked){
ListView lv = (ListView) arg0;
TextView tv = (TextView) lv.getChildAt(lastChecked);
CheckedTextView cv = (CheckedTextView) tv;
cv.setChecked(false);
}
ListView lv = (ListView) arg0;
TextView tv = (TextView) lv.getChildAt(arg2);
CheckedTextView cv = (CheckedTextView) tv;
if(!cv.isChecked())
cv.setChecked(true);
lastChecked = arg2;
somethingChecked=true;
}
});
new LoadListTask().execute(); //This loads Items into the List
Button b = (Button) findViewById(R.id.savePrefBtn);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//IF SOMETHING IS SELECTED,
//THEN UPDATE SHARED PREFERENCES
Intent i = new Intent(SetPrefsActivity.this, SomeOtherActivity.class);
startActivity(i);
}
}
});
}
//other stuff to fill the arrayAdapter
}
What I want to do, is:
When someone clicks the button, it gets information from the listview and updates a shared preference according to the radio option that's selected.
What I'm having trouble with is getting the index of the currently selected item. What is the best way to retrieve that information? Am I implementing the single choice list completely wrong?
Thank You!
arg2 is the position in your list.
It looks like you are doing some extra (unnecessary) processing. arg1 is your row view, and since the android.R.layout.simple_list_item_single_choice layout contains only a CheckedTextView, you can use that directly without having to look for it.
CheckedTextView cv = (CheckedTextView) arg1;
I want to be able to long press items in the spinner view and have a contextMenu appear. I tried this code:
spinner = (Spinner) findViewById(R.id.catagorySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,android.R.layout.simple_dropdown_item_1line, data);
spinner.setAdapter(adapter);
registerForContextMenu(spinner);
but as you can guess this added a context menu to the actual Spinner and not to the contents inside. Does anyone know how i can do this?
Have you tried this?
spinner.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int arg2, long arg3) {
view.showContextMenu();
return true;
}
});
You can register for each item inside the adapter's getView() method.
View getView(View convertView, ... ) {
....
// inflate view or reuse.
....
getContext().registerForContextMenu(convertView);
....
return convertView;
}