Search code examples
javaandroidxmllayout

How to create a function that reuses layout with making some changes


I want to make an app like Instagram. It needs to publish posts with images and description text. From previous answers I understand , that i should create a post layout and use it for creating other posts. My question is : How can i create a function that helps me to create posts similar to my post_layout but with changed text and image? So i need a function that will help me to create posts using one template post layout. What will be the best way of achieving this?


Solution

  • You can reuse it by making "inflate" to the layout but I would like to clarify that your return value will be of type "View"

    Example:-

    private View createPost(String text, Bitmap image){
    
       View createdPost = getLayoutInflater().inflate(R.layout.post_template,null);
       TextView tv_postTitle = createdPost.findViewById(R.id.fragment_post_tv_title);
       ImageView iv_postImage = createdPost.findViewById(R.id.fragment_post_iv_image);
    
       tv_postTitle.setText(text);
       iv_postImage.setImageBitmap(image);
    
       return createdPost;
       }
    

    I hope this is useful