vikky
vikky

Reputation: 77

Creating Android layout with java code in android

How can I add one TextView with the image in this.I want to add a TextView below the imageView.

   public View getView(int position, View convertView, ViewGroup parent) {
     ImageView imageView;

   if (convertView == null) {
        imageView = new ImageView(mContext);
       imageView.setLayoutParams(new GridView.LayoutParams(400, 400));
       imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
        } else {
      imageView = (ImageView) convertView;
   }

     imageView.setImageResource(mThumbIds[position]);

     return imageView;
    }

Upvotes: 1

Views: 807

Answers (2)

Blackbelt
Blackbelt

Reputation: 157447

You should use the xml layout editor to create your Grid's row and use an inflater to retrive the View Java's object. Programmatically, something like

LinearLayout parent = new LinearLayout(context);

parent.setLayoutParams(new GridView.LayoutParams(400, 400));
parent.setOrientation(LinearLayout.VERTICAL);

TextView textView = new TextView(context);
textView.setId(1)
ImageView imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
imageView.setId(0);

parent.addView(imageView);
parent.addView(textView);

should do it.

parent is what your getView will return. Of course you will have to change the cast from ImageView to LinearLayout. you can use findViewById with 0 and 1, to retrieve respectively the ImageView and the TextView, or getChildAt(0) and getChildAt(1) to do the same thing

Upvotes: 0

Nikunj
Nikunj

Reputation: 4157

     LinearLayout LL = new LinearLayout(this);
     LL.setOrientation(LinearLayout.VERTICAL);

     LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);

     LL.setLayoutParams(LLParams);

           ImageView imageView = new ImageView(mContext);

           //....your imageview code.......


           TextView textView = new TextView(mContext);

           //....your textview code.......


     LL.addView(imageview);
     LL.addView(textview);

Upvotes: 1

Related Questions