从PreferenceActivity xml Android中显示选择器

时间:2013-07-19 20:33:46

标签: android android-intent preferenceactivity

更新

我收到此错误:

Syntax error on token(s), misplaced construct(s)

以下是更新后的代码:

public class SettingsFragment extends PreferenceActivity {

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

        // Add a button to the header list.
        if (hasHeaders()) {
            TextView txt = new TextView(this);
            txt.setText("Falcon pro version 1.2 @falcon");
            txt.setGravity(Gravity.CENTER);
            setListFooter(txt);
        }

        Preference sharingPref = findPreference("sharing");

        sharingPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Share application");
            String shareMessage = "My text";
            shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareMessage);
            startActivity(Intent.createChooser(shareIntent, "Share"));
            return true;
        });

    }

    public void onBuildHeaders(List<Header> target) {
        loadHeadersFromResource(R.xml.preferences, target);
    }

}

=============================================== =================================

当用户点击Android偏好时,有没有办法显示android选择器?

或者是否可以从首选项xml调用此代码?

Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Share application");
String shareMessage = "My text";
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareMessage);
startActivity(Intent.createChooser(shareIntent, "Share"));

2 个答案:

答案 0 :(得分:3)

要访问preferenceActivity中的菜单项,您可以按以下方式请求首选项:

Preference sharingPref = findPreference("sharing");

“分享”是偏好的key

有了这个,你可以像这样添加setOnPreferenceClickListener

sharingPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
   public boolean onPreferenceClick(Preference preference) {
       Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
       shareIntent.setType("text/plain");
       shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Share application");
       String shareMessage = "My text";
       shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareMessage);
       startActivity(Intent.createChooser(shareIntent, "Share"));
       return true;
   }
});

<强>更新

抱歉,我错过了原始代码中的一行:

public boolean onPreferenceClick(Preference preference) {

我现在已经更新了。

答案 1 :(得分:0)

您应遵循Android指南设计偏好设置:

http://developer.android.com/design/patterns/settings.html

并参阅Api指南以快速但完整地概述Preference类:

http://developer.android.com/guide/components/fundamentals.html

也许ListPreference正是您所寻找的。