首页 > 解决方案 > 如何将数据从 Activity 传递到 CustomView?

问题描述

活动 B 有一个自定义视图,如下所示:

public class MakePaymentCustomView extends LinearLayout {
    private Context _context;
    public MakePaymentCustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        _context = context;
        setOrientation(LinearLayout.VERTICAL);
        LayoutInflater.from(context).inflate(R.layout.make_payment_custom_layout, this, true);
        String title;
        String subtitle;
        String[] listOfVouchers = ((MerchantDetailsActivity) getContext()).listOfVouchers;
        Log.d("LIZ OF VOUCHERS", listOfVouchers.toString());
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PaymentCustomView, 0, 0);
        try {
            title = a.getString(R.styleable.PaymentCustomView_customViewTitle);
            subtitle = a.getString(R.styleable.PaymentCustomView_customViewSubtitle);
        } finally {
            a.recycle();
        }
        // Throw an exception if required attributes are not set
        if (title == null) {
            throw new RuntimeException("No title provided");
        }
        if (subtitle == null) {
            throw new RuntimeException("No subtitle provided");
        }

        init(title, subtitle);
    }
    // Setup views
    private void init(String title, String subtitle) {
        List<String> categories = new ArrayList<String>();
        categories.add("Automobile");
        categories.add("Business Services");
        categories.add("Computers");
        categories.add("Education");
        categories.add("Personal");
        categories.add("Travel");
        TextView titleView = findViewById(R.id.customview_textview_title);
        TextView subtitleView = findViewById(R.id.customview_textview_subtitle);
        Spinner voucherList = findViewById(R.id.voucherSpinner);
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(_context, android.R.layout.simple_spinner_item, categories);
        voucherList.setAdapter(dataAdapter);
        titleView.setText(title);
        subtitleView.setText(subtitle);
    }
}

活动 A 有一个名为 的公共变量listOfVouchers。我正在尝试从自定义视图访问此变量,如下所示:

Log.d("LIZ OF VOUCHERS", listOfVouchers.toString());

但它返回以下错误:

com.app.ActivityA cannot be cast to com.app.ActivityB

如何在活动 B 的自定义视图中从活动 A 访问变量?需要它来填充自定义视图中的微调器。

标签: android

解决方案


您可以在活动 B 中找到您的自定义视图,以便在本地保存数据并将其传递给我,看看我在此处的回答


推荐阅读