Doing stuff in main activity from PreferenceActivity? - java

I have this line info.setTextSize(TypedValue.COMPLEX_UNIT_SP, number_config); below my cases in onItemSelected for a spinner. (it sets the textsize of an EditText with a value set with the spinner)
Then I have a preferences activity, in which I have a switchpreference, and I would like the above line to be "active" when the switch is set to "On" and inactive when it's set to off. So the textsize does not change when it's set to off. How would you do this?
Thank you very much
My spinners onItemSelected:
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
switch (position) {
case 0:
config_textsize = "10.0f".toString();
break;
case 1:
config_textsize = "12.0f".toString();
break;
...
}
String number_config = Float.valueOf(config_textsize);
/*This line */ EditText info.setTextSize(TypedValue.COMPLEX_UNIT_SP, number_config);
}
Preferences Activity:
public class Settings extends PreferenceActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
This is my switchpreference in xml:
<SwitchPreference
android:key="EditTextSize"
android:title="Text Size"
android:summary="Change text size when editing" />

Try:
this should return true if switched on or false if not. It´s only an assumption, I had never used SwitchPreference, but try it...
EDIT
create a method which returns integer:
private int getPosition(){
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(YourActivity.this);
boolean switchOn = prefs.getBoolean("EditTextSize",
false);
int position=-1;
if(switchOn==false){
position=0;
}else if(switchOn==true){
position=1
}
return position;}

Related

How to change the background color of every item in a ListView?

I am developing an app which has a text message interface (something like Facebook Messenger, Whatsapp, etc). I want to be able to change the background color of all the chat bubbles (a ListView of TextViews) sent by the user when they pick a new color (in a NavigationView).
However, with the current code that I have, I only am able to change the color after the EditText used to compose the message is clicked again. Or I am able to only edit the first bubble sent, but as soon as the color is changed.
Here's what I tried :
ItemColor1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Toast.makeText(activity, "Couleur mise à jour", Toast.LENGTH_SHORT).show();
currentTheme = position;
SharedPreferences.Editor editor = pref.edit();
editor.putInt("indexColorSelected",currentTheme);
editor.apply();
chatAdapter.notifyDataSetChanged();
//the following changes only the first message sent
for(int i=0; i<chatAdapter.getCount(); i++){
ChatData message = chatMessageList.get(position);
TextView msg = activity.findViewById(R.id.text);
msg.setText(message.body);
msg.setBackgroundResource(R.drawable.user_color1);
}
}
});
ChatData is a custom Class that I created which looks like this :
public class ChatAdapter extends BaseAdapter {
private static LayoutInflater inflater = null;
private ArrayList<ChatData> chatMessageList;
private Context mContext;
ChatAdapter(Activity activity, ArrayList<ChatData> list) {
mContext = activity;
chatMessageList = list;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
...
}
Color drawable:
<corners
android:bottomRightRadius="5dp"
android:radius="40dp"/>
<gradient
android:angle="45"
android:endColor="#01f1fa"
android:startColor="#0189ff"
android:type="linear" />
</shape>
getView() method of the Adapter:
public View getView(int position, View convertView, ViewGroup parent) {
ChatData message = chatMessageList.get(position);
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.msglist, parent, false);
TextView msg = vi.findViewById(R.id.text);
msg.setText(message.body);
LinearLayout layout = vi.findViewById(R.id.message_layout);
LinearLayout parent_layout = vi.findViewById(R.id.message_layout_parent);
inflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// if message is mine then align to right
if (message.isMine) {
layout.setGravity(Gravity.RIGHT);
int couleurBubble = getCouleurSelectionnee();
switch(couleurBubble){
case R.color.c1: msg.setBackgroundResource(R.drawable.user_color1); break;
case R.color.c2: msg.setBackgroundResource(R.drawable.user_color2); break;
case R.color.c3: msg.setBackgroundResource(R.drawable.user_color3); break;
case R.color.c4: msg.setBackgroundResource(R.drawable.user_color4); break;
case R.color.c5: msg.setBackgroundResource(R.drawable.user_color5); break;
case R.color.c6: msg.setBackgroundResource(R.drawable.user_color6); break;
case R.color.c7: msg.setBackgroundResource(R.drawable.user_color7); break;
case R.color.c8: msg.setBackgroundResource(R.drawable.user_color8); break;
default: break;
}
parent_layout.setGravity(Gravity.RIGHT);
}
// If not mine then align to left
else {
layout.setGravity(Gravity.LEFT);
msg.setBackgroundResource(R.drawable.bot_chat);
parent_layout.setGravity(Gravity.LEFT);
}
return vi;
}
I don't really know where to go from here so any kind of help would be appreciated. If you want me to provide more code, let me know and I will.
Thank you.
I'm sharing how I would do it. Maybe, this can help you.
There's some strange issue because you are calling notifyDataSetChanged(). This would be enough to re-draw all message bubbles.
My ideia is:
Add a int variable to the adapter class (mColorResource). This variable will point to the proper drawable that should be used (like R.drawable.user_color1).
public class ChatAdapter extends BaseAdapter {
int mColorResource;
ChatAdapter(Activity activity, ArrayList<ChatData> list, int initialColorResource) {
mContext = activity;
chatMessageList = list;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// You must receive the color on the construtor
mColorResource = initialColor;
}
// Use this method to update the color (when user select a new color)
public void setColor(int newColorResource) {
mColorResource = newColorResource;
}
public View getView(int position, View convertView, ViewGroup parent) {
...
// Note how this if-else is cleaner now
if (message.isMine) {
layout.setGravity(Gravity.RIGHT);
msg.setBackgroundResource(mColorResource);
parent_layout.setGravity(Gravity.RIGHT);
} else {
layout.setGravity(Gravity.LEFT);
msg.setBackgroundResource(R.drawable.bot_chat);
parent_layout.setGravity(Gravity.LEFT);
}
...
}
}
Then, when a color is selected, find the proper drawable based on the view clicked and pass it to the adapter:
ItemColor1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
Toast.makeText(activity, "Couleur mise à jour", Toast.LENGTH_SHORT).show();
currentTheme = position;
SharedPreferences.Editor editor = pref.edit();
editor.putInt("indexColorSelected", currentTheme);
editor.apply();
// Here, you send the proper drawable...
// I'm not sure how you convert color selected to the drawable
// So, add your logic to convert the button clicked to a drawable here
// like R.drawable.user_color1
chatAdapter.setColor(R.drawable.NAME_OF_THE_COLOR);
// Request to re-draw all items from the list (all bubbles)
chatAdapter.notifyDataSetChanged();
}
});
Also, on your activity, you create the adapter with the last used color. Something like:
#Override
protected void onCreate(#Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
// Set a default color (if user is open you app for the first time)
int chatColor = R.drawable.user_color1;
// Add your logic to read the shared preference and convert that last color used to a valid drawable.
// Like chatColor = pref.getInt(indexColorSelected, R.drawable.user_color1) etc....
// Set the color in the adapter.
chatAdapter = newAdapter(this, mChatDataList, chatColor);
}

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.

I want a central way to control my buttons

Hi I have 2 lines each with a name textfield, 2 buttons and a textfield to show the amount. There will be more lines later.
I want 1 button to add 1 to the amount and the other to decrease the amount by 1.
But I don't know how to get the ID from the button I press. I have gotten this far.
I hope someone can let me know. How I can get the indexvalue depending on which button is pressed.
public class MainActivity extends AppCompatActivity {
private ArrayList<Integer> ButtonUp;
private ArrayList<Integer> Amount;
private ArrayList<Integer> ButtonDown;
int ArrayIndex = 0;
int Value = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonUp();
Amount();
ButtonDown();
}
// ArrayList ButtonUp
public void ButtonUp(){
ButtonUp.add(R.id.Bup1);
ButtonUp.add(R.id.Bup2);
}
// ArrayList Amount
public void Amount(){
Amount.add(R.id.Aantal1);
Amount.add(R.id.Aantal2);
}
// ArrayList ButtonDown
public void ButtonDown() {
ButtonDown.add(R.id.Bdown1);
ButtonDown.add(R.id.Bdown2);
}
// Get position ArrayList on press
// Publish new Value
public void buttonPress(View v) {
switch (v.getId()) {
case R.id.Bup1:
SetAmountUp(id);
displayQuantity(Value);
break;
case R.id.Bup2:
SetAmountUp(R.id.Bup2);
displayQuantity(Value);
break;
case R.id.Bdown1:
SetAmountDown(R.id.Bdown1);
displayQuantity(Value);
break;
case R.id.Bdown2:
SetAmountDown(R.id.Bdown1);
displayQuantity(Value);
break;
}
}
public void SetAmountUp(int indexNumberUp){
Value = Amount.get(ButtonUp.indexOf(indexNumberUp));
Value++;
Amount.set(ArrayIndex,Value);
}
public void SetAmountDown(int indexNumberDown){
Value = Amount.get(ButtonDown.indexOf(indexNumberDown));
Value--;
Amount.set(ArrayIndex,Value);
}
// Publish number
private void displayQuantity(int NewAmount) {
int ID = Amount.get(ArrayIndex);
TextView quantityTextView = (TextView) findViewById(ID);
quantityTextView.setText(NewAmount);
}
}
In the layout, declare an unique id to each button, then add android:onClick="increment" to each button.
In your class, create the method
public void increment(View view) {
switch (view.getId()){
case R.id.yourbuttonid1:
// do what you whant
break;
case R.id.yourbuttonid2:
// do with second editext
break
// ....
}
}
Same approach to decrease method.
It will be much easier for you if you used a recyclerView for that

How do I get the value of a Spinner of another class? (Getting NullPointerException)

I have two classes Settings and MainActivity. I am trying to get the selected item of a spinner created at the Settings class from the MainActivity class.
I used sharedpreferences within the Settings activity to save the selected spinner value when the activity closes. This works.
To get the value from Settings activity while in MainActivity I use
public static Settings getlang = new Settings();
and
getlang.getLang1().getItemAtPosition(getlang.getLang1().getSelectedItemPosition());
getLang1() is a methode I created in the Settings activity that returns the Spinner itself.
The problem is, If I try to do this without opening the Settings activity first and directly going into the MainActivity I get the NullPointerException at this line
getlang.getLang1().getItemAtPosition(getlang.getLang1().getSelectedItemPosition());
But If I first open the Settings activity and then go to MainActivity everything works fine.
How can I fix this?
Here is the Settings activity
public class Settings extends Activity {
public SharedPreferences prefsSet;
public String prefNameSet = "MyPrefSet";
public static final String PREFS_NAME_SET = "SAVEDATASET";
private static final String SPINNER1_STATE = "spinner1_state";
public int language;
public int userChoice;
private static Spinner spinner1;
private Button savesett;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
savesett = (Button) findViewById(R.id.bSaveSett);
spinner1 = (Spinner) findViewById(R.id.spinner1);
SharedPreferences sharedPref = getSharedPreferences("FileName",
MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("userChoiceSpinner", -1);
if (spinnerValue != -1)
// set the value of the spinner
spinner1.setSelection(spinnerValue);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
userChoice = spinner1.getSelectedItemPosition();
SharedPreferences sharedPref = getSharedPreferences("FileName",
0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("userChoiceSpinner", userChoice);
prefEditor.commit();
Toast.makeText(
parent.getContext(),
"Chosen Language: "
+ parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
savesett.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ourIntent = new Intent(Settings.this, MainActivity.class);
startActivity(ourIntent);
}
});
}
public int getLang() {
return userChoice;}
public Spinner getLang1() {
return Settings.spinner1;
}
The issue is that the Settings activity may or may not be instantiated. Given that it is your main activity that is trying to use it, it most likely never will be.
What you want to do is persist the value of the spinner in your preferences and not the index of the spinner item.
Consider the case of a user being able to use a spinner that selects how often they want a service to be checked by the app. The spinner choices are "1 minute", "5 minutes", "10 minutes", "15 minutes", "30 minutes", "1 hour".
When the preference is saved, we'll save 1, 5, 10, 15, 30, or 60.
The activity that uses this information will just get back an int that corresponds to how many minutes it should wait between refreshes.

Set text size of a TextView with value selected from a Spinner, on button click

I would like to set a value with a spinner, and then in my onClick method set the text size of a Remote View TextView (on a widget) to the selected value. How would I do this?
Thanks
I have tried:
String selected;
Context context = WidgetConfig.this;
static Spinner spinner;
...
spinner.setOnItemSelectedListener(this);
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
Log.v(TAG, "OnItemselected started");
switch (position) {
case 0:
selected = "10".toString();
Break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
View.OnClickListener mOnClickListener = new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "set remote view");
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
Log.v(TAG, "set txt size");
/* without this line*/ float number = Float.valueOf(selected.toString());
/* and this line, it runs fine */ views.setFloat(R.id.tvConfigInput, "setTextSize", number);
...
}
};
UPDATE:
I declared the string twice, so i fixed that, and now it's not crashing, but it not working.
The text size isn't changing.. what to do?
your string selected is null, you did define the selected string in a scope instead of a global var. Change it and it should work
String selected = "0"; // defined outside the function scope
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
Log.v(TAG, "OnItemselected started");
switch (position) {
case 0:
selected = "10".toString();
Break;
}
}
float number = Float.valueOf(selected);
Your answer is in the following:
Line 254 in WidgetConfig.java is calling a method on a null object.
11-20 21:07:29.018: E/AndroidRuntime(2547): java.lang.NullPointerException
11-20 21:07:29.018: E/AndroidRuntime(2547): at com.harteg.NotesWidgetPro.WidgetConfig$1.onClick(WidgetConfig.java:254)

Categories

Resources