android - 如何将数据从 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 访问变量?需要它来填充自定义视图中的微调器。
解决方案
您可以在活动 B 中找到您的自定义视图,以便在本地保存数据并将其传递给我,看看我在此处的回答。
推荐阅读
- c# - Visual Studio - Outlook 插件 - 从 SQL 数据库填充组合框,为什么字符串值返回这样?
- bash - 如果已经存在,则 Bash 脚本分区跳过
- android - (android) 应该只在第一次调用 setAdapter() 吗?
- python - 自动包装 xlsxwriter python 的列,以便它们适合内容?
- matlab - 模型预测控制的计算矩阵
- xpath - 当标签为@href 时,xpath text() 返回“None”
- python - 如何根据不同的条件加入或合并两个数据框?
- sql-server - 数据库备份到 Azure url - SQL Server 2014
- javascript - 如何制作 React Material UI
100% 宽度 - vba - VBA Word:在word文档中找到的文本之前插入文本