我只是根据此question的答案设置了偏好活动的按钮。我的主要问题是,此按钮无法点击,而首选项活动的其他元素是可点击的。
我创建了一个简单的例子来证明我的困境,它应该显示出与复制和粘贴时相同的症状。
public class preferenceTest extends PreferenceActivity{
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "I got clicked", Toast.LENGTH_SHORT).show();
}
});
}
public static class MyPreferenceFragment extends PreferenceFragment
{
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preftest);
// Do Stuff
}
}
}
RES \布局\ activity_main.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="fill_parent"
android:orientation="vertical">
<ListView android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="@android:color/black"
android:layout_weight="10"/>
<Button android:text="This is a button on bottom of all preferences."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:textColor="@android:color/black"
android:layout_weight="1"/>
</LinearLayout>
RES \ XML \ preftest.xml
<PreferenceCategory
android:title="New Title"
android:summary="Title">
<ListPreference
android:key="list1"
android:title="List one"
android:summary="List1"
/>
<ListPreference
android:key="list2"
android:title="List two"
android:summary="List2"/>
</PreferenceCategory>
<CheckBoxPreference
android:key="check1"
android:title="check1"
android:summary="CheckBox Test"/>
</PreferenceScreen>
答案 0 :(得分:2)
我不确定您为什么要在PreferenceActivity中添加按钮,但您可以做的是添加一个普通的Preference
,然后通过活动代码进行单击。
例如,在preferences.xml
<Preference
android:key="@string/pref_key_dummy_pref_button"
android:title="@string/pref_title_dummy_pref_button" />
然后,在PreferenceActivity上创建一个Preference对象:
Preference mDummyButtonPref;
从onCreate初始化它:
addPreferencesFromResource(R.xml.preferences);
mDummyButtonPref= findPreference(getString(R.string.pref_key_dummy_pref_button));
然后,添加覆盖onPreferenceTreeClicked来处理点击次数:
@Override
@Deprecated
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
if (preference == mDummyButtonPref) {
Log.v(TAG, "Dummy got clicked");
}
}