1

Androidアプリの背景色を変更しようとしています(ADKは初めてです)。
別の質問で、メインレイアウト(RelativeLayout)とアプリ内の他のすべてのビューの間で別のLinearLayoutを使用し、代わりにその色を変更する必要があることを読みました。背景をどの色に変更するかを設定して、設定アクティビティとすべてがスムーズに実行されるようにします。ただし、R.id.bg(bgはLinearLayoutのID)をfindViewById()に渡すと、nullが返され、背景色を変更しようとするたびにNPEがスローされます。

編集:Y'知っている、これがクラス全体のソースです。: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

        }

    }
}
4

2 に答える 2

1

View従来の方法では、設定から直接フェッチすることはできません。

あなたができる最も近いものは、Preference使用を取得することですfindPreference()

Preference myPreference = findPreference("key");

(私はあなたがそうすると思います)が必要な場合は、Viewこれを試すことができます:

View v = myPreference.getView(null, null);

Viewそして、それはを表すコンテナを返すはずPreferenceです。

于 2012-11-25T00:59:42.573 に答える
-1

onCreateメソッドを表示します。たぶんあなたは追加するのを忘れますsetContentView(R.layout.your_layout);

super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);

または、間違ったRファイルをインポートします。

于 2012-11-24T23:41:19.190 に答える