在"首选项行"中添加一个按钮

Sud*_*hat 5 android android-preferences

我想在"设置"屏幕中显示一个按钮.这里已经提出这个确切的问题.但遗憾的是没有答案.:(

在此输入图像描述

为了达到这个目的,我创建了一个这样的自定义首选项 -

  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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这确实有效.但它表现得很奇怪.正如您在单击该按钮时所看到的,我正在将用户带到Activity调用BuyScreenActivity.奇怪的部分是当我按回BuyScreenActivity,我回到我的设置屏幕,但onDestroyonStopBuyScreenActivity不叫的.为什么它会那样?

如果我向下滚动设置屏幕,则会调用onStop&onDestroy.为什么这必须这样做?

小智 0

我不知道为什么会发生这种情况,但如果它困扰你,只需重写 BuyScreenActivity.java 中的 onBackPressed() 即可:

@Override
public void onBackPressed() {
    startActivity(new Intent(getContext(), SettingsACtivity.class));
}
Run Code Online (Sandbox Code Playgroud)

请注意,我假设您只能通过“设置”进入 BuyScreen。如果不是,那么很容易将前一个活动的名称放入意图数据中,然后将其切换到所需的活动。