我正在扩展 ConstraintLayout 以便能够进行自定义,并且希望从外部类或 layout.xml 获取活动启动意图,并在单击此自定义视图时启动该活动。我知道如何将图标和文本作为属性,但不知道如何将意图作为属性。以下是我目前拥有的。如有任何帮助,我们将不胜感激。
public class MyGridDelegate extends ConstraintLayout implements View.OnClickListener {
private String text;
private Drawable icon;
private Intent link;
public MyGridDelegate (...)
{
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MyGridLayoutDelegate, defStyle, 0);
String text = a.getString(R.styleable.MyGridLayoutDelegate_text);
Drawable icon = a.getDrawable(R.styleable.MyGridLayoutDelegate_icon);
Intent link = .....; // *********Intent is missing*********
}
@Override
public void onClick(View v) {
// Launch some activity that is received as attribute
MyGridDelegate.this.startActivity(this.link);
}
}
attrs.xml
<declare-styleable name="MyGridDelegate">
<attr name="text" format="string" />
<attr name="icon" format="integer" />
<attr name="link" format="******dont know*****" />
</declare-styleable>
layout_main.xml
<vendor.xxxx.yyy.MyGridLayout
style="@style/MyGridLayoutStyle"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent">
<vendor.xxxx.yyy.MyGridLayoutDelegate
style="@style/MyGridLayoutDelegateStyle"
app:icon="@drawable/settings_bl_icon"
app:text="Bluetooth"
app:link="****dont know*****"
android:layout_row="0"
android:layout_column="0"/>
我发现我可以将要启动的活动名称作为字符串传递。然后做这样的事情:
setOnClickListener(v -> {
Intent intent = new Intent();
intent.setClassName(getContext(), m_link);
getContext().startActivity(intent);
});