活动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
我如何可以访问活动A变量在活动B的自定义视图?将需要它来填充自定义视图的微调。
您的自定义视图在b活动中发现,为了在本地保存数据,并把它传递看看my answer here覆盖它。
我觉得你的做法是不正确的。如果您需要在自定义视图券的名单,你应该提供所谓的“setVouchers”自定义视图,类似的公共方法:
public void setVouchers(String[] listOfVouchers){
mVouchers = listOfVouchers;
}
其中mVouchers是您MakePaymentCustomView类的一个实例变量。一旦你定义的方法,把它的活动/破坏你的需要,你的情况活动A
使用共享偏好。不要保存共享偏好你的价值。获取自定义视图中的价值。利用股票的偏好值删除值后,以避免未知错误。
这是不是最好的答案,但只是建议。