I am attempting to change the background color of my Android app (I'm new to the ADK).
I read in another question that I would have to use another LinearLayout between my main layout (RelativeLayout) and all of the other views in the app, and change the color of that instead. I want a preference to dictate which color the background changes to, and the preference activity and everything is running smoothly; however, when I pass R.id.bg (bg is the LinearLayout's ID) to findViewById(), it returns null and throws an NPE whenever I attempt to change the background color.
EDIT: Y'know what, here's the entire class's source. :P
public class Preferences extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
private void showToast(CharSequence text) {
Context context = getApplicationContext();
showToast(context, text, 3000);
}
private void showToast(Context context, CharSequence text, int duration) {
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equalsIgnoreCase("list_color")) {
LinearLayout bg = (LinearLayout) findViewById(R.id.bg);
String color = sharedPreferences.getString("list_color", "White");
if (bg == null) {
showToast("Unable to change background color");
} else {
if (color.equals("White")) {
bg.setBackgroundColor(android.R.color.white);
showToast("Background color set to white");
} else if (color.equals("Black")) {
bg.setBackgroundColor(android.R.color.black);
showToast("Background color set to black");
}
} // end NP test
}
}
}
You cannot fetch a View directly from preferences in the traditional manner.
The closest you can do is get the Preference using findPreference():
Preference myPreference = findPreference("key");
If you need the View (which I assume you do), you can try this:
View v = myPreference.getView(null, null);
And that should return the View container which represents the Preference.
Show your onCreate method.
Maybe you forget to add setContentView(R.layout.your_layout);:
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
or import incorrect R file.
Related
I have four buttons(ImageView) inside a popup window, each button will change the the color of a button in my service class to the desired color. When I click one of these buttons it will change the color but when I exit from the app en start it again, my option is not saved.
//Inner class inside my MainActivity
public static class SetReng {
static int reng;
public SetReng() {
}
public int getReng() {
return this.reng;
}
}
public void onGreen (View view) {
SetReng.reng = Color.GREEN;
ImageView Green = (ImageView)view.findViewById(R.id.kesk);
Green.setPressed(true);
Toast.makeText(MainActivity.this, "Bloq color set to green", Toast.LENGTH_SHORT).show();
editor.putInt("Which", SetReng.reng);
editor.apply();
}
Here's the code in my service that should load the color options
SetReng putReng = new SetReng();
int theReng= putReng.getReng();
SharedP= PreferenceManager.getDefaultSharedPreferences(context);
int colorOp= SharedP.getInt("Which", theReng);
mButtondeh= new Button(this);
mButtondeh.setBackgroundColor(colorOp);
What am I doing wrong?
I'm stuck with this for the last couple of days so anything will be appreciated!
Try using
...
editor.putInt("Which", SetReng.reng);
editor.commit(); // instead of apply
...
I solved it by replacing getReference() manager with getSharedPreference() and in my service, I changed PreferenceManager.getDefaultSharedPreferences(context); to SharedP = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); And now it works perfectly!
While writing Robotium testcase, I want to differentiate between two images(drawable) placed on same imageView. Drawables are placed dynamically. I have tried to get drawable with the help of getDrawable() but every time different drawable object is coming.
Is there any way to get the drawable id? Any help or guidance will be well appreciated.
You can't get the drawable id from the drawable itself, but you can store and retrieve the drawable id of the imageView using the setTag() and getTag() methods.
TestActivity.java
public class TestActivity extends Activity {
private static String TAG = "TestActivity";
private Activity mActivity;
private static int ID_TAG = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Log.d(TAG, "onCreate");
mActivity = this;
// set drawable
ImageView imgView = new ImageView(mActivity);
imageView.setImageResource(R.drawable.photo);
String value = String.format("%d", R.drawable.photo);
imageView.setTag(ID_TAG, value);
// get drawable
value = imageView.getTag(ID_TAG);
drawableId = Integer.parseInt(value);
if(drawableId == R.drawable.photo){
Log.d(TAG, "You found the photo");
}
}
}
I tried to solve my problem so i changed so much code. I change even title of the post.
I can change the color of imageview background in preferences ui successfully. But after leaving fragment and launch again, the ui can not be updated in the same way as before.
First of all, I use sherlockactionbar . There are 3 tabs . when 3rd bar is pressed, a fragment is , including buttons, is loaded. When one of button is pressed, another preference fragment is loaded.
The code below shows how to call preference fragment when one of the button is pressed :
SettingsMenuFragment.java
public class SettingsMenuFragment extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Button ICSbutton= (Button) view.findViewById(R.id.CallSearchSettingsButton);
ICSbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
clearFragmentStack();
SettingsIncomingSearchFragment removeSISF = (SettingsIncomingSearchFragment) getActivity().getSupportFragmentManager().findFragmentByTag("SISF");
if(removeSISF != null)
{
getActivity().getSupportFragmentManager().beginTransaction().remove(removeSISF).commit() ;
getActivity().getSupportFragmentManager().executePendingTransactions();
}
SettingsIncomingSearchFragment Prefrag = new SettingsIncomingSearchFragment();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(android.R.id.content, Prefrag ,"SISF");
transaction.addToBackStack(null);
transaction.commit();
getActivity().getSupportFragmentManager().executePendingTransactions();
}
} );}}
and the code below shows preferencefragment :
public class SettingsIncomingSearchFragment extends PreferenceListFragment implements SharedPreferences.OnSharedPreferenceChangeListener,PreferenceListFragment.OnPreferenceAttachedListener {
Context ctx ;
public static final String SHARED_PREFS_NAME = "settings";
LinearLayout mainlayout ;
LinearLayout sublayout ;
View view ;
Preference myPref ;
ImageView img ;
SharedPreferences sp ;
#Override
public void onCreate(Bundle icicle) {
ctx = getActivity() ;
super.onCreate(icicle);
addPreferencesFromResource(R.xml.pref_incomingsearchsettings);
myPref = (Preference) findPreference("incomingsearchbackgroundcolor");
setColor() ;
myPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
HSVColorPickerDialog cpd = new HSVColorPickerDialog( ctx, 0xFF4488CC, new OnColorSelectedListener() {
#Override
public void colorSelected(Integer color)
{
sp.edit().putString("incomingsearchbackgroundcolor", String.valueOf(color)).commit();
}
});
cpd.setTitle( "Pick a color" );
cpd.show();
return true ;
}
});
}
private void setColor() {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater)
getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.rectangle_layout, null);
mainlayout = (LinearLayout)view.findViewById(R.id.rectangle_main_layout_ll);
sublayout = (LinearLayout)mainlayout.findViewById(R.id.rectangle_layout_ll);
sp = ctx.getSharedPreferences(SHARED_PREFS_NAME, ctx.MODE_PRIVATE);
String defValue = null ;
defValue = sp.getString("incomingsearchbackgroundcolor", null);
img = (ImageView)sublayout.findViewById(R.id.iv_priority);
img.setBackgroundColor(Integer.parseInt(defValue));
}
#Override
public void onPreferenceAttached(PreferenceScreen root, int xmlId) {
// TODO Auto-generated method stub
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
if(key.equals("incomingsearchbackgroundcolor"))
{
sp = ctx.getSharedPreferences(SHARED_PREFS_NAME, ctx.MODE_PRIVATE);
String defValue = null ;
defValue = sp.getString("incomingsearchbackgroundcolor", null);
Log.d("Debug", defValue);
int iColor = Integer.parseInt(defValue);
img.setBackgroundColor(iColor);
img.invalidate();
if(this.isAdded())
{
getActivity().getSupportFragmentManager().beginTransaction().detach(this).commit() ;
getActivity().getSupportFragmentManager().executePendingTransactions();
getActivity().getSupportFragmentManager().beginTransaction().attach(this).commit();
getActivity().getSupportFragmentManager().executePendingTransactions();
}
}
}
#Override
public void onResume()
{
super.onResume();
sp.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
sp.unregisterOnSharedPreferenceChangeListener(this);
}
}
and this is preference xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:summary = "Options" android:title = "OPTIONS" android:key="options">
<CheckBoxPreference android:key="IncomingCallSearch" android:summary="On/Off" android:title="Enable Incoming Call Search" android:defaultValue="true"/>
</PreferenceCategory>
<PreferenceCategory android:summary = "Screen Settings" android:title = "Screen settings" android:key="ScreenSettings" >
<ListPreference
android:entries="#array/screenLocOptions"
android:entryValues="#array/screenLocValues"
android:key="incomingcallsearch_screenlocation"
android:title="Location"
android:defaultValue="Top"/>
<Preference
android:defaultValue="0xFF000000"
android:key="incomingsearchbackgroundcolor"
android:title="Background Color"
android:layout="#layout/rectangle_layout" />
</PreferenceCategory>
and this is the rectangle_layout xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:id="#+id/rectangle_main_layout_ll">
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:text="Background color"
android:layout_weight= "0.9"/>
<LinearLayout
android:layout_width="50dp"
android:layout_height="50dp"
android:orientation="vertical"
android:layout_weight= "0.1"
android:id="#+id/rectangle_layout_ll">
<ImageView
android:id="#+id/iv_priority"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
/>
</LinearLayout>
As i wrote previous version of this post, the code above runs successfully in the first the the fragment loaded, imageview background color updated in preferences ui. I try to write failure condition step by step :
1 . I select the 3rd bar from actionbar and a fragment loaded including buttons.2 . I press the button that loads preferences fragment(you can see the code above)
3 . In this preferencefragment, there is a preference including textview and imageview(you can see the details above)
4 . When i click this preference, a color picker ran.(you can see the details above)
5 . I choose a color from color picker and save it to sharedpreference.(you can see the details above)
6 . onsharedpreferencechanged event triggered and i change the background color of imageview(you can see the details above) succesfully.
7 . I leave fragment with choosing another tab from action bar or with using backpress button.
8 . I launch same fragment with pressing same button in 3rd bar.
9 . I again use color picker and onsharedpreferencechanged event is triggered.
10 . I can see with debugging that true color code is taken from sharedpreference and it is set to imageview background color and the code below is run :
getActivity().getSupportFragmentManager().beginTransaction().detach(this).commit() ;
getActivity().getSupportFragmentManager().executePendingTransactions();
getActivity().getSupportFragmentManager().beginTransaction().attach(this).commit();
getActivity().getSupportFragmentManager().executePendingTransactions();
11 . But preference is not updated in this time. The old color or black is seen in imageview.
Thank you very much
getSupportFragmentmanager().detach(this).attach(this).commit()
All the changes cumming only after the commit. So if you will call detach(this) and attach(this) without a commit at the middle you changed nothing.
Try doing some thing like this:
getSupportFragmentmanager().detach(this).commit();
getSupportFragmentmanager().attach(this).commit();
This is what stays behind the commit idea.
P.S
I did not found FragmentManager.detach() method in the API...
at last i solved the problem and it is really simple . I hope this post helps anyone who has problem with dynamic preference updating.
public class SettingsIncomingSearchFragment extends PreferenceListFragment
implements SharedPreferences.OnSharedPreferenceChangeListener,
PreferenceListFragment.OnPreferenceAttachedListener {
Context ctx ;
public static final String SHARED_PREFS_NAME = "settings";
<-- Begin : i delete these global variables and define them in methods locally and
set the values in methods -->
LinearLayout mainlayout ;
LinearLayout sublayout ;
View view ;
Preference myPref ;
ImageView img ;
SharedPreferences sp ;
<-- End : i delete these global variables and define them in methods locally and
set the values in methods -->
I have a color picker which I use in sharedPrefereces. With the default colorpicker I managed to acheive what I want, but I noticed there is no black or white colors. http://www.yougli.net/android/a-photoshop-like-color-picker-for-your-android-application/
I would like to use this code but in the last rows, he shows an example, where I can see it is attached to a preferenced Screen. Instead of it I use my own activity with buttons where using shared Preferences I can save datas/values (so its not a preferenceActivity, just an Activity). For example clicking on a layout results:
OptVertexColor = (LinearLayout) findViewById(R.id.OptVC);
OptVertexColor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoadChartVertexColor();
ColorPickerDialog dlg = new ColorPickerDialog(settings.this,
new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(int color) {
SaveChartVertexColor("vertexcolor", color);
}
}, loadedVertexColor);
dlg.setTitle("Select new color");
dlg.show();
}
});
The default color picker dialog appears and I can save a color. Now how can I use this without a preference screen and acheive the same thing? I tried to copy the code above to this code, but I coudnt figure out how to handle it.
public class MySettings extends PreferenceActivity implements OnPreferenceClickListener, ColorPickerDialog.OnColorChangedListener {
public boolean onPreferenceClick(Preference pref)
{
new ColorPickerDialog(this, this, DROIDS_COLOR_KEY, mPrefs.getInt(DROIDS_COLOR_KEY, DROIDS_COLOR_DEFAULT), DROIDS_COLOR_DEFAULT).show();
return true;
}
public void colorChanged(String key, int color)
{
((PreferenceScreen)this.findPreference(SETTINGS_KEY)).getEditor().putInt(key, color).commit();
}
}
Thank you in advance!
In your own Activity, add
implements ColorPickerDialog.OnColorChangedListener
to the class declaration.
Add to your class body:
public void colorChanged(String key, int color) {
//create your SharedPreferences and your SharedPreferences.Editor here
editor.putInt(key, color);
editor.commit();
}
And in a button click listener add:
new ColorPickerDialog(this, this, DROIDS_COLOR_KEY, mPrefs.getInt(DROIDS_COLOR_KEY, DROIDS_COLOR_DEFAULT), DROIDS_COLOR_DEFAULT).show();
This should work. Let me know if you I failed to answer your question, and I'll see what I can do.
I want to to have some validation for my EditText wherein I want to show "" icon (that comes when you put editText.setError("blah blah")) but don't want the text in the popup displaying that "blah blah".
Is there any way to do it? One way is to create a custom layout which will show the image icon in the EditText. But is there any better solution?
Problem solved after a lot of research and permutations- (Also thanks to #van)
Create a new class that will extend EditText something like this-
public class MyEditText extends EditText {
public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setError(CharSequence error, Drawable icon) {
setCompoundDrawables(null, null, icon, null);
}
}
Use this class as a view in your xml like this-
<com.raj.poc.MyEditText
android:id="#+id/et_test"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Now in the third step, just set a TextWatcher to your custom text view like this-
et = (MyEditText) findViewById(R.id.et_test);
errorIcon = getResources().getDrawable(R.drawable.ic_error);
errorIcon.setBounds(new Rect(0, 0, errorIcon.getIntrinsicWidth(), errorIcon.getIntrinsicHeight()));
et.setError(null,errorIcon);
et.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(s.toString().length()>6){
et.setError("", null);
}else{
et.setError("", errorIcon);
}
}
});
where R.drawable.ic_error =
Keeping text null solves the problem
But if we keep only null in setError(null), this won't show the validation error; it should be null along with second param.
You dont need to create a new EditText class or change xml. The solution is very simple:
Edittext editText= (EditText) rootView.findViewById(R.id.email);
String str= editText.getText().toString();
if(str.equalsIgnoreCase("") ){
Drawable dr = getResources().getDrawable(R.drawable.error);
//add an error icon to yur drawable files
dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());
editText.setCompoundDrawables(null,null,dr,null);
}
Sorry Rajkiran, but your solution is not working on Android 4.2 version. If I am trying to set null value for error, it is not even displayed. The solution I came up was to extend EditText and override setError method. No I have only error indicator without popup.
#Override
public void setError(CharSequence pError, Drawable pIcon) {
setCompoundDrawables(null, null, pIcon, null);
}
I have been dealing with the same problem. I wanted to use .setError() to my EditText when user insert null input. But I think the pop-out message is annoying, especially when you have more EditTexts.
My solution was naive and simple, but it worked on all devices I've tried so far.
I created my own class myEditText and just #Override this method:
#Override
public void setError(CharSequence error, Drawable icon) {
setCompoundDrawables(null, null, icon, null);
}
then use in layout.xml
<cz.project.myEditText
...
/>
and finally in my code
I put onFocusChangeListener to myEditText, so when someone clicks-in, the icon disappears.
myEditText input = (myEditText) findViewById(R.id.input);
input.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
input.setError(null);
});
if(val == null) input.setError("");
It works Exactly how I want = no pop-up message when .setError() is called on EditText.
To get only the error-icon without an error-message-popup only when setError("") is called (i.e. set an empty String as error-message) I use a custom EditText-class where I override setError(CharSequence, Drawable) like this:
#Override
public void setError(CharSequence error, Drawable icon) {
if (error == null) {
super.setError(null, icon);
setCompoundDrawables(null, null, null, null);
}
else if (error.toString().equals("")) setCompoundDrawables(null, null, icon, null);
else super.setError(error, icon);
}
Everything else stays the same:
Use setError(null) to get neither the icon nor the message-popup.
Use setError(errorMessage), where errorMessage is a String with length 1 at least, to get the icon and message-popup.
This is the very useful when you want to show the error messages for the edittext field when the user enter wrong information.this is very simply program only you have to use serError() method in the edittext.
Step 1:
Create button and implement onclickListener.
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Step 2:
Validate the input fields and set the error in the input field.
if(edName.length()>3){
if(edNumber.length()>3){
Toast.makeText(getApplicationContext(), "Login success", Toast.LENGTH_SHORT).show();
}else{
edNumber.setError("Number Mininum length is 4");
}
}else{
edName.setError("Name Mininum length is 4");
}
Refer this link for more:http://velmuruganandroidcoding.blogspot.in/2014/08/set-error-message-in-edittext-android.html