Android 如何将数据从活动传递到CustomView?

Android 如何将数据从活动传递到CustomView?,android,Android,活动B有一个自定义视图,如下所示: public class MakePaymentCustomView extends LinearLayout { private Context _context; public MakePaymentCustomView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); _context = context;

活动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);
    }
}
Log.d("LIZ OF VOUCHERS", listOfVouchers.toString());
但它返回以下错误:

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

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

在活动B中可以找到您的自定义视图,以便在本地保存数据并将其传递给用户。请查看其中的内容。

我认为您的方法不正确。如果您需要自定义视图中的凭证列表,则应在自定义视图中提供一个名为“SetCredentials”的公共方法,类似于:

公共作废设置凭证(字符串[]凭证列表){
mVouchers=凭证列表;
}
其中,mVouchers是MakePaymentCustomView类的实例变量。定义好方法后,在需要的活动/片段中调用它,在您的案例中,活动A使用共享首选项。 在共享首选项中保存您的值。 在自定义视图中获取您的值。 使用值后,从共享首选项中删除值以避免未知错误


这不是最好的答案,只是建议。

您应该对此问题提供反馈