我想要在“设置”屏幕上有一个按钮。这个问题已经被问过here https://stackoverflow.com/questions/10514005/add-a-button-into-prefrencescreen-android。但遗憾的是没有答案。 :(
为了实现这一点,我创建了一个像这样的自定义首选项 -
public class CustomPreference extends Preference {
private LinearLayout mWidgetContainer;
private View mRowView;
public CustomPreference(Context context) {
super(context);
}
public CustomPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected View onCreateView(ViewGroup parent) {
LayoutInflater viewInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRowView = viewInflater.inflate(R.layout.preferences_row_view, parent, false);
mWidgetContainer = (LinearLayout) mRowView.findViewById(android.R.id.widget_frame);
Button button = new Button(getContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
button.setLayoutParams(params);
button.setBackgroundResource(R.drawable.listview_row_bg);
button.setTextSize(14);
button.setPadding(5, 5, 5, 5);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), BuyScreenActivity.class);
getContext().startActivity(intent);
}
});
button.setTypeface(null, Typeface.BOLD);
button.setText("Buy now");
mWidgetContainer.addView(button);
return mRowView;
}
}
这确实有效。但它的行为很奇怪。正如您所看到的,单击该按钮后,我将用户带到名为“Activity”的活动BuyScreenActivity
。奇怪的是当我按下BuyScreenActivity
,我回到“设置”屏幕,但是onDestroy
and onStop
of BuyScreenActivity
根本没有被调用。为什么它会这样?
如果我向下滚动设置屏幕,onStop
& onDestroy
然后将被调用。为什么这必须是这样的?