Reputation: 326
I am trying to create a dynamic android layout with multiple views. The number of views are dependent on the items in a list.
<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>
I inflate this view
and then add to the mainlayout
View view = getLayoutInflater().inflate(R.layout.activity_category_view, null);
mainLayout.addView(view)
The context class for the view CategoryActivity
has a instance variable categoryId
I need to set the value this categoryId
and refer it later i.e. during onClick action and then take appropriate action
in the CategoryActivity class i have duly mentioned
setContentView(R.layout.activity_category_view);
I have tried various ways but still not able to resolve and am stuck for good !
Upvotes: 2
Views: 304
Reputation: 3825
You can do something like
android:tag="MyInstanceVariable"
<ImageView
android:id="@+id/img_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:tag="MyInstanceVariable"
android:foregroundGravity="center"
android:src="@android:drawable/ic_menu_view"/>
you can add it dynamically
iv.setTag("MyInstanceVariable");
iv.setTag(R.String.Tag,"MyInstanceVariable"); //For multiple Tag
and you can access in java file like
String tag = (String) iv.getTag();
String tag = (String) iv.getTag(R.String.Tag);
Upvotes: 1
Reputation: 6360
In case of dynamic views, you must use getTag
and setTag
methods to store and retrieve data into/from the views. See the below code based on your question:
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);
I hope this will help you.
Upvotes: 1