How to add default text in spinner? - android

I am new to android,I know access of spinner but I want to add default text in spinner and want set lay out like below image,can any one help me with this,
final String[] items = new String[] {"One", "Two", "Three"};
final ArrayAdapter<String> adapter123 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, items);
sp3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(RegistrationForm.this)
.setTitle("the prompt")
.setAdapter(adapter123, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
});

My suggestion for your case is use Button initially set text and set gravity (not layout_gravity) to left|center_vertical instead of opening an AlertDialog open a PopupWindow set that Button as anchor of that PopUpWindow. In that PopUpWindow place a ListView and in OnItemClick change text with selected value in that Button using setText(java.lang.CharSequence)
code snippet
XML for that Button
<Button
android:id="#+id/propertyBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="#dimen/dp_4"
android:background="#drawable/property_btn_large"
android:ellipsize="marquee"
android:gravity="left|center_vertical"
android:marqueeRepeatLimit="marquee_forever"
android:minHeight="0dp"
android:minWidth="0dp"
android:onClick="showPropertyPopUp"
android:paddingLeft="42dp"
android:paddingRight="22dp"
android:shadowColor="#android:color/white"
android:shadowDx="1"
android:shadowDy="1"
android:shadowRadius="1"
android:text="#string/select_property" />
Java code for opening PopUpWindow in that Button click
//don't forget to initialize that button in onCreate(...)
public void showPropertyPopUp(View v) {
propertyList = dbHelper.getAllProperties();
dbHelper.closeDB();
if(propertyList != null && propertyList.size() > 0) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popUpView = inflater.inflate(R.layout.pop_up, null, false);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.select_dropdown);
popupWindowProperty = new PopupWindow(popUpView, propertyBtn.getWidth(),
300, true);
popupWindowProperty.setContentView(popUpView);
popupWindowProperty.setBackgroundDrawable(new BitmapDrawable(getResources(),
bitmap));
popupWindowProperty.setOutsideTouchable(true);
popupWindowProperty.setFocusable(true);
popupWindowProperty.showAsDropDown(propertyBtn, 0, 0);
ListView dropdownListView = (ListView) popUpView.
findViewById(R.id.dropdownListView);
PropertyDropdownAdapter adapter = new PropertyDropdownAdapter(
AddIncomeActivity.this,
R.layout.row_pop_up_list, propertyList);
dropdownListView.setAdapter(adapter);
dropdownListView.setOnItemClickListener(this);
}
}
code for setting text on that Button in OnItemClick
PropertyInfo addPropertyInfo = propertyList.get(position);
String propertyName = addPropertyInfo.getPropertyName();
propertyBtn.setText(propertyName);
popupWindowProperty.dismiss();
pop_up layout
<?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/dropdownListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#null"
android:fadeScrollbars="false" >
</ListView>
</LinearLayout>
Screenshot on clicking on that Button
Screenshot after item click of ListView

Add one more element in array which you are passing in spinner and if you want to add validation you can check it by runtime using -
if (spnType.getSelectedItemPosition() == 0) {
View view = spnType.getSelectedView();
SpinnerView adapter = (SpinnerView) spnType.getAdapter();
adapter.setError(view, getString(R.string.err_leadtype));
return false;
} else {
strType = arllistType.get(spnType.getSelectedItemPosition()).get(
WebServiceResponseParameter.LIST_VALUE);
}

As Nitish explained, You need to add default value on top of your array R.array.day_birthdate. Suppose you your array is day_birthdate then add day in top where you define
<string-array name="day_birthdate">
<item name="0">day</item>
<item name="1">1</item>
...
</string-array>
Add validaton on Spinner, if option first is selected then,
if (mSpinnerBirthDate.getSelectedItemPosition() == 0) { //where mSpinnerBirthDate is Spinner for Birthdate
//show invalid selection message
}else{
//get selected value from spinner
}

Add one more element in array which you are passing in spinner and then write this code in java file.
String array[]=getResources().getStringArray(R.array.name_Of_array);
ArrayAdapter<String> ad=new ArrayAdapter<String>(this,layoutid, array);
spinner.setAdapter(ad);

You can not do that, for that you have to create custom spinner or you have to show alertdialog as a action when text view is clicked.
Edited :
Create a array
String a [] = new String [4] ;
a[0] = "ram";
a[1] = "shyam";
a[2] = "mohan";
a[3] = "krishna";
use this array as a source of listview data, now as a action listview will be displayed and set a listener for listview which will provide you a position of clicked item in the listview,
use that position for array[position], lets position = 2, then clicked item text will be mohan set this text as a item of textview .
Edited 2:
Create custom Dialog with listview inside it.
set onItemClickListener in listview.
onCreate
{
dayTextView.setText("day");
}
onItemClickListener ()
{
dayTextView.setText("Sunday");
}
Edited 3 :
Follow this tutorial for custom dilaog : http://rajeshvijayakumar.blogspot.in/2013/04/alert-dialog-dialog-with-item-list.html

Related

Align layout to the bottom of the screen when using a scroll view and adding programmatically views

I have a form with a bunch of relative layouts, each one representing a group.
These are of two kind. One is the filter area which contains a spinner to choose a filter and an edit box for the input from the user and there can be multiple ones. The other kind has only one instance and contains a button that adds the aforementioned kind. This is aligned with the bottom of the parent which is a relative layout that contains all the others. This is also contained into a scroll view so it scrolls when the number of filter areas make the height bigger than the screen. My problem is that once I add enough filter areas to exceed the height of the screen the button gets moved once out of screen, then when you scroll down and press it again to add another one the button stays there. It's like the relative layout doesn't grow any more.
Is it something I have to set up in the xml?
The original xml is the following:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"> <!--IMPORTANT otherwise backgrnd img. will not fill the whole screen -->
<RelativeLayout
android:id="#+id/searchLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_vertical_margin"
tools:context="com.kadis.materialref.Search">
<RelativeLayout
android:id="#+id/controlArea"
android:layout_width="match_parent"
android:layout_height="#dimen/controlAreaHeight"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/activity_vertical_margin">
<View
android:id="#+id/dividerControl2"
style="#style/Divider"/>
<Button
style="#style/AddButton"
android:id="#+id/addAttributeButton"
android:layout_centerHorizontal="true"
android:layout_width="#dimen/addButtonWidth"
android:layout_height="wrap_content"
android:layout_below="#+id/dividerControl2"
android:onClick="addFilter"
android:text="#string/addSearchAttributeString"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/filterArea0"
android:layout_width="match_parent"
android:layout_height="#dimen/filterLayoutHeight"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="#dimen/filterArea">
<Spinner
android:id="#+id/filterOperatorSelector0"
android:layout_width="#dimen/operatorSpinnerWidth"
android:layout_height="#dimen/filterSpinnerHeight"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<Spinner
android:id="#+id/filterAttributeSelector0"
android:layout_width="wrap_content"
android:layout_height="#dimen/filterSpinnerHeight"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_toEndOf="#id/filterOperatorSelector0"
android:layout_toRightOf="#id/filterOperatorSelector0"/>
<EditText
android:id="#+id/filterInput0"
style="#style/SearchFormFieldText"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/filterAttributeSelector0"
android:text="Hello World"/>
</RelativeLayout>
</RelativeLayout>
This is the initial screen when first opening it.
The code for the screen is the following.
public class Search extends Activity
{
private String[] filterAttributes;
private String[] filterOperators;
private Spinner originalAttributeSelector;
private Spinner originalOperatorSelector;
private int lastAddedFilterAreaId;
// private MultiSelectionSpinner multiSpinner;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
lastAddedFilterAreaId = R.id.filterArea0;
// Get window sizes
DisplayMetrics dm = new DisplayMetrics();
getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
int displayWidth = dm.widthPixels;
// Get items in spinners (attributes to search on an doperators to apply).
filterAttributes = getResources().getStringArray(R.array.attributes);
filterOperators = getResources().getStringArray(R.array.operators);
// multiSpinner = (MultiSelectionSpinner) findViewById(R.id.FilterSpinner);
// multiSpinner.setItems(filterAttributes);
originalOperatorSelector = (Spinner) findViewById(R.id.filterOperatorSelector0);
// Add items on the spinner.
ArrayAdapter<String> operatorSpinnerAdapter =
new ArrayAdapter<>(this, R.layout.spinner_item_material_ref, filterOperators);
operatorSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
originalOperatorSelector.setAdapter(operatorSpinnerAdapter);
// Fix the width of the spinner so it doesn't get resized when making selections.
// Get the screen width and subtract the width of the button next to the spinner.
originalAttributeSelector = (Spinner) findViewById(R.id.filterAttributeSelector0);
originalAttributeSelector.getLayoutParams().width = displayWidth - originalOperatorSelector.getWidth();
// Create the adapter containing the list of choices for the spinner (as well the style for it)
// and bind it to the spinner.
ArrayAdapter<String> attributeSpinnerAdapter =
new ArrayAdapter<>(this, R.layout.spinner_item_material_ref, filterAttributes);
attributeSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
originalAttributeSelector.setAdapter(attributeSpinnerAdapter);
originalAttributeSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// Make the selected text of the spinner slide.
view.setSelected(true);
// Get container, the RelativeLayout.
RelativeLayout filterArea = (RelativeLayout) parent.getParent();
// Get input element, EditText.
View filterInput = filterArea.getChildAt(filterArea.getChildCount()-1);
// Disable the add button if the selected values is the first (Please make a selection)
if (id == 0)
{
((EditText) filterInput).setText("");
filterInput.setEnabled(false);
} else
{
findViewById(R.id.filterInput0).setEnabled(true);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public void addFilter(View view)
{
// New Relative Layout to be added.
RelativeLayout filterLayout = createFieldArea();
// Add the operator spinner to the filter layout.
Spinner filterOperatorSelector = createFilterOperatorSelector();
filterLayout.addView(filterOperatorSelector);
// Add the attribute spinner to the filter layout, next to the operator spinner.
Spinner filterAttributeSelector = createFilterAttributeSelector(filterOperatorSelector);
filterLayout.addView(filterAttributeSelector);
// Add an Edit Text as the placeholder for the user input in the filter layout, below the attribute spinner.
EditText filterInput = createFilterInputField(filterAttributeSelector);
filterLayout.addView(filterInput);
// Adding the whole filter layout to the search layout (whole screen)
RelativeLayout searchLayout = (RelativeLayout) findViewById(R.id.searchLayout);
searchLayout.addView(filterLayout);
RelativeLayout controlArea = (RelativeLayout) findViewById(R.id.controlArea);
}
private RelativeLayout createFieldArea()
{
// Generate id for new relative layout to be created.
int filterLayoutId = MiscUtils.generateViewId();
RelativeLayout filterLayout = new RelativeLayout(this);
filterLayout.setId(filterLayoutId);
// Define width and height parameters.
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
getResources().getDimensionPixelSize(R.dimen.filterLayoutHeight));
// Define position
rlp.addRule(RelativeLayout.BELOW, lastAddedFilterAreaId);
rlp.addRule(RelativeLayout.ALIGN_PARENT_START);
rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
filterLayout.setLayoutParams(rlp);
// Update which is the latest added filter layout
lastAddedFilterAreaId = filterLayoutId;
return filterLayout;
}
private Spinner createFilterOperatorSelector()
{
Spinner filterOperatorSelector = new Spinner(this);
filterOperatorSelector.setId(MiscUtils.generateViewId());
// Add items on the spinner.
ArrayAdapter<String> spinnerArrayAdapter =
new ArrayAdapter<>(this, R.layout.spinner_item_material_ref, filterOperators);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
filterOperatorSelector.setAdapter(spinnerArrayAdapter);
// Define width and height parameters.
RelativeLayout.LayoutParams rlpSp = new RelativeLayout.LayoutParams(
getResources().getDimensionPixelSize(R.dimen.operatorSpinnerWidth),
getResources().getDimensionPixelSize(R.dimen.filterSpinnerHeight));
// Define position
rlpSp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
rlpSp.addRule(RelativeLayout.ALIGN_PARENT_START);
// Set layout parameters
filterOperatorSelector.setLayoutParams(rlpSp);
return filterOperatorSelector;
}
private Spinner createFilterAttributeSelector(Spinner filterOperatorSelector)
{
Spinner filterAttributeSelector = new Spinner(this);
filterAttributeSelector.setId(MiscUtils.generateViewId());
// Add items on the spinner.
ArrayAdapter<String> spinnerArrayAdapter =
new ArrayAdapter<>(this, R.layout.spinner_item_material_ref, filterAttributes);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
filterAttributeSelector.setAdapter(spinnerArrayAdapter);
// Define width and height parameters.
RelativeLayout.LayoutParams rlpSp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
getResources().getDimensionPixelSize(R.dimen.filterSpinnerHeight));
// Define position
rlpSp.addRule(RelativeLayout.ALIGN_PARENT_END);
rlpSp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rlpSp.addRule(RelativeLayout.END_OF, filterOperatorSelector.getId());
rlpSp.addRule(RelativeLayout.RIGHT_OF, filterOperatorSelector.getId());
// Set layout parameters
filterAttributeSelector.setLayoutParams(rlpSp);
return filterAttributeSelector;
}
private EditText createFilterInputField(Spinner filterAttributeSelector)
{
ViewGroup parent = (ViewGroup) filterAttributeSelector.getParent();
EditText filterInput =
(EditText) getLayoutInflater().inflate(R.layout.search_attribute_input, null);
filterInput.setId(MiscUtils.generateViewId());
// Define width and height parameters.
RelativeLayout.LayoutParams rlpET = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
// Define position
rlpET.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rlpET.addRule(RelativeLayout.ALIGN_PARENT_END);
rlpET.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
rlpET.addRule(RelativeLayout.ALIGN_PARENT_START);
rlpET.addRule(RelativeLayout.BELOW, filterAttributeSelector.getId());
// Set layout parameters
filterInput.setLayoutParams(rlpET);
return filterInput;
}
}
When I add the first layout that fills the screen and after I scroll down to find the button.
If I press the add button here nothing changes. I know from the debugger that the new layout was created so I am guessing it's out of the screen.

Android Set button color on first click, unset on second click

please i need help on this.
I have searched here but the answers i have seen are not working for me, the posts being old, the functions are mostly deprecated.
I am trying to set the color of buttons on a single click in order to highlight them and unset the color on a second click. It's like making some choice from a number of buttons, and if I click on a selected button again maybe after changing my mind on my selection, the color should revert to the default. So that i am only left with the selected buttons highlighted.
The buttons are generated with an adapter in gridview and the onclicklistener applies to all of them.
The code i'm using is as shown:
public class ButtonAdapter extends BaseAdapter {
private Context context;
public View getView(int position, View convertView, ViewGroup parent)
{
final Button btn;
if (convertView == null) {
btn = new Button(context);
btn.setLayoutParams(new GridView.LayoutParams(40, 40));
btn.setPadding(2, 2, 2, 2);
}
else {
btn = (Button) convertView;
}
//exus
btn.setText(Integer.toString(gridNumbers[position]));
btn.setTextColor(Color.BLACK);
btn.setId(position);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//btn.setBackgroundColor(Color.GREEN);
//Toast.makeText(getBaseContext(), "Button clicked", Toast.LENGTH_LONG).show();
if (v.getSolidColor()!=Color.GREEN)
{
btn.setBackgroundColor(Color.GREEN);
}
else
{
btn.setBackgroundColor(Color.GRAY);
}
}
});
return btn;
}
}
}
My XML:
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="8"
android:columnWidth="20dp"
android:stretchMode="columnWidth"
android:gravity="center" />
You can use a list of boolean properties instead of doing this.
Set a public boolean list in your class (it should be public and outside of any functions otherwise the onclicklistener will have error)
List<boolean> blist=new Arraylist<boolean>(Size);
//Size is maximum number of buttons
int index;
Then whenever you create a new button add this:
blist.add(index,false);
index++;
in the onclicklistener; find the index of the button from its position and save the index in an integer named pos.
if(blist.get(pos)==false)
{
//not clicked yet
blist.remove(pos);
blist.add(pos,true);
//here write the code u need for this if
}
else
{
blist.remove(pos);
blist.add(pos,false);
//todo: ur code for else
}
I tried this way and it worked for me,if you want to change on click
counter = 1;
//By Default set color
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter == 1)
{
// Default color
counter = 2;
}
else
{
//your color
counter = 1;
}
}
});
View reused in GridView. So, you should define state for your buttons in your base adapters.
Take an ArrayList that will hold your selected index and remove it when grid is not selected.
Ex:
ArrayList<Integer> selectedItems;
In Construtor
selectedItems = new ArrayList<Integer>();
In OnClickListener
public void onClick(View v) {
if (selectedItems.contains(new Integer(position))) {
selectedItems.remove(new Integer(position));
notifyDataSetChanged();
} else {
selectedItems.add(new Integer(position));
notifyDataSetChanged();
}
}
In getView():
if (selectedItems.contains(new Integer(position))) {
btn.setBackgroundColor(Color.GREEN);
} else {
btn.setBackgroundColor(Color.GRAY);
}
Use toggle button insted of normal button. Like
<ToggleButton
android:id="#+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/check" //check.xml
android:layout_margin="10dp"
android:textOn=""
android:textOff=""
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_centerVertical="true"/>
and then make an xml file check.xml in drawable folder something like
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="#drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="#drawable/unselected_image"
android:state_checked="false"/>
</selector>
refrence.

Getting Array index on item click

I have created an Android RSS Reader App.I have a text marquee in my android app.Iam fetching RSS feed and store RSS title as an array.Iam setting this array as the marque text.Check the code,
String MarqueeStr="";
TextView flashnews;
for (int i = 0; i < nl.getLength(); i++) {
MarqueeStr = MarqueeStr +" | "+ Headlines.Title[i];
}
flashnews.setText(MarqueeStr);
Now I have to set an onclick listener for my marquee, so that user can view detailed description of title which they are clicked.I know how to set it.But my problem is, how can i get the array index of clicked string in the marquee text when a user click on the marquee?
here is my XML layout,
<TextView
android:id="#+id/flashs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:lines="1"
android:ellipsize="marquee"
android:layout_marginLeft="70dp"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:textColor="#e7e7e7" />
screen shote here..
can you see that "Latest News"? its my marquee text
I think that will only be possible if you will create your textviews dynamically and set id for them. like if you are having 10 news link then use 10 textviews
TextView txt = null;
View.OnClickListener marquee_click = new View.OnClickListener() {
#Override
public void onClick(View v) {
int selected_item = v.getTag();
switch (selected_item) {
case 0:
break;
case 1:
break;
case 2:
break;
default:
break;
}
}
};
LinearLayout news_text_layout = new LinearLayout(getApplicationContext());
news_text_layout.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 0; i < 10; i++) {
txt = new TextView(getApplicationContext());
txt.setTag(i); // OR txt.setId(i);
txt.setText("new " + i);
txt.setOnClickListener(marquee_click);
news_text_layout.addView(txt);
}
// ADD YOUR LINEAR LAYOUT ON WHICH YOU HAVE ADDED ALL TEXT VIEW IN YOUR LISTVIEW FOOTER.
// NOW PERFORM SAME ANIMATION OR TRICK ON LINEAR LAYOUT WHICH YOU WERE PERFORMING ON marquee text.
Hope it can help you...
You can add every FlashNews as a dynamically created TextView. And you can put all of these in
one HorizontalScrollView. And set their listeners seperatly.
For marquee function, you can programmatically scroll the horizontalView within your code.
I dont know if it's possible to make it with your idea. (Actually it can be done, but it will contain pain i guess)
for animation look at this i have just created.
Create new project then add class and xml file which i am giving.
public class Test_stflowActivity extends Activity {
LinearLayout ll = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout1);
final TranslateAnimation ts = new TranslateAnimation(200, -100, 0, 0);
ll.setAnimation(ts);
ts.setDuration(5000);
TextView tv = new TextView(getApplicationContext());
tv.setText("*bharat sharma*");
tv.setTextSize(30);
ll.addView(tv);
ll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ll.startAnimation(ts);
}
});
}
}
this is xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" >
</LinearLayout>
</RelativeLayout>
it is working for me
if you use a ListView with an adapter, (which you should), you can use the getItem(int position) function to get the specific item.

How do I create an Android Spinner as a popup?

I want to bring up a spinner dialog when the user taps a menu item to allow the user to select an item.
Do I need a separate dialog for this or can I use Spinner directly? I see this link, mentions a MODE_DIALOG option but it doesn't seem to be defined anymore. AlertDialog may be OK but all the options say "clicking on an item in the list will not dismiss the dialog" which is what I want. Any suggestion?
Ideally, the code would be similar to the case where the spinner is shown on the screen:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
myspinner.setAdapter(adapter);
// myspinner.showAsDialog() <-- what i want
You can use an alert dialog
AlertDialog.Builder b = new Builder(this);
b.setTitle("Example");
String[] types = {"By Zip", "By Category"};
b.setItems(types, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
switch(which){
case 0:
onZipRequested();
break;
case 1:
onCategoryRequested();
break;
}
}
});
b.show();
This will close the dialog when one of them is pressed like you are wanting.
In xml there is option
android:spinnerMode="dialog"
use this for Dialog mode
Try this:
Spinner popupSpinner = new Spinner(context, Spinner.MODE_DIALOG);
See this link for more details.
MODE_DIALOG and MODE_DROPDOWN are defined in API 11 (Honeycomb). MODE_DIALOG describes the usual behaviour in previous platform versions.
Adding a small attribute as android:spinnerMode="dialog" would show the spinner contents in a pop-up.
You can create your own custom Dialog. It's fairly easy. If you want to dismiss it with a selection in the spinner, then add an OnItemClickListener and add
int n = mSpinner.getSelectedItemPosition();
mReadyListener.ready(n);
SpinnerDialog.this.dismiss();
as in the OnClickListener for the OK button. There's one caveat, though, and it's that the onclick listener does not fire if you reselect the default option. You need the OK button also.
Start with the layout:
res/layout/spinner_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/dialog_label"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:hint="Please select an option"
/>
<Spinner
android:id="#+id/dialog_spinner"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<Button
android:id="#+id/dialogOK"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="OK"
android:layout_below="#id/dialog_spinner"
/>
<Button
android:id="#+id/dialogCancel"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Cancel"
android:layout_below="#id/dialog_spinner"
android:layout_toRightOf="#id/dialogOK"
/>
</RelativeLayout>
Then, create the class:
src/your/package/SpinnerDialog.java:
public class SpinnerDialog extends Dialog {
private ArrayList<String> mList;
private Context mContext;
private Spinner mSpinner;
public interface DialogListener {
public void ready(int n);
public void cancelled();
}
private DialogListener mReadyListener;
public SpinnerDialog(Context context, ArrayList<String> list, DialogListener readyListener) {
super(context);
mReadyListener = readyListener;
mContext = context;
mList = new ArrayList<String>();
mList = list;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_dialog);
mSpinner = (Spinner) findViewById (R.id.dialog_spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String> (mContext, android.R.layout.simple_spinner_dropdown_item, mList);
mSpinner.setAdapter(adapter);
Button buttonOK = (Button) findViewById(R.id.dialogOK);
Button buttonCancel = (Button) findViewById(R.id.dialogCancel);
buttonOK.setOnClickListener(new android.view.View.OnClickListener(){
public void onClick(View v) {
int n = mSpinner.getSelectedItemPosition();
mReadyListener.ready(n);
SpinnerDialog.this.dismiss();
}
});
buttonCancel.setOnClickListener(new android.view.View.OnClickListener(){
public void onClick(View v) {
mReadyListener.cancelled();
SpinnerDialog.this.dismiss();
}
});
}
}
Finally, use it as:
mSpinnerDialog = new SpinnerDialog(this, mTimers, new SpinnerDialog.DialogListener() {
public void cancelled() {
// do your code here
}
public void ready(int n) {
// do your code here
}
});
You can use a spinner and set the spinnerMode to dialog, and set the layout_width and layout_height to 0, so that the main view does not show, only the dialog (dropdown view). Call performClick in the button click listener.
mButtonAdd.setOnClickListener(view -> {
spinnerAddToList.performClick();
});
Layout:
<Spinner
android:id="#+id/spinnerAddToList"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="10dp"
android:prompt="#string/select_from_list"
android:theme="#style/ThemeOverlay.AppCompat.Light"
android:spinnerMode="dialog"/>
The advantage of this is you can customize your spinner any way you want.
See my answer here to customize spinner:
Overriding dropdown list style for Spinner in Dialog mode
Here is an Spinner subclass which overrides performClick() to show a dialog instead of a dropdown. No XML required. Give it a try, let me know if it works for you.
public class DialogSpinner extends Spinner {
public DialogSpinner(Context context) {
super(context);
}
#Override
public boolean performClick() {
new AlertDialog.Builder(getContext()).setAdapter((ListAdapter) getAdapter(),
new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialog, int which) {
setSelection(which);
dialog.dismiss();
}
}).create().show();
return true;
}
}
For more information read this article: How To Make Android Spinner Options Popup In A Dialog
This is from the Android SDK source code.
As you can see you have a special constructor to create a Spinner with the specified mode you wanna use.
Hope it will help you :)
/**
* Construct a new spinner with the given context's theme, the supplied attribute set,
* and default style. <code>mode</code> may be one of {#link #MODE_DIALOG} or
* {#link #MODE_DROPDOWN} and determines how the user will select choices from the spinner.
*
* #param context The Context the view is running in, through which it can
* access the current theme, resources, etc.
* #param attrs The attributes of the XML tag that is inflating the view.
* #param defStyle The default style to apply to this view. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
* #param mode Constant describing how the user will select choices from the spinner.
*
* #see #MODE_DIALOG
* #see #MODE_DROPDOWN
*/
public Spinner(Context context, AttributeSet attrs, int defStyle, int mode) {
super(context, attrs, defStyle);
If you want to show it as a full screen popup, then you don't even need an xml layout. Here's how do do it in Kotlin.
val inputArray: Array<String> = arrayOf("Item 1","Item 2")
val alt_bld = AlertDialog.Builder(context);
alt_bld.setTitle("Items:")
alt_bld.setSingleChoiceItems(inputArray, -1) { dialog, which ->
if(which == 0){
//Item 1 Selected
}
else if(which == 1){
//Item 2 Selected
}
dialog.dismiss();
}
val alert11 = alt_bld.create()
alert11.show()
Here is a Kotlin version based on the accepted answer.
I'm using this dialog from an adapter, every time a button is clicked.
yourButton.setOnClickListener {
showDialog(it /*here I pass additional arguments*/)
}
In order to prevent double clicks I immediately disable the button, and re-enable after the action is executed / cancelled.
private fun showDialog(view: View /*additional parameters*/) {
view.isEnabled = false
val builder = AlertDialog.Builder(context)
builder.setTitle(R.string.your_dialog_title)
val options = arrayOf("Option A", "Option B")
builder.setItems(options) { dialog, which ->
dialog.dismiss()
when (which) {
/* execute here your actions */
0 -> context.toast("Selected option A")
1 -> context.toast("Selected option B")
}
view.isEnabled = true
}
builder.setOnCancelListener {
view.isEnabled = true
}
builder.show()
}
You can use this instead of a context variable if you are using it from an Activity.

Copy text from TextView on Android

I have a ListView where each item is a TextView.
I want to enable the long press behaviour similar to an EditText that displays the default context menu with items like "Select all", "Cut all", "Copy all", etc.
Is there an easy way to enable this for a TextView?
I think I have a solution.
Just call
registerForContextMenu(yourTextView);
and your TextView will be registered for receiving context menu events.
Then override onCreateContextMenu in your Activity:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
//user has long pressed your TextView
menu.add(0, v.getId(), 0, "text that you want to show in the context menu - I use simply Copy");
//cast the received View to TextView so that you can get its text
TextView yourTextView = (TextView) v;
//place your TextView's text in clipboard
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(yourTextView.getText());
}
Hope this helps you and anyone else looking for a way to copy text from a TextView
Actually, you do not have to develop this feature by yourself. You just need to use EditText instead TextView, while you set the android:editable of EditText to false. My code is here:
R.layout.edittext.xml
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:editable="false"
android:background="#null"
android:textColor="#FFFFFF"/>
ListItemCopyTextActivity.java
public class ListItemCopyTextActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ListView lv = new ListView(this);
String[] values = new String[15];
for (int i = 0; i < 15; i++) {
values[i] = "ListItem NO." + i;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.edittext, values);
lv.setAdapter(adapter);
ll.addView(lv, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
setContentView(ll);
}
}
You can just long click the item, and choose the select text, copy, cut, past etc.
To allow users to copy some or all of the TextView's value and paste it somewhere else,
set the XML attribute {#link android.R.styleable#TextView_textIsSelectable android:textIsSelectable} to "true"
or
call {#link #setTextIsSelectable setTextIsSelectable(true)}.
You might want to register an onItemLongClickListener on your ListView and then based on the selected item, provide the user with whatever options you choose.
I have a solution, but I'm not exactly to useful.
just use this method :
txtDescDetail.setCursorVisible(true);
i hope to do it.
Here is the solution
<TextView
android:id="#+id/textID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:clickable="true"
android:focusable="true"
android:text="Terms and Conditions"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
override setOnLongClickListener
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
textID.setTextIsSelectable(true)
textID. setOnLongClickListener {
val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("Copied String", textID.text)
clipboardManager.setPrimaryClip(clip)
true // Or false if not consumed
}
}
the expected behavior will be like the image below

Categories

Resources