Hi I'm a newbie in android. I just wanted to know if there is any way to change the font size of a String in android?
String name = db.getName(Id)
String str = "Name : " + name;
I want to have "Name" with bigger font size than the value in "name".Where "name" is the value I get from the database.
Please do suggest any method to do this!! Thanks in advance!!
Use
TextView textView = (TextView) findViewById(R.id.textView);
Spannable span = new SpannableString(str);
span.setSpan(new RelativeSizeSpan(0.8f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(span);
on a TextView to get different TextSizes.
When you are putting the text into a textView you can increase the font. For example
textView.setText(yourString);
textView.setTextSize(20);
Or you can give the font size in the Layout.xml file itself
<TextView
android:id = "#+id/textView"
........
android:textSize = "20dp"/>
Please feel free to ask any further doubts if you need further clarifications.
You do not change the font size of a String instead you change the font size of the text when you display the String(for instance in the TextView if you are using one). A String is simply a data object holding the text you want to display and has nothing to do with the way you display it.
You need to use a Spannable and give it to your TextView in order to modify just a portion of the text. To change the size use :
span.setSpan(new RelativeSizeSpan(0.8f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
You can't change the font size of a String, because String is just a set of characters, but you can alter the font size of a TextView that contains this String using the setTextSize() method. Hope this helps.
You can't. As you can't in any other language. What you need to do is to change the fontsize of the element that will display the text, not the String itself.
Try creating a layout in res/layout/ folder, add a TextView element and then search for the textSize property.
The best Idea to show variances in a ListView is showing headers. A Simple Example is explained here It states the following code:
Simple activity Xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/add_journalentry_menuitem"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/list_journal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
List Header
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_header_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="2dip"
android:paddingBottom="2dip"
android:paddingLeft="5dip"
style="?android:attr/listSeparatorTextViewStyle" />
List Item
<?xml version="1.0" encoding="utf-8"?>
<!-- list_item.xml -->
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_item_title"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:paddingLeft="15dip"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
Main Activity
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ListSample extends Activity
{
public final static String ITEM_TITLE = "title";
public final static String ITEM_CAPTION = "caption";
// SectionHeaders
private final static String[] days = new String[]{"Mon", "Tue", "Wed", "Thur", "Fri"};
// Section Contents
private final static String[] notes = new String[]{"Ate Breakfast", "Ran a Marathan ...yah really", "Slept all day"};
// MENU - ListView
private ListView addJournalEntryItem;
// Adapter for ListView Contents
private SeparatedListAdapter adapter;
// ListView Contents
private ListView journalListView;
public Map<String, ?> createItem(String title, String caption)
{
Map<String, String> item = new HashMap<String, String>();
item.put(ITEM_TITLE, title);
item.put(ITEM_CAPTION, caption);
return item;
}
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
// Sets the View Layer
setContentView(R.layout.main);
// Interactive Tools
final ArrayAdapter<String> journalEntryAdapter = new ArrayAdapter<String>(this, R.layout.add_journalentry_menuitem, new String[]{"Add Journal Entry"});
// AddJournalEntryItem
addJournalEntryItem = (ListView) this.findViewById(R.id.add_journalentry_menuitem);
addJournalEntryItem.setAdapter(journalEntryAdapter);
addJournalEntryItem.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long duration)
{
String item = journalEntryAdapter.getItem(position);
Toast.makeText(getApplicationContext(), item, Toast.LENGTH_SHORT).show();
}
});
// Create the ListView Adapter
adapter = new SeparatedListAdapter(this);
ArrayAdapter<String> listadapter = new ArrayAdapter<String>(this, R.layout.list_item, notes);
// Add Sections
for (int i = 0; i < days.length; i++)
{
adapter.addSection(days[i], listadapter);
}
// Get a reference to the ListView holder
journalListView = (ListView) this.findViewById(R.id.list_journal);
// Set the adapter on the ListView holder
journalListView.setAdapter(adapter);
// Listen for Click events
journalListView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long duration)
{
String item = (String) adapter.getItem(position);
Toast.makeText(getApplicationContext(), item, Toast.LENGTH_SHORT).show();
}
});
}
}
Two more additional XMLs are present there, but with these given structure you can Implement what you want in a better way rather than Just size difference.
P.S.- the full app is available here
Spannable font: In order to set a different font size to some portion of text, a RelativeSizeSpan can be used, as shown in the following example:
Spannable spannable = new SpannableString(firstWord+lastWord);
spannable.setSpan(new ForegroundColorSpan(firstWordColor), 0, firstWord.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(lastWordColor), firstWord.length(), firstWord.length()+lastWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText( spannable );
Credit: Copy and Pasted from this webpage.
You cannot do that. You can add the string to the View lets say EditText or TextView and set the text Size for the view in xml as below:
android:textSize="18dp"
or programatically, you can do like this:
<YourTextView>.setTextSize(18);
Due to lack of idea before, i had asked similar question here. I hope you will get an idea with this link.
Related
Edit: I have been able to track the problem down to the use of EditText rather than TextView. The repeated calls only happen when a field is an EditText and the system behaves itself when the field is a TextView. I can find nothing in the documentation or online that indicates that LineBackgroundSpan will not work with EditText.
I have updated the MCVE to show how things work with TextView (it does) and with EditText (it doesn't - at least not well). My updated question is how to get LineBackgroundSpan working with EditText.
I have implemented a simple class to add a rounded background to text in an EditText using LineBackgroundSpan. Everything works OK but while debugging I noticed that the drawBackground method of my class is called repeatedly and, seemingly, without end for each span in the string even though no changes are being made. It is not apparent on the display, but is readily apparent if a breakpoint is set in the drawBackground method.
In trying to track down the issue, I was able to reduce the code down to an MCVE.The following code will simply highlight an entire line of text. The top line is an EditText and the bottom line is a TextView. (This is not what I am really trying to do, but it serves the purpose.)
This MCVE exhibits the problem for me on emulators running API 17 and API 24 as well as an actual phone running API 24. Setting the disableDraw argument to true for the constructor of RoundedBackgroudSpan() will disable background drawing action in drawBackground(). I am seeing the problem on the EditText even with background drawing disabled.
What is going on here? Am I misunderstanding how to work with spans? Will spans not work with EditText? Any help will be greatly appreciated.
MainActivity.java
package com.example.bgspanmcve;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.style.LineBackgroundSpan;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import static android.text.Spanned.SPAN_INCLUSIVE_INCLUSIVE;
public class MainActivity extends AppCompatActivity {
final String dispString = "XAB CD EF";
private static int count = 0; // times drawBackground is called
#Override
protected void onCreate(Bundle savedInstanceState) {
EditText editText;
TextView textView;
RoundedBackgroundSpan bg;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the EditText field with a span.
// RoundedBackgroundSpan#drawBackground will be called forever for this EditText.
editText = ((EditText) findViewById(R.id.editText));
SpannableString ssEditText = new SpannableString(dispString);
bg = new RoundedBackgroundSpan(INHIBIT_DRAWING, false);
ssEditText.setSpan(bg, 0, ssEditText.length(), SPAN_INCLUSIVE_INCLUSIVE);
editText.setText(ssEditText);
// Set up the TextView field with a span.
// RoundedBackgroundSpan#drawBackground will be called once for this TextView.
textView = ((TextView) findViewById(R.id.textView));
SpannableString ssTextView = new SpannableString(dispString);
bg = new RoundedBackgroundSpan(INHIBIT_DRAWING, true);
ssTextView.setSpan(bg, 0, ssTextView.length(), SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(ssTextView, TextView.BufferType.EDITABLE);
}
private static class RoundedBackgroundSpan implements LineBackgroundSpan {
private boolean mDisableDraw;
private boolean mIsTextView;
RoundedBackgroundSpan(boolean disableDraw, boolean isTextView) {
super();
mDisableDraw = disableDraw;
mIsTextView = isTextView;
}
#Override
public void drawBackground(
Canvas canvas, Paint paint, int left, int right, int top,
int baseline, int bottom, CharSequence text, int start, int end, int lnum) {
count++;
if (mIsTextView) {
Log.d(TAG, "<<<<drawBackground (TextView) #" + count);
} else {
Log.d(TAG, "<<<<drawBackground (EditText) #" + count);
}
if (mDisableDraw) return;
Paint localPaint = new Paint();
RectF rect = new RectF(left, top, right, bottom);
localPaint.setColor(BG_COLOR);
canvas.drawRoundRect(rect, RADIUS_X, RADIUS_Y, localPaint);
}
private final String TAG = RoundedBackgroundSpan.class.getSimpleName();
private final int BG_COLOR = 0xfF00FF00;
private final int RADIUS_X = 20;
private final int RADIUS_Y = 20;
}
private final static String TAG = MainActivity.class.getSimpleName();
private final boolean INHIBIT_DRAWING = true;
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.bgspanmcve.MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginStart="0dp"
android:inputType="text"
android:paddingEnd="0dp"
android:paddingStart="0dp"
android:text="EditText"
android:textSize="20sp" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#id/editText"
android:layout_below="#id/editText"
android:layout_marginStart="0dp"
android:layout_marginTop="16dp"
android:paddingEnd="0dp"
android:paddingStart="0dp"
android:text="TextView"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>
The call to drawBackground() is timed to the rate of the flashing cursor which is about 500 ms as suggested by #Suragch. I am now convinced that the call to drawBackground() is made as part of the cursor implementation.
As a quick, but not definitive test, I have set the EditText field to not show the cursor but to still be editable (android:cursorVisible="false"). When this attribute set to false, the repeated calls to drawBackground() cease.
I'm currently working on 100 Random Facts app that simply displays a new fact when the button is clicked. Every time a new fact is displayed the same screen pops up but with a different color as the background. I did this by storing the facts in an array and also the colors in an array and then randomly matching them, i want to do this but with images instead. How can I change the background to a customized image when a random fact pops up. So that each time the new fact button is pressed a fact pops up but instead of the background being a color, being an random image instead?
Any help is appreciated!
Here is my code, The Different Colors are stored in a java class called ColorWheel
ColorWheel.java
package com.example.android.funfacts;
import android.graphics.Color;
import java.util.Random;
public class ColorWheel {
//Member variable (propoerties about the object)
public String[] mColors = {
"#39add1", // light blue
"#3079ab", // dark blue
"#c25975", // mauve
"#e15258", // red
"#f9845b", // orange
"#838cc7", // lavender
"#7d669e", // purple
"#53bbb4", // aqua
"#51b46d", // green
"#e0ab18", // mustard
"#637a91", // dark gray
"#f092b0", // pink
"#b7c0c7" // light gray
};
String color="";
//Method (abilities:things the object can do)
public int getColor(){
//Randomly select a fact
Random randomGenerator =new Random(); // construct a new random generator
int randomNumber =randomGenerator.nextInt(mColors.length);
color = mColors[randomNumber];
int colorAsInt = Color.parseColor(color);
return colorAsInt;
}
}
FunFactsActivity.java
public class FunFactsActivity extends Activity {
public static final String TAG =FunFactsActivity.class.getSimpleName();
private FactBook mFactBook = new FactBook();
private ColorWheel mColorWheel= new ColorWheel();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fun_facts);
// Declare our view variables and assign them the views from the layout file
final TextView factLabel = (TextView) findViewById(R.id.factTextView);
final Button showFactButton= (Button) findViewById(R.id.showFactButton);
final RelativeLayout relativelayout =(RelativeLayout) findViewById(R.id.relativeLayout);
View.OnClickListener listener= new View.OnClickListener() {
#Override
public void onClick(View view) {
String fact = mFactBook.getFact();
//Update the label with our dynamic fact
factLabel.setText(fact);
int color = mColorWheel.getColor();
relativelayout.setBackgroundColor(color);
showFactButton.setTextColor(color);
}
};
showFactButton.setOnClickListener(listener);
//Toast.makeText(this,"YAY! our activity was created",Toast.LENGTH_LONG).show();
Log.d(TAG, "We are Logging from the oncreate method");
}
}
activity_fun_facts.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.austinzeller.funfacts.FunFactsActivity"
android:background="#drawable/image1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/did_you_knoww"
android:textSize="24sp"
android:textColor="#android:color/background_light"
android:textStyle="normal|bold" />
<Button
android:text="#string/new_random_fact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/showFactButton"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#android:color/background_light"
android:textColor="#51b46d" />
<TextView
android:text="#string/ants_stretch_when_they_wake_up_in_the_morningg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/factTextView"
android:textColor="#android:color/background_light"
android:textSize="21sp"
android:layout_above="#+id/showFactButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="129dp"
android:textStyle="normal|bold" />
</RelativeLayout>
FactBook.java
package com.example.android.funfacts;
import java.util.Random;
public class FactBook {
//Member variable (propoerties about the object)
public String[] mFacts = {
"There are 206 bones in the human body!",
"Left-handed people are better at sports that require good spatial
judgment and fast reaction, compared to right-handed individuals.",
"Your heart beats over 100,000 times a day!",
"One quarter of the human brain is used to control the eyes.",
"Europe is the only continent without a desert.",
"The tongue is the strongest muscle in the human body.",
"Food can only be tasted if it is mixed with saliva.",
"About 3000 years ago, most Egyptians died by the time they were
30!",
"Under extreme stress, some octopuses will eat their own arms.",
"A fully loaded supertanker traveling at normal speed takes a least
twenty minutes to stop.",
"Aluminum used to be more valuable than gold!",
"More than half the population of Kenya is under the age of 15."
built." };
String fact="";
//Method (abilities:things the object can do)
public String getFact(){
//Randomly select a fact
Random randomGenerator =new Random(); // construct a new random generator
int randomNumber =randomGenerator.nextInt(mFacts.length);
fact = mFacts[randomNumber];
return fact;
}
}
So, Does anybody know how to create following grid? I need to set clickable event to every word:
If four words are not fit to a line then should be shown three in a line:
if it will be exceed to a line n words then should be shown n words in a line.
Is there anybody knows how to implement this?
You can use SpannableString and ClickableSpan. this Activity, for example, creates TextView with your text and manages clicks on each word:
public class MainActivity extends AppCompatActivity {
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
TextView textView = (TextView) findViewById(R.id.textView);
String text = "up down Antidisestablishment over took dropped lighten with from throught fell on up down Antidisestablishment over took dropped lighten with from throught fell on";
String[] textArray = text.split(" ");
SpannableString ss = new SpannableString(text);
int start = 0;
int end = 0;
for(final String item : textArray){
end = start + item.length();
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
Toast.makeText(activity, "Say " + item+ "!", Toast.LENGTH_SHORT).show();
}
#Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
}
};
ss.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
start += item.length()+1;
}
textView.setText(ss);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.TRANSPARENT);
}
}
and here is activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:padding="5dp">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#000000"
android:textColorLink="#000000"/>
</LinearLayout>
if you click on any word you get popup with this word
EDIT: to justify the text use the library android-justifiedtextview
But not the library from gradle, there are the old version which does not support SpannableString. I recommend just copy the class JustifyTextView from git to your project. Then you can use this view in your .xml like:
<com.yourdomain.yourproject.JustifyTextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#000000"
android:textColorLink="#000000"/>
here is what I got with this library:
you also can modify the library to keep last line unjustified. Every word in the text is still clickable.
If the amount of items you have to add is little, consider using a FlowLayout. It extends a LinearLayout, so just wrap it in a ScrollView, add your views to it dynamically, and you should be good to go.
I am trying to make a bible app. I'm using listview to show verses..in my listview i used a textview in a customlayout for the listview's list items, I put a seekbar below the listview so the users can adjust the font size. I solved this but my problem is only the first item adjusts when I use the seekbar. I saw some posts but they used getView method, I didn't use that..Please help, I'm new in android development
Main Activity code:
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int Blast;
#Override
public void onStopTrackingTouch(SeekBar seekBar){
TextView shopName = (TextView)findViewById(R.id.item_version);
prefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
ed.putFloat("fontsize", ((TextView) findViewById(R.id.item_version)).getTextSize());
ed.commit();
// myList.setSelection(1);
((TextView) findViewById(R.id.item_version)).setTextSize(TypedValue.COMPLEX_UNIT_PX, seekBar.getProgress());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar){
((TextView) findViewById(R.id.item_version)).setTextSize(TypedValue.COMPLEX_UNIT_PX,seekBar.getProgress());
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser){
((TextView) findViewById(R.id.item_version)).setTextSize(TypedValue.COMPLEX_UNIT_PX,progress);
Blast = progress;
}
});
public void viewAll1(){
Cursor cursor = myDB.getAllData2();
String[] from = new String[]{DBAdapter.KEY_NAME};
int[] to = new int[]{R.id.item_version};
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(this, R.layout.item_layout, cursor, from, to, 0);
ListView myList = (ListView) findViewById(R.id.listView);
myList.setAdapter(myCursorAdapter);
}
item_layout.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/item_version"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textStyle="bold"
android:textIsSelectable="false"
android:typeface="serif"
android:paddingStart="20dp" />
Well, you should use getView method, it won't bite, seriously. getView let's you tweak the way each view in your ListView is displayed. The TextView with id item_version exists inside the ListView, so findViewById won't work. The only way to get a reference to that TextView is using getView.
You should read a tutorial about ListViews and adapters, so that you understand how getView works and how to not shoot yourself in the foot while using it, but here's a little help to get you started.
Override SimpleCursorAdapter to hold an extra attribute for font size. Something like:
float textSize = 14f;
public void setTextSize(float size){
textSize = size;
}
Then, right below that line, overridegetView, so that for every view you do something like:
TextView textview = (TextView) view.findViewById(R.id.item_version);
textview.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
Your activity should hold a reference to your adapter. When progress changes, here's how you can update your ListView
adapter.setTextSize(progress);
adapter.notifyDatasetChanged();
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