我有一个带有自定义布局的首选项屏幕,其中包含一个带有 onClickListener 的按钮。这个想法是,如果我按下按钮,它所附加的首选项将被删除。如何确定单击的按钮附加到哪个首选项?
自定义布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:paddingEnd="?android:attr/scrollbarSize" >
<ImageView
android:id="@+android:id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="6dip"
android:layout_marginEnd="6dip"
android:layout_marginStart="15dip"
android:layout_marginTop="6dip"
android:layout_weight="1" >
<TextView
android:id="@+android:id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:singleLine="true"
android:text="Preference"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+android:id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@android:id/title"
android:layout_below="@android:id/title"
android:maxLines="4"
android:text="Summary"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="?android:attr/textColorSecondary" />
<Button
android:id="@+id/deleteButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="@drawable/delete_item"
android:focusable="false"
android:onClick="onRemoveButtonClick" />
</RelativeLayout>
</LinearLayout>
代码
public class MainActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preferencescreen);
addPreferencesFromResource(R.xml.prefs);
}
public void addPref() {
PreferenceManager preferenceManager = getPreferenceManager();
PreferenceScreen preferenceScreen = (PreferenceScreen) preferenceManager
.findPreference("mainPrefScreen");
ListPreference prefList = new ListPreference(this);
prefList.setTitle("New Item");
prefList.setEntries(R.array.Names);
prefList.setEntryValues(R.array.Values);
prefList.setLayoutResource(R.layout.preference);
prefList.setKey("New Item Key");
preferenceScreen.addPreference(prefList);
}
public void onRemoveButtonClick(View v) {
// ON Delete button Click here
// What TO Do
}
public void addApp(View v) {
addPref();
}
}