Сохранение размера текста в общих настройках

1

Я пытаюсь сохранить размер текста в общих предпочтениях, при запуске проекта мое приложение неожиданно останавливается здесь, это код:
SharedPreferenceActivity.class

package com.SharedPreference;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;

public class SharedPreferenceActivity extends Activity 

{

SeekBar seek=(SeekBar)findViewById(R.id.seekBar1);
EditText ed1=(EditText)findViewById(R.id.editText1);
Button b=(Button)findViewById(R.id.button1);
private final String TEXT_VALUE_KEY="textvalue";
private final String FONT_SIZE_KEY="fontsize";
final String MyPref="preference";

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState)
 {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);  
b.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View arg0) {

SharedPreferences  pref=getSharedPreferences(MyPref,MODE_PRIVATE);              
SharedPreferences.Editor editor=pref.edit();            
editor.putFloat(FONT_SIZE_KEY,ed1.getTextSize());           
editor.putString(TEXT_VALUE_KEY, ed1.getText().toString());         
editor.commit();

}

});

 SharedPreferences prefs=getSharedPreferences(MyPref, MODE_PRIVATE);

 final float fontsize=prefs.getFloat(FONT_SIZE_KEY, 12);

 seek.setProgress((int) fontsize);

 ed1.setText(prefs.getString(TEXT_VALUE_KEY, "")); 

 ed1.setTextSize(seek.getProgress());

 seek.setOnSeekBarChangeListener(new  SeekBar.OnSeekBarChangeListener() {


public void onStopTrackingTouch(SeekBar arg0) {

// TODO Auto-generated method stub

            }

            public void onStartTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub

            }

            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                // TODO Auto-generated method stub
                ed1.setTextSize(fontsize);
            }
        });
    }
}

XML файл:

<?xml version="1.0" encoding="utf-8"?>

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"

 android:layout_width="fill_parent"

 android:layout_height="fill_parent"

 android:orientation="vertical" >

<TableRow >


  <SeekBar

     android:id="@+id/seekBar1"

   android:layout_width="match_parent"

   android:layout_height="wrap_content" />


</TableRow>

<TableRow >

<EditText

   android:id="@+id/editText1"

  android:layout_width="match_parent"

  android:layout_height="150dp"

  android:layout_weight="0.6"

  android:ems="10" ></EditText>


</TableRow>

<TableRow >

 <Button

 android:id="@+id/button1"

  android:layout_width="50dp"

 android:layout_height="50dp"

 android:text="Button" />

</TableRow>

</TableLayout>
Теги:
text-size

2 ответа

1
Лучший ответ

найдите точки в методе onCreate.

public void onCreate(Bundle savedInstanceState)
{
 super.onCreate(savedInstanceState);

 setContentView(R.layout.main);
 seek=(SeekBar)findViewById(R.id.seekBar1);
 ed1=(EditText)findViewById(R.id.editText1);
 b=(Button)findViewById(R.id.button1);
 ...
 ...
}
  • 0
    setContentView (R.layout.main); должны быть установлены ......... так что я отредактировал это ...
  • 1
    Спасибо, теперь мое приложение работает
0

ed1 не инициализируется с помощью findviewbyId в Oncreatre.....

поскольку вы можете получить только ed1, когда вы установили представление контента в onCreate

b, ed1, seekbar все должно быть инициализировано после этой строки "setContentView (R.layout.main)"; используя findviewbyId в Oncreatre.....

  • 1
    Спасибо, теперь мое приложение работает
  • 0
    это gr8 .......... :)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню