Using NumberPicker Widget with Strings - android

Is there a way to use the Android NumberPicker widget for choosing strings instead of integers?

NumberPicker picker = new NumberPicker(this);
picker.setMinValue(0);
picker.setMaxValue(2);
picker.setDisplayedValues( new String[] { "Belgium", "France", "United Kingdom" } );

NumberPicker numberPicker = new NumberPicker(this);
String[] arrayString= new String[]{"hakuna","matata","timon","and","pumba"};
numberPicker.setMinValue(0);
numberPicker.setMaxValue(arrayString.length-1);
numberPicker.setFormatter(new NumberPicker.Formatter() {
#Override
public String format(int value) {
// TODO Auto-generated method stub
return arrayString[value];
}
});

String value = String.valueOf(picker.getValue());
You could mean something else, but it isn't very clear what you mean.
UPDATED:
You can fake it by setting your own formatter:
CountryFormatter implements Formatter {
public String toString(int value) {
switch(value) {
case 0:
return "England";
case 1:
return "France";
}
return "Unknown";
}
}
picker.setFormatter(new CountryFormatter());
getValue() will still return an int, so you probably want to map the names of countries to their ids.
ADDED:
The implementation of NumberPicker has:
public void setRange(int start, int end, String[] displayedValues)
Which seems to do a better job of what you want then the above formatter.. although it isn't mentioned in the documentation so probably isn't part of the public api

try this solution, may help you
NumberPicker pickers = new NumberPicker(this);
String[] arrayPicker= new String[]{"abc","def","ghi","jkl","mno"};
//set min value zero
pickers.setMinValue(0);
//set max value from length array string reduced 1
pickers.setMaxValue(arrayPicker.length - 1);
//implement array string to number picker
pickers.setDisplayedValues(arrayPicker);
//disable soft keyboard
pickers.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
//set wrap true or false, try it you will know the difference
pickers.setWrapSelectorWheel(false);
//create button to test selected text string
btnPicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//get position (int) from number picker
int pos = pickers.getValue();
//get string from number picker and position
String selecPicker = arrayPicker[pos];
//test toast to get selected text string
Toast.makeText(context, selecPicker , Toast.LENGTH_SHORT).show();
}
});

This worked for me.
public class YourClassName extends AppCompatActivity {
NumberPicker picker = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_layout_file);
picker = (NumberPicker) findViewById(R.id.pickerId_From_your_Layout_file);
picker.setMinValue(0);
picker.setMaxValue(3);
picker.setDisplayedValues(new String[]{"English", "French","Kiswahili","عربى"});
}
}

Related

Need to change variable name in a for loop everytime in Java Android Studio

I am a beginner level programmer and I am again here to take everybody's help and solve my problem. Actually I don't have an error this time but I need to do something which I am not able to,
The thing is that I want to use a for loop 3 times and everytime I have a condition to check if my Quantity1 = 0 or not, again if my Quantity2 is = 0 or not and same for the third time. I can also repeat the code 3 times but I need to do this is because, I am uploading my data to a realtime database. And I am uploading my SelectedDate1 if Quantity1 != 0 and same for the three times, but to read them I have to know that how many Quantities and SelectedDates are uploaded and for that I have created a variable OrderQuantity. But the problem is if the user has selected the 1st date and the 3rd date and not the 2nd one as its quantity is 0, so when it is uploaded it shows OrderQuantity=2and the selectedDate1 comes under 1 but the 3rd date comes under 2nd node with name 3, but it should come with the name of variable+i, I hope you understand my question. And if not, please comment and I'll provide you an english video for what I want. Hoping your help as soon as possible.-
I think there is no use of main_activity.xml as it will make my question very big.
But here goes my MainActivity.java (without imports as it was very big)
public class MainActivity extends AppCompatActivity implements DatePickerFragment.applyDate, AdapterView.OnItemSelectedListener {
String CurrentDateString;
TextView mainDate;
Integer OrderQuantity = 3;
String itemOneDate;
String itemTwoDate;
String itemThreeDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button SelectDate1 = findViewById(R.id.SelectDateButton1);
Button SelectDate2 = findViewById(R.id.SelectDateButton2);
Button SelectDate3 = findViewById(R.id.SelectDateButton3);
SelectDate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(1, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate1;
}
});
SelectDate2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(2, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate2;
}
});
SelectDate3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(3, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate3;
}
});
ArrayAdapter<CharSequence> FoodAdapter = ArrayAdapter.createFromResource(this, R.array.FoodList, android.R.layout.simple_spinner_item);
FoodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner SelectItem1 = findViewById(R.id.SelectItem1);
SelectItem1.setAdapter(FoodAdapter);
SelectItem1.setOnItemSelectedListener(this);
Spinner SelectItem2 = findViewById(R.id.SelectItem2);
SelectItem2.setAdapter(FoodAdapter);
SelectItem2.setOnItemSelectedListener(this);
Spinner SelectItem3 = findViewById(R.id.SelectItem3);
SelectItem3.setAdapter(FoodAdapter);
SelectItem3.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> QuantityAdapter = ArrayAdapter.createFromResource(this, R.array.Quantity, android.R.layout.simple_spinner_item);
QuantityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Quantity1 = findViewById(R.id.SelectQuantity1);
Quantity1.setAdapter(QuantityAdapter);
Quantity1.setOnItemSelectedListener(this);
Spinner Quantity2 = findViewById(R.id.SelectQuantity2);
Quantity2.setAdapter(QuantityAdapter);
Quantity2.setOnItemSelectedListener(this);
Spinner Quantity3 = findViewById(R.id.SelectQuantity3);
Quantity3.setAdapter(QuantityAdapter);
Quantity3.setOnItemSelectedListener(this);
Button DoneButton = findViewById(R.id.DoneButton);
EditText PersonName = findViewById(R.id.PersonName);
EditText PersonPhone = findViewById(R.id.PersonPhone);
EditText PersonAddress = findViewById(R.id.PersonAddress);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference Name = database.getReference(PersonPhone.getText().toString() + "/Name");
Name.setValue(PersonName.getText().toString());
DatabaseReference Phone = database.getReference(PersonPhone.getText().toString() + "/Phone");
Phone.setValue(PersonPhone.getText().toString());
DatabaseReference Address = database.getReference(PersonPhone.getText().toString() + "/Address");
Address.setValue(PersonAddress.getText().toString());
//I need help here in these three if-else statements
if (Quantity1.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders" + "/1" + "/Date");
dateOne.setValue(itemOneDate);
}
if (Quantity2.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders" + "/2" + "/Date");
dateOne.setValue(itemTwoDate);
}
if (Quantity3.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders" + "/3" + "/Date");
dateOne.setValue(itemOneDate);
}
DatabaseReference OrderQuantities = database.getReference(PersonPhone.getText().toString() + "/OrderQuantity");
OrderQuantities.setValue(OrderQuantity);
}
});
}
public void setDate(int selectedYear, int selectedMonth, int selectedDay, int buttonNumber) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, selectedYear);
c.set(Calendar.MONTH, selectedMonth);
c.set(Calendar.DAY_OF_MONTH, selectedDay);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String CurrentDateString = format.format(c.getTime());
mainDate.setText(CurrentDateString);
if (buttonNumber == 1) {
itemOneDate = CurrentDateString;
} else if (buttonNumber == 2) {
itemTwoDate = CurrentDateString;
} else if (buttonNumber == 3) {
itemThreeDate = CurrentDateString;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Here is the image of the data saved on realtime database when 1st and 3rd date are selected.-
Also see that what I have selected on the virtual device.
And here is the link from where I learnt to make a datePickerFragment for selecting date.
Edit: go object-oriented
Edit: since my first two suggestions didn’t work for you, I am suggesting using some abstraction. Declare a class to hold a spinner and its related data, and iterate a list of such objects. Your list can hold a variable number of objects so there will be a variable number of spinners. Caveat: I don’t know Android UI programming, so may be missing a detail or two there. And I still have not compiled my code myself.
public class MySpinner {
private FirebaseDatabase database;
private Spinner quantity;
private String number;
private String itemDate;
public MySpinner(FirebaseDatabase database,
Spinner quantity, String number, String itemDate) {
this.database = database;
this.quantity = quantity;
this.number = number;
this.itemDate = itemDate;
}
/* #return true if there was a positive quantity to process, false otherwise */
public boolean processQuantity() {
if (quantity.getSelectedItem().toString().equals("0")) {
return false;
}
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString()
+ "/Orders" + number + "/Date");
dateOne.setValue(itemDate);
return true;
}
}
I have also object-orientedly fitted the class with a method to do the work for each spinner. Now with a list of objects of your class you may process each in turn in a loop like this:
for (MySpinner mySpinner : yourListOfMySpinners) {
if (! mySpinner.processQuantity()) { // quantity was 0
OrderQuantity -= 1;
}
}
I am leaving to yourself to fill objects into your list. There will probably also be some adjusting and tailoring that you will want to do.
Original answer follows.
Use an array or list
It’s not uncommon for beginners in programming to ask that question. It’s not quite the right question to ask. What you need is to iterate over your quantities in a loop. The solution to that is to put them into an array or list and iterate over that array or list. Code is not tested.
Spinner[] quantities = { Quantity1, Quantity2, Quantity3 };
for (int i = 0; i < quantities.length; i++) {
if (quantities[i].getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders/" + (i + 1) + "/Date");
dateOne.setValue(itemTwoDate);
}
}
While it would be possible to select a variable the way you describe, it’s neither the best, the easiest nor the nicest solution.
Or use a method
An alternative is to declare a method that does the job for each quantity and call it three times without using any loop. In your case the method may need to take quite many arguments, though, which is not ideal.
processSpinner(database, Quantity1, "/1", itemOneDate);
processSpinner(database, Quantity2, "/2", itemTwoDate);
processSpinner(database, Quantity3, "/3", itemThreeDate);
Your method may be declared like:
private void processSpinner(FirebaseDatabase database,
Spinner quantity, String number, String itemDate) {
if (quantity.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString()
+ "/Orders" + number + "/Date");
dateOne.setValue(itemDate);
}
}

Android - Loop random array and don't repeat

I am a beginner in Android App development. The code below is a quiz app and I want it to loop random questions and don't repeat the question, I tried to use a flag2 to randomly generate questions but I was getting compile errors, can anyone help me out with this. I'm also a beginner in Java.
TextView tv;
Button btn1;
RadioButton rb1,rb2,rb3;
RadioGroup rg;
String Questions[]={"What is 1+1?","Capital of USA?","What is 2+2","Echo with Laughter","Warg"};
String opt[]={"2","3","4", "New York","Washington DC","Maryland", "5","4","6","Stairway to Heaven","Hotel California","Highway to hell","Jon","Bran","Dario" };
String ans[]={"2","Washington DC","4","Stairway to heaven","Bran"};
int flag=0;
public static int correct;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tv=(TextView)findViewById(R.id.textView2);
btn1=(Button)findViewById(R.id.button2);
rg=(RadioGroup)findViewById(R.id.radioGroup);
rb1=(RadioButton)findViewById(R.id.radioButton);
rb2=(RadioButton)findViewById(R.id.radioButton2);
rb3=(RadioButton)findViewById(R.id.radioButton3);
tv.setText(Questions[flag]);
rb1.setText(opt[0]);
rb2.setText(opt[1]);
rb3.setText(opt[2]);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton uans = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
String ansText = uans.getText().toString();
if (ansText.equalsIgnoreCase(ans[flag])) {
correct++;
}
else {
Intent in = new Intent(getApplicationContext(),Token.class);
startActivity(in);
}
flag++;
if (flag < Questions.length) {
tv.setText(Questions[flag]);
rb1.setText(opt[flag * 3]);
rb2.setText(opt[(flag * 3)+1]);
rb3.setText(opt[(flag * 3)+2]);
}
else {
Intent in = new Intent(getApplicationContext(),Token.class);
startActivity(in);
}
}
use java.lang.Math.random().
it will return values from 0.0 to 0.1 convert those values in integer & get the question of the integer
Generate random number within the range which here would be from 0 to Maximum number of question, you can do it like below:
int numberOfQuestion = 5;
Random rn = new Random();
randomNum = rn.nextInt() % numberOfQuestion; // random number from 0 to MaxRange - 1
Instead of using three arrays you can create a class:
class Quiz{
String question;
String answer;
String[] options;
boolean asked;
}
And every time when the particular question is asked just make the flag asked to true, and before asking question just check if that question is asked or not, if not then only display the question.
Three string array actualy useless. You should use object ArrayList.
public class QuestionObject{
int id;
String question;
String [] options;
String answer;
--you should implement getter and setter--
public int getId(){
return this.id;
}
public void setId(int id){
this.id= id;
}
public String getQuestion(){
return this.question;
}
public void setQuesion(String question){
this.question = question;
}
public String[] getOptions()
{
return options;
}
public void setOptions(String[] options)
{
this.options= options;
}
public int getOptionsElement(int location)
{
return options[location];
}
public void setOptionsElement(int value, int location)
{
options[location] = value;
}
public String getAnswer(){
return this.answer;
}
public void setAnswer(String answer){
this.answer= answer;
}
}
And you should use this like
ArrayList<QuestionObject> questionObject = new ArrayList<QuestionObject>();
ArrayList<QuestionObject> answeredQuestion = new ArrayList<QuestionObject>();
Don't forget fill the questionObject with your Question options and aswers.
After that your logic must be implement.you can take the id of question when question display and remove the list. May be you can push the removed question another Arraylist.
//take the diplaying question this id can be your random number
int id = questionObject.getId(); //or int id = yourRandomNumber;
//store the another arraylist this question
answeredQuestion.add(questionObject.get(id));
//remove it from list than never show again
questionObject.remove(id);
I think this may help you.
EDIT:
This is due to while goes infinite, New declarations as Lists:
Random random = new Random();
String rightAnswer=null;
List<String> questions=new ArrayList<String>(); // list of questions
List<String> answers=new ArrayList<String>(); // list of answers
String[] ques={"What is 1+1?","Capital of USA?","What is 2+2","Echo with Laughter","Warg"};
questions.addAll(Arrays.asList(ques));
String[] ans={"2","Washington DC","4","Stairway to heaven","Bran"};
answers.addAll(Arrays.asList(ans));
ArrayList<String[]> options = new ArrayList<String[]>(); // list of arrays that holds options
String[] opt1={"2","3","4"};
String[] opt2={"New York","Washington DC","Maryland"};
String[] opt3={"5","4","6"};
String[] opt4={"Stairway to Heaven","Hotel California","Highway to hell"};
String[] opt5={"Jon","Bran","Dario" };
options.add(opt1);
options.add(opt2);
options.add(opt3);
options.add(opt4);
options.add(opt5);
And where you want to generate question you can write this code, I am assuming in onClick() of Button:
int questionNumber;
if(questions.size()>0) // only run if list contains something
{
questionNumber = random.nextInt(questions.size()); // generate random question from current list
String[] currentOptions=options.get(questionNumber);
tv.setText(questions[questionNumber]);
rb1.setText(currentOptions[0]);
rb2.setText(currentOptions[1]);
rb3.setText(currentOptions[2]);
rightAnswer=answers.get(questionNumber); // hold right answer in this variable
questions.remove(questionNumber); // remove question which is asked
answers.remove(questionNumber); // remove answer which is asked
options.remove(questionNumber); // remove options that are showed
}
else
{
tv.setText("No questions remaining");
}
This is tested, and I was able to get these results:
NOTE: Declaration part must be outside the function that generates random question, otherwise it will fail.

Compare text in EditText with defined String?

i'm new with Android and i'm writing a simple alarm clock application.when i type the string into the EditText like this "10:00,Monday" this string will compare syntax with the defined string if true it'll turn on the AlarmClock. But i don't know how to compare. May you give me an idea? Thanks so much. My app's interface and code below
1.My app's interface https://dl.dropbox.com/u/40382482/Screenshot%20from%202012-10-25%2023%3A51%3A14.png
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Calendar cal = Calendar.getInstance();
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat time = new SimpleDateFormat("hh:mm:ss");
final TextView labelDate = (TextView) findViewById(R.id.lblDate);
final TextView lableTime = (TextView) findViewById(R.id.lblTime);
labelDate.setText(date.format(cal.getTime()));
lableTime.setText(time.format(cal.getTime()));*/
final ArrayList<String> setAlarm = new ArrayList<String>();
//nhap noi dung vao edit text
final EditText alarmEnter = (EditText) findViewById(R.id.setting);
final Button button = (Button) findViewById(R.id.Okay);
OnClickListener add = new OnClickListener()
{
public void onClick(View v)
{
if(alarmEnter.getText().toString().equals(""))
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Info Missing");
builder.setMessage("Please Enter All Information");
builder.setPositiveButton("Continue", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface diablog, int which)
{
}
}
); builder.show();
}
else {
//compare string in EditText and defined string?
}
}
};
button.setOnClickListener(add);
}
To compare one string with another, use:
if(strText.equals("myString")){ // strText is the string from the edit text, myString is the string
// you are comparing it to
// do something
}else{
// do something else
}
This will return a boolean.
if (myEditText.getText().toString().equals(myString)) { ... }

Getting Values from DatePicker and TimePicker

I have 2 datepickers and 2 timepickers on a screen and also a submit button. The user selects the start date, start time, end date, and end time. The program then takes these values and stores them into variables, however the variables only return the default values for these controls. Is there anyway to get the updated value from each of these controls?
My code looks like this for the edit screen:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.editscreen);
timepickerStart = (TimePicker)findViewById(R.id.timePicker1);
timepickerEnd = (TimePicker)findViewById(R.id.timePicker2);
datepickerStart = (DatePicker)findViewById(R.id.datePicker1);
datepickerEnd = (DatePicker)findViewById(R.id.datePicker2);
submitbutton = (Button)findViewById(R.id.submit);
locationText = (EditText)findViewById(R.id.locationText);
eventText = (EditText)findViewById(R.id.eventText);
}
public void DateStart(View v)
{
GlobalVariables.datepickerYearStart = datepickerStart.getYear();
GlobalVariables.datepickerMonthStart = datepickerStart.getMonth();
GlobalVariables.datepickerDayStart = datepickerStart.getDayOfMonth();
}
public void DateEnd(View v)
{
GlobalVariables.datepickerYearEnd = datepickerEnd.getYear();
GlobalVariables.datepickerMonthEnd = datepickerEnd.getMonth();
GlobalVariables.datepickerDayEnd = datepickerEnd.getDayOfMonth();
}
public void TimeStart(View v)
{
GlobalVariables.timepickerHourStart = timepickerStart.getCurrentHour();
GlobalVariables.timepickerMinuteStart = timepickerStart.getCurrentMinute();
}
public void TimeEnd(View v)
{
GlobalVariables.timepickerHourEnd = timepickerEnd.getCurrentHour();
GlobalVariables.timepickerMinuteEnd = timepickerEnd.getCurrentMinute();
}
public void submitClicked(View v)
{
startActivity(new Intent(this, AddToCalendar.class));
}
Rewrite
Looking at your current code, let's stick with the various get methods from DatePicker and TimePicker. However you never call DateStart() or any of the others, they look like you have them set up for an OnClickListener... Regardless, try this:
public void submitClick(View v) {
DateStart(null);
TimeStart(null);
DateEnd(null);
TimeEnd(null);
// Do what you please your GlobalVariables
}
Though I might leave out the multiple GlobalVariables and store one long value for each date/time:
public void submitClick(View v) {
Calendar calendar = Calendar.getInstance();
calendar.set(datepickerStart.getYear(), datepickerStart.getMonth(),
datepickerStart.getDayOfMonth(), timepickerStart.getCurrentHour(),
timepickerStart.getCurrentMinute(), 0);
long startTime = calendar.getTimeInMillis();
// And similar approach for the end time, then use them however you please
}
You need to set a listener to your DatePicker:
DatePicker picker = new DatePicker(this);
picker.init(<year>, <monthOfYear>, <dayOfMonth>, new DatePicker.OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//set the value of the variable here
}
});

android dev how to underline and change color of word in string like a link color

I have a app that gets a string from a database and it sets to a label. Now i want that label to underline one word such as "This word should be underlined." and i want to be able to click on that underline word and get its value. So do i set it up before i send it to the database or after. Thanks for any help. I tried code below and each line is highlighted because of the for loop. please help
SpannableStringBuilder builder = new SpannableStringBuilder();
for(int i=0;i<ListClass.getLatestActivity().size();i++){
String myString = ListClass.getLatestActivity().get(i);
builder.append(myString);
String substringThatShouldBeClickable = myString.substring(0,myString.indexOf(' ')).trim();
MySpan span = new MySpan(substringThatShouldBeClickable);
span.setOnMySpanClickListener(mySpanOnClickListener);
int start = 0;
int end = builder.length();
builder.setSpan(span, start, end, 0);
builder.append("\n" + "\n") ;
}
RAInfo.setText(builder);
RAInfo.setMovementMethod(LinkMovementMethod.getInstance());
Ok, so there's a few things you'll need to do. They way to accomplish this is by using a span inside of the TextView.
First you'll need a class that extends ClickableSpan:
public class MySpan extends ClickableSpan {
public interface OnMySpanClickListener {
public void onMySpanClick(String tag);
}
private final String myData;
private OnMySpanClickListener mOnMySpanClickListener;
public MySpan(String tag) {
super();
if (tag == null) {
throw new NullPointerException();
}
myData = tag;
}
#Override
public void onClick(View widget) {
if (mOnMySpanClickListener != null) {
mOnMySpanClickListener.onMySpanClick(myData);
}
}
public OnMySpanClickListener getOnMySpanClickListener() {
return mOnMySpanClickListener;
}
public void setOnMySpanClickListener(OnMySpanClickListener onMySpanClickListener) {
mOnMySpanClickListener = onMySpanClickListener;
}
}
In your Activity, you'll set the text of the TextView like this:
String myString = getFromDatabase();
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(myString);
//You'll need to call the constructor for MySpan with only the value of the part
//of the string that you want to work with ("Bob" in the example), however you
//determine that.
String substringThatShouldBeClickable = getMySubstring(myString); //"Bob"
MySpan span = new MySpan(substringThatShouldBeClickable);
span.setOnMySpanClickListener(mySpanOnClickListener);
//start and end control the range of characters in the string that are clickable,
//so modify this part so it only underlines the characters you want clickable
int start = 0;
int end = bulider.length();
builder.setSpan(span, start, end, 0);
label.setText(builder);
label.setMovementMethod(LinkMovementMethod.getInstance());
Finally, you'll need a handler for the click events on the span:
MySpan.OnMySpanClickListener mySpanOnClickListener = new MySpan.OnMySpanClickListener() {
public void onMySpanClick(String tag) {
//Here is where you'll do your work with the value in the String "tag"
}
};
Hope this helps.

Categories

Resources