Add a button in Preference Row

最后都变了- 提交于 2020-01-02 04:25:09

问题


I want a button in my Settings screen. This exact question has been asked here. But unfortunately has no answers. :(

In order to get to this, I created a custom preference like this -

  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;
    }
}

This does work. But it behaves strange. As you can see on click of that button I'm taking the user to Activity called BuyScreenActivity. The strange part is when I press back on BuyScreenActivity, I come back to my Settings screen but onDestroy and onStop of BuyScreenActivity is not called at all. Why would it behave that way?

If I scroll down the settings screen, onStop & onDestroy will then be called. Why does this have to behave that way?

来源:https://stackoverflow.com/questions/14194944/add-a-button-in-preference-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!