Android 在首选项行中添加按钮
我想在我的设置屏幕上有一个按钮。有人提出了这个确切的问题。但不幸的是没有答案( 为了实现这一点,我创建了一个自定义首选项,如下所示-Android 在首选项行中添加按钮,android,android-preferences,Android,Android Preferences,我想在我的设置屏幕上有一个按钮。有人提出了这个确切的问题。但不幸的是没有答案( 为了实现这一点,我创建了一个自定义首选项,如下所示- public class CustomPreference extends Preference { private LinearLayout mWidgetContainer; private View mRowView; public CustomPreference(Context context) { su
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;
}
}
这确实有效。但它的行为很奇怪。正如你所看到的那样,点击该按钮,我将用户带到名为BuyScreenActivity
的活动中。奇怪的部分是当我再次按下BuyScreenActivity
时,我返回到我的设置屏幕,但onDestroy
和onStop
的是not打电话来了,为什么会这样
如果我向下滚动设置屏幕,onStop
&onDestroy
将被调用。为什么必须这样做?我不知道为什么会发生这种情况,但如果它困扰您,只需覆盖BuyScreenActivity.java中的onBackPressed():
@Override
public void onBackPressed() {
startActivity(new Intent(getContext(), SettingsACtivity.class));
}
请注意,我假设您只能通过设置进入BuyScreen。
如果您没有,那么很容易将上一个活动的名称放入意图数据中,并切换到所需的活动。您只需将setOnClickListener
of按钮公开给持有自定义首选项的任何活动。让宿主活动决定单击事件的操作。我将尝试并回来。我试过了。即使在onStart和onResume中,我似乎也找不到该按钮的引用:(