gpt4 book ai didi

android - 在 Android View 上下文类中设置实例变量

转载 作者:搜寻专家 更新时间:2023-11-01 09:37:31 26 4
gpt4 key购买 nike

我正在尝试创建一个具有多个 View 的动态 android 布局。 View 数取决于列表中的项目。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginBottom="5px"
android:layout_marginTop="5px"
android:orientation="vertical"
android:padding="5dp" tools:context=".CategoryActivity">

<ImageView
android:id="@+id/img_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:foregroundGravity="center"
android:src="@android:drawable/ic_menu_view"/>

<TextView
android:id="@+id/text_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Category"
android:textColor="#000000"
android:layout_alignParentStart="true"/></LinearLayout>

我膨胀这个 View ,然后添加到mainlayout

    View view = getLayoutInflater().inflate(R.layout.activity_category_view, null);
mainLayout.addView(view)

View CategoryActivity 的上下文类有一个实例变量 categoryId

我需要设置此 categoryId 的值并稍后引用它,即在 onClick 操作期间,然后采取适当的操作

在我适当提到的 CategoryActivity 类中

setContentView(R.layout.activity_category_view);

我尝试了各种方法,但仍然无法解决,永远卡住了!

最佳答案

如果是动态 View ,您必须使用getTagsetTag 方法在 View 中存储和检索数据。根据您的问题查看以下代码:

View view = getLayoutInflater().inflate(R.layout.activity_category_view, null);
view.setTag(categoryId);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int cat_id=(Integer)view.getTag();
// do whatever you want to do further with it
}
});
mainLayout.addView(view);

希望对您有所帮助。

关于android - 在 Android View 上下文类中设置实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41935847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com