I want to change android:hint depending on each model.
(Android device might have different sdcard path. I want to set this value.)
How can I get the element or change the attribute?
Such as
Preferences.java
public class Preferences extends PreferenceActivity {
private void setDeviceSDCardPath () {
String defaultPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
pref = getElementById(R.preferences.pref_id); // <--- invalid, but I want to do like this
pref.hint = "ex.) " + defaultPath; // <-- also invalid
}
}
preferences.xml
<PreferenceCategory android:title="#string/title">
<EditTextPreference
android:id="#+id/pref_id"
android:key="pref_key"
android:title="#string/pref_title"
android:summary="#string/pref_summary"
android:hint="/storage/sdcard"
android:defaultValue="/storage/sdcard/Download/"/>
</PreferenceCategory>
your_editText.setHint("Your New hint");
Check this doc
myTextView.setHint("My conditional hint");
See the javadoc for EditTextPreference:
http://developer.android.com/reference/android/preference/EditTextPreference.html
It is a subclass of DialogPreference and shows the EditText in a
dialog. This EditText can be modified either programmatically via
getEditText(), or through XML by setting any EditText attributes on
the EditTextPreference.
When you got the EditText object by using getEditText() on your EditTextPreference object you can simply use setHint(String message) method. I believe this should work:
EditTextPreference editPref = (EditTextPreference) findPreference(R.id.pref_id);
editPref.getEditText().setHint(message);
yout_editText.setSummary("some description to your preference edit text");
in xml: android:defaultValue or android:summary
Related
I'm passing a listview in to an onselect but theres a couple of ways it's called from different listviews. So i'm trying to work out which listview is being clicked.
I thought I could do the following however the string thats returned is like com.myapp.tool/id/32423423c (type thing) instead of lvAssets.
Here is what I've got:
#Override
public void onNumberRowSelect(ListView listview, clsNameID stat) {
if(listview.getAdapter().toString().equals("lvGenericAssets")){
} else if(listview.getAdapter().toString().equals("lvAssets")){
} else {
Functions.ShowToolTip(getApplicationContext(),
listview.getAdapter().toString());
}
}
As Emil Adz said in first, you can get the id of your list by calling list.getId();
Then use String idList = getResources().getResourceEntryName(id); and you will be able to get the name of the id you have given to your list
Why wont you just use: list.getId(); if you defined it in the XML file then you should define there an id for you ListView.
If you are doing this from code then you can use the list.setId(); to first set it's id.
Another thing you can do is to add a Tag to your listView: list.setTag("list1");
and latter on distinct this listView using the Tag: list.getTag();
Im trying to switch between Holo.Light and Holo (Dark) so everything in my application is changed to the theme the user sets in the preferences.
I've been looking at a few open source apps that this is done in and cant seem to make it work with my project, Any help on this would be greately appreciated.
The Current ISSUE im running into inside DashboardActivity.java is:
"I've having issues with "setTheme(Integer.parseInt( pref.getString("
DashboardActivity (Updated)
public class DashboardActivity extends Activity {
public static final int THEME_BLACK = R.style.DarkThemeAndroid;
public static final int THEME_WHITE = R.style.LightThemeAndroid;
public static final int THEME_WHITE_BLACK = android.R.style.Theme_Holo_Light_DarkActionBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// I've having issue with the "pref.getString" i've tried "Settings.getString" and get error about needing a getString method is needed in Settings.java
setTheme(Integer.parseInt( pref.getString("selectedTheme", String.valueOf(R.style.LightThemeAndroid) )));
setContentView(R.layout.dashboard_layout);
// the rest of my code
)
)
Settings (Updated)
public class Settings extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
final static String[] mThemeEntries = {
"Default (Light)",
"Dark"
};
final static String[] mThemeValues = {
String.valueOf(R.style.LightThemeAndroid),
String.valueOf(R.style.DarkThemeAndroid)
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Loads the XML preferences file.
addPreferencesFromResource(R.xml.settings);
// SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
ListPreference listPref = (ListPreference)findPreference("selectedTheme");
listPref.setEntries(mThemeEntries);
listPref.setEntryValues(mThemeValues);
listPref.setValue( pref.getString("selectedTheme", String.valueOf(mThemeValues[0]) ) );
XML Resources
Themes.xml
<style name="LightThemeAndroid" parent="android:style/Theme.Holo.Light">
</style>
<style name="DarkThemeAndroid" parent="android:style/Theme.Holo">
</style>
Settings.xml
<ListPreference
android:title="Themes"
android:summary="Change the UI of the application"
android:key="theme"
android:entries="#array/themesReturnValue"
android:entryValues="#array/themesDisplayWord"
android:defaultValue="Theme1" />
Arrays.xml
<string-array name="themesReturnValue">
<item>Light</item>
<item>Dark</item>
<item>LightActionBar</item>
</string-array>
<string-array name="themesDisplayWord">
<item>Theme1</item>
<item>Theme2</item>
<item>Theme3</item>
</string-array>
getTheme() is a non-static method and you are trying to call it in a static way (not from an instance variable). You need an instance of the object to call the non-static method. Also, the docs state
Note that this should be called before any views are instantiated in the Context (for example before calling setContentView(View) or inflate(int, ViewGroup)).
Docs
There exists non-static getTheme() method of the ContextThemeWrapper class that returns Theme object type. Change the name of the getTheme() method to a different one for example getThe() and you should be fine.
First like codeMagic said, you are calling getTheme in a non-static way, I would also put the theme related constants in 1 class. Try making getTheme a static method (Although i would probably create a seperate class just for theme). Apart from that, here is a solution I was working on 2 days ago as i couldn't find anywhere on google or here for an answer to a more dynamic fluid theme preference.
I start off with my preference fragment (in your case, activity). Then declare the themes and values into an array...
public class LayoutFragment extends PreferenceFragment {
final static String[] mThemeEntries = {
"Default (Light)",
"Dark"
};
final static String[] mThemeValues = {
String.valueOf(R.style.Theme_Default),
String.valueOf(R.style.Theme_Dark)
};
then in my oncreate method, i set these values (note, in the xml i do not set these values and there are no references to those values in the xml files)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_layout);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
ListPreference listPref = (ListPreference)findPreference("selectedTheme");
listPref.setEntries(mThemeEntries);
listPref.setEntryValues(mThemeValues);
listPref.setValue( pref.getString("selectedTheme", String.valueOf(mThemeValues[0]) ) );
}
Notice that i had converted these values to a string, dont ask why, but i was getting a whole lot of trouble trying to store the int value of those resource id's (this is also why xml values was not an option)...
now when ever i need to set a theme from the user preference... I just call
setTheme(Integer.parseInt( pref.getString("selectedTheme", String.valueOf(R.style.Theme_Default) )));
and off course you could provide a static method somewhere to do the castings etc without writing it for each activity.
EDIT: You don't need the array's to be static, I must off left them like that while I was trying different things to get it to work.
I'm trying to figure out how to capture data from a form using EditText & Spinner's and insert it into a SQLite database. I am able to write the hard coded attributes but when I try to use R.id.fieldName it throws an error due to being an Integer vice a String.
public class PetAdd extends Activity {
DBAdapter db = new DBAdapter(this);
private OnClickListener btnPetAddListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
db.open();
long id;
id = db.insertPet("name", "type", "breed", "sex", "notes");
/**id = db.insertPet(R.id.petName, R.id.SpinnerPetType, R.id.petBreed, R.id.SpinnerPetGender, R.id.EditTextPetAddOptions);*/
db.close();
}
};
I'm still trying to learn all this stuff and my brain is fried from looking at a plethora of online tutorials, examples and Google documentation. If anyone can show me how to do this or direct me to a barney style tutorial that breaks it down for me to understand what's going on, it'd be greatly appreciated.
R.id.fieldName is a numeric reference to the item in your Activity (provided it's part of your layout).
You'll need to call findViewById(R.id.fieldName) to get a refererene to it. You'll also need to cast it to the correct type of view (in your case EditText) and then call getText().toString() on the whole thing.
Putting it all together...
EditText myField = (EditText)findViewById(R.id.userName); //assuming you have a field named userName in your XML
String userNameValue = myField.getText().toString();
Oh, and welcome to Stack... don't forget to mark answers as correct and up-vote them when they're helpful.
If you use R.id.name you are in fact using internally generated int that Android uses. You need the raw data your spinner has.
I suggest you play with getItem and getItemId in your Spinner. If you are using a SimpleAdapter you can expect to get the ID of your item with getItemId.
The implementation of getItem is up to you. I usually use BaseAdapter or in the case of Spinners, ArrayAdapter, which has several convenient methods.
And with the EditText you need to call getText() to the EditText.
When I am using android on websites and reading emails, I notice that I can click on addresses to load into google maps, or click on phone numbers to call, or click on emails and send an email.
These elements on the web are formatted in a variety of ways, so there is some built in function that detects these sort of things.
How do I allow this within my app? I have a page which displays contact information in plain text and I would like the user to just be able to click.
Do I Absolutely need to create clicklisteners for each textview or is there a system function I just need to enable?
Use
android:autoLink="phone"
in textView in the xml layout file
Android has a utility expressly for this purpose: Linkify
TextView noteView = (TextView) findViewById(R.id.noteview);
noteView.setText(someContent);
Linkify.addLinks(noteView, Linkify.ALL);
See also: https://android-developers.googleblog.com/2008/03/linkify-your-text.html
import android.text.util.Linkify;
Linkify.addLinks(text, Linkify.PHONE_NUMBERS);
You can use it in TextView like this,
Set android:autoLink="phone" as below,
<TextView
android:layout_width="fill_parent"
android:id="#+id/text"
android:layout_height="wrap_content"
android:autoLink="phone"
android:gravity="center"
android:linksClickable="true"
android:text="#string/txtCredits" />
However,
For some reason above code does not work all time. So, add below code also,
TextView textView = (TextView) findViewById(R.id.text);
textView.setMovementMethod(LinkMovementMethod.getInstance());
android:autoLink="phone"
was working for me on all phones... except Samsung.
Therefore, I chose the following option. Transformed phone number texts to support click to call:
+49 / 30 123456789
and then used this static helper method to add web link support to my TextViews
public static void linkifyTextViews(#NonNull TextView... textViews) {
for (TextView textView : textViews) {
Linkify.addLinks(textView, Linkify.WEB_URLS);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
If you want to detect different patterns like emails, contact numbers, weblink and set a separate on click implementations for these patterns I suggest you to use CustomClickableEmailPhoneTextview
Sample Code to use the library.
CustomPartialyClickableTextview customPartialyClickableTextview= (CustomPartialyClickableTextview) findViewById(R.id.textViewCustom);
/**
* Create Objects For Click Patterns
*/
ClickPattern email=new ClickPattern();
ClickPattern phone=new ClickPattern();
ClickPattern weblink=new ClickPattern();
/**
* set Functionality for what will happen on click of that pattern
* In this example pattern is email
*/
email.setOnClickListener(new ClickPattern.OnClickListener() {
#Override
public void onClick() {
Toast.makeText(MainActivity.this,"email clicked",Toast.LENGTH_LONG).show();
}
});
/**
* set Functionality for what will happen on click of that pattern
* In this example pattern is phone
*/
phone.setOnClickListener(new ClickPattern.OnClickListener() {
#Override
public void onClick() {
Toast.makeText(MainActivity.this,"phone clicked",Toast.LENGTH_LONG).show();
}
});
/**
* set Functionality for what will happen on click of that pattern
* In this example pattern is weblink
*/
weblink.setOnClickListener(new ClickPattern.OnClickListener() {
#Override
public void onClick() {
Toast.makeText(MainActivity.this,"website clicked",Toast.LENGTH_LONG).show();
}
});
/**
* set respective regex string to be used to identify patter
*/
email.setRegex("\\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}\\b"); // regex for email
phone.setRegex("[1-9][0-9]{9,14}"); // regex for phone number
weblink.setRegex("^(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]"); // regex for weblink
/**
* add click pattern to the custom textview - first parameter is tag for reference second parameter is ClickPattern object
*/
customPartialyClickableTextview.addClickPattern("email",email);
customPartialyClickableTextview.addClickPattern("phone",phone);
customPartialyClickableTextview.addClickPattern("weblink",weblink);
Because my mainActivity does not run my Tab2Activity at startup until the user press the setting button to run the PreferenceActivity, therefore i have to first check the audioStatus boolean value in order to avoid unwanted boolean result but after this step i'm kinna lost because of the bug in CheckBoxPreference it gives me...
Now i don't know how to work with the logic comparison to get the audio even without navigating to Tab2Activity? Main problem here i'm facing is working with the logics yet getting the desirable result..
I'm kinna new in java/android and currently creating an car blackbox app can someone help me... Thanks :)
My mainActivity file
if(Tab2Activity.audioPref == false)
audioStatus = false;
else
audioStatus = Tab2Activity.audioPref;
if(audioStatus == false)
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
if(audioStatus == false)
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
My Tab2Activity.java file
public static boolean audioPref;
public static String timeIntervalPref;
public void getPrefs() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
audioPref = prefs.getBoolean("AudioPref", true);//Suppose to produce "false" isn't it?
timeIntervalPref = prefs.getString("TimeIntervalPref", "60000");
}
}
My xml file
<CheckBoxPreference
android:title="Audio"
android:defaultValue="True"
android:summary="Select w/o Audio when Recording"
android:key="AudioPref" />
save your settings to a SharedPreferences then read them from there rather than relying on the state of a public boolean in the Tab2Activity.
http://developer.android.com/reference/android/content/SharedPreferences.html
example of use:
http://saigeethamn.blogspot.com/2009/10/shared-preferences-android-developer.html
EDIT: I don't know why you are trying to get the preferences from tab2activity.
why wouldn't you do the following in mainActivity:
SharedPreferences prefs=PreferenceManager.getDefaultSharedreferences(getBaseContext());
audioStatus=prefs.getBoolean("AudioPref",true); // (only use true if you want the default to be true if the value has not yet been set, otherwise you should be doing ("AudioPref",false) )
if(!audioStatus)
{
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
}
The bug you linked describes issues when you try to set default shared preference values to 'false'. If you want that to be the default, then just use "false" as the default value when you go to retrieve the value using getBoolean(string,defValue)