How to setText in selected textView - java

Needed some help here. In my map test app I have 2 Autocomplete textViews. First textView gets the address of marker on load as well as chages the address if map is dragged.
But I am struggling for second textView where I need the same feature depending which textView is active.
I tried it like:
private AutoCompleteTextView mFromAddress;
private AutoCompleteTextView mToAddress;
mFromAddress = (AutoCompleteTextView) findViewById(R.id.fromAddress);
mToAddress = (AutoCompleteTextView) findViewById(R.id.toAddress);
// Decoder Coding.. str prints address
if (mFromAddress.isSelected()) {
mFromAddress.setText(str);
} else if (mToAddress.isSelected()) {
mToAddress.setText(str);
}
But no expected results. Even the first textView stops working.
I am new to java and Android Studio. I am looking for some suggestions here.

Try hasFocus() function
if (mFromAddress.hasFocus()) {
mFromAddress.setText(str);
} else if (mToAddress.hasFocus()) {
mToAddress.setText(str);
}
Another way is that define another TextView in code and set it as active TextView when focus change in OnFocusChangeListener
AutoCompleteTextView activeET;
activeET = mFromAddress; // set mFromAddress as active text in start
mFromAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if(hasFocus)
activeET = mFromAddress;
}
});
mToAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if(hasFocus)
activeET = mToAddress;
}
});
Now you just need to set text to activeET
activeET.setText(str);

Related

Strikethrough text ListView cannot find symbol method

I'm doing a to-do list and I wanted add a strikethrough effect after double tapping the ListView but it gave me an error which says the following.
Cannot find symbol listView.setPaintFlags(listView.getPaintFlags() _ Paint.STRIKE_THRU_TEXT_FLAG)
How Can I solve it?
listView.setOnTouchListener(new View.OnTouchListener() {
private GestureDetector gd = new GestureDetector(MainActivity.this,new GestureDetector.SimpleOnGestureListener() {
public boolean onDoubleTap(MotionEvent e) {
ListView listView = (ListView) findViewById(R.id.listView);
listView.setPaintFlags(listView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
return true;
}
});
#Override
public boolean onTouch(View view, MotionEvent event) {
return gd.onTouchEvent(event);
}
});
}
I do not think the ListView has the method which provides the strikethrough feature on its items. I think the TextView inside an item of your ListView has the attribute which should work like the following.
TextView tv = (TextView) v.findViewById(android.R.id.text1);
tv.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
You might also consider implementing your custom adapter to get the reference of the TextView and strikethrough the view using the code above.

Get currentItem of (Vertical)ViewPager

I have an app with vertical slider to switch between different smileys (from happier to saddest)
My problem is i don't know how I can get currentItem of my ViewPager (When User is on a specific smiley)
I've tried
verticalViewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mPreferences.edit().putInt(PREF_KEY_CURRENT_SMILEY,verticalViewPager.getCurrentItem()).apply();
return false;
}
});
And in the other activity (where i have to store the current smiley selected) :
currentSmileyInt = mPreferences.getInt(PREF_KEY_CURRENT_SMILEY,-50);
currentSmileyString = Integer.toString(currentSmileyInt);
currentSmileyTextView.setText(currentSmileyString);
If i'm good the textview on the other activity should display an int between 1-6. (different positions), and if i'm not good it display -50.
I don't understand what i'm doing wrong, as i set verticalVP.setCurrentItem(3) the corresponding smiley is displayed ...
Thank you in advance and sorry for my bad english :)
**You can use ViewPager.OnPageChangeListener**
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
final SharedPreferences.Editor editor = pref.edit();
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
currentPage=position;
Toast.makeText(MainAsyncActivity.this, "position: "+position, Toast.LENGTH_SHORT).show();
editor.putInt("key_name",currentPage); // Storing integer
editor.commit(); // commit changes
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
**get stored value from SharedPreferences**
int currentSmileyInt= pref.getInt("key_name", 0);
Log.d("Keyname: ", String.valueOf(currentSmileyInt));
String currentSmileyString = Integer.toString(currentSmileyInt);
currentSmileyTextView.setText(currentSmileyString);
why don't you just use getcurrentItem method from viewpager. like following, will give you the pageNumber of the view pager.
// getting current Page
int page = mPager.getCurrentItem();
This method getCurrentItem will work for you to get a position of ViewPager fragment and you can use like this following:
((YourActivity)getActivity()).verticalViewPager.getCurrentItem());
YourActivityis where you are exactly using the ViewPager with adapter and getActivity() is the Context as a reference of your fragment and do not forget to make verticalViewPager object as public access specifier.

Set Background Color of a List Item if it is Clicked

I want to change the background color of the List Item depending on whether the item is clicked or not. How can I achieve this! I did tried the following:
articleListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Find the current article that was clicked on
Article currentArticle = mAdapter.getItem(position);
if (currentArticle.getUrl() != null) {
TextView article_TV = (TextView) findViewById(R.id.post_title);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
article_TV.setBackgroundColor(getApplicationContext().getColor(R.color.colorItemClicked));
}
else
article_TV.setBackgroundColor(getResources().getColor(R.color.colorItemClicked));
}
}
});
Update :-
Silly mistake it was. As suggested by ak sacha should be
TextView article_TV = (TextView) view.findViewById(R.id.post_title);
As suggested by ak sacha we can achieve it simply by using
TextView article_TV = (TextView) view.findViewById(R.id.post_title);
This is because we are using that in a adapter, so we need to find the view within listview row.Hence we use view.findviewbyid

refresh and alter layout on click of checkbox

I didn't really know how to phrase this.
Basically I have this method:
private void uploadFile(int maxSpinner) {
setContentView(R.layout.upload);
CheckBox local = (CheckBox) findViewById(R.id.local_checkbox);
Spinner dropdown = (Spinner)findViewById(R.id.spinner1);
local.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkbox = isChecked;
if( isChecked){
uploadFile(6);
Log.i("checked", "yes");
}
else {
uploadFile(5);
Log.i("checked", "no");
}
}
});
ArrayList<String> categories = new ArrayList<>();
for( int category = 1; category <= maxSpinner+1; category++){
categories.add(Integer.toString(category));
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, categories);
dropdown.setAdapter(adapter);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
category = arg2+1;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
The corresponding layout file has a checkbox and a spinner.
maxSpinner is the limit for the for-loop that sets the amount of Spinner elements. I want to change maxSpinner depending on whether the checkbox gets selected or not.
So in the beginning uploadFile() gets called elsewhere with 5 as the argument. When I click the checkbox local I want to call uploadFile again, but this time with either 6 or again 5 as an argument, so I get a different amount of elements for the spinner.
The way I tried it is seen above. Nothing happens when I click the checkbox, I can see in the log it always logs "yes", even though the checkbox never actually gets visibly checked.
any help would be appreciated,
thanks
sorry, it does work just as expected, it just doesn't update the checkbox because I'm not telling it to do so.

Android - default value in editText

In my app I have an edit user details page and I want to display the current name, email address etc in the corresponding editText fields and then the user can just erase that and enter a new one if they want.
Is there a way to do this? Thanks for any help
There is the hint feature? You can use the setHint() to set it, or set it in XML (though you probably don't want that, because the XML doesn't 'know' the name/adress of your user :) )
You can use EditText.setText(...) to set the current text of an EditText field.
Example:
yourEditText.setText(currentUserName);
From the xml:
android:text="yourtext"
You can use text property in your xml file for particular Edittext fields.
For example :
<EditText
android:id="#+id/ET_User"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yourusername"/>
like this all Edittext fields contains text whatever u want,if user wants to change particular Edittext field he remove older text and enter his new text.
In Another way just you get the particular Edittext field id in activity class and set text to that one.
Another way = programmatically
Example:
EditText username=(EditText)findViewById(R.id.ET_User);
username.setText("jack");
You can do it in this way
private EditText nameEdit;
private EditText emailEdit;
private String nameDefaultValue = "Your Name";
private String emailDefaultValue = "abc#xyz.com";
and inside onCreate method
nameEdit = (EditText) findViewById(R.id.name);
nameEdit.setText(nameDefaultValue);
nameEdit.setOnTouchListener( new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (nameEdit.getText().toString().equals(nameDefaultValue)){
nameEdit.setText("");
}
return false;
}
});
nameEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus && TextUtils.isEmpty(nameEdit.getText().toString())){
nameEdit.setText(nameDefaultValue);
} else if (hasFocus && nameEdit.getText().toString().equals(nameDefaultValue)){
nameEdit.setText("");
}
}
});
emailEdit = (EditText)findViewById(R.id.email);
emailEdit.setText(emailDefaultValue);
emailEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus && TextUtils.isEmpty(emailEdit.getText().toString())){
emailEdit.setText(emailDefaultValue);
} else if (hasFocus && emailEdit.getText().toString().equals(emailDefaultValue)){
emailEdit.setText("");
}
}
});
First you need to load the user details somehow
Then you need to find your EditText if you don't have it-
EditText et = (EditText)findViewById(R.id.youredittext);
after you've found your EditText, call
et.setText(theUserName);
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et = (EditText) findViewById(R.id.et);
EditText et_city = (EditText) findViewById(R.id.et_city);
// Set the default text of second EditText widget
et_city.setText("USA");
}
}
Use android android:hint for set default value or android:text
We wish there is a default value attribute in each view of android views or group view in future versions of SDK. but to overcome that, simply before submission, check if the view is empty equal true, then assign a default value
example:
/* add 0 as default numeric value to a price field when skipped by a user,
in order to avoid parsing error of empty or improper format value. */
if (Objects.requireNonNull(edPrice.getText()).toString().trim().isEmpty())
edPrice.setText("0");

Categories

Resources