Null ImageView Reference - android

I'm trying to get a reference to an ImageView object and for whatever reason, it keeps coming back as null.
XML:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dip">
<ImageView android:id="#+id/application_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="#+id/label" android:text="Application Name" />
<CheckBox android:id="#+id/check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" />
</LinearLayout>
Java:
ImageView img = (ImageView) v.findViewById(R.id.application_icon);
I don't feel like I'm doing anything wrong yet my img var always comes back as null. What's wrong with this picture?

Sat's answer is correct, i.e., you need a proper layout, but setContentView() is not the only way to reference a View. You can use a LayoutInflater to inflate a parent layout of the View (even if it is not shown) and use that newly inflated layout to reference the View.
public class MyActivity extends Activity {
Context context;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
// the rest of yout code
private void someCallback() {
LayoutInflater inflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.iconLayout, null);
ImageView img = (ImageView) ll.findViewById(R.id.application_icon);
// you can do whatever you need with the img (get the Bitmap, maybe?)
The only change you need to your xml file is to add an ID to the parent layout, so you can use it with the LayoutInflater:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="iconLayout"
<!-- all the rest of your layout -->
<ImageView android:id="#+id/application_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<!-- all the rest of your layout -->
</LinearLayout>

When you are referencing the imageView , make sure that you are using the proper layout, i.e. setContentView(R.layout.yourIntendedXmlLayout);
That xml should contain your imageView. Then you can refer to your imageView.

use
ImageView img = (ImageView)findViewById(R.id.application_icon);

Related

Custom expandable card with child views

I am new to Android development and feel like this is a really trivial problem, but I cannot word it well enough to find a solution online, so I might as well ask the question here.
My goal is to create a reusable component that is essentially an expandable card like the one described here: https://material.io/design/components/cards.html#behavior.
To do it, I created a custom view that extends a CardView:
public class ExpandableCardView extends CardView {
public ExpandableCardView(Context context) {
super(context);
}
public ExpandableCardView(Context context, AttributeSet attrs) {
super(context, attrs);
// get custom attributes
TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ExpandableCardView, 0, 0);
String heading = array.getString(R.styleable.ExpandableCardView_heading);
array.recycle();
// inflate the layout
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.expandable_card_view, this, true);
// set values
TextView headingTextView = findViewById(R.id.card_heading);
headingTextView.setText(heading.toUpperCase());
// set collapse/expand click listener
ImageView collapseExpandButton = findViewById(R.id.collapse_expand_card_button);
collapseExpandButton.setOnClickListener((View v) -> toggleCardBodyVisibility());
}
private void toggleCardBodyVisibility() {
LinearLayout description = findViewById(R.id.card_body);
ImageView imageButton = findViewById(R.id.collapse_expand_card_button);
if (description.getVisibility() == View.GONE) {
description.setVisibility(View.VISIBLE);
imageButton.setImageResource(R.drawable.ic_arrow_up);
} else {
description.setVisibility(View.GONE);
imageButton.setImageResource(R.drawable.ic_arrow_down);
}
}
}
And the layout:
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/expandable_card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="16dp"
android:animateLayoutChanges="true"
app:cardCornerRadius="4dp">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_header"
android:padding="12dp"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/card_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="#color/colorPrimary"
android:layout_alignParentLeft="true"
android:text="HEADING"/>
<ImageView
android:id="#+id/collapse_expand_card_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
app:srcCompat="#drawable/ic_arrow_down"/>
</RelativeLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_body"
android:padding="12dp"
android:layout_marginTop="28dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:visibility="gone" >
</LinearLayout>
</androidx.cardview.widget.CardView>
Ultimately I want to be able to use it like so in my activities, usually multiple instances per activity:
<xx.xyz.yy.customviews.ExpandableCardView
android:id="#+id/card_xyz"
android:layout_width="match_parent"
android:layout_height="match_parent"
custom_xxx:heading="SOME HEADING" >
<SomeView></SomeView>
</xx.xyz.yy.customviews.ExpandableCardView>
Where SomeView is any text, image, layout or another custom view altogether, typically with data bound from the activity.
How do I get it to render SomeView inside the card body? I want to take whatever child structure is defined within the custom view and show it in the card body when it is expanded. Hope I made it easy to understand.
I think that a better approach would be to define the layout that will be inserted into the CardView ("SomeView") in a separate file and reference it with a custom attribute like this:
<xx.xyz.yy.customviews.ExpandableCardView
android:id="#+id/card_xyz"
android:layout_width="match_parent"
android:layout_height="match_parent"
custom_xxx:heading="SOME HEADING"
custom_xxx:expandedView="#layout/some_view"/>
I'll explain my rationale at the end, but let's look at an answer to your question as stated.
What you are probably seeing with your code is SomeView and expandable_card_view appearing all at once in the layout. This is because SomeView is implicitly inflated with the CardView and then expandable_card_view is added through an explicit inflation. Since working with layout XML files directly is difficult, we will let the implicit inflation occur such that the custom CardView just contains SomeView.
We will then remove SomeView from the layout, stash it, and insert expandable_card_view in its place. Once this is done, SomeView will be reinserted into the LinearLayout with the id card_body. All this has to be done after the completion of the initial layout. To get control after the initial layout is complete, we will use ViewTreeObserver.OnGlobalLayoutListener. Here is the updated code. (I have removed a few things to simplify the example.)
ExpandableCardView
public class ExpandableCardView extends CardView {
public ExpandableCardView(Context context) {
super(context);
}
public ExpandableCardView(Context context, AttributeSet attrs) {
super(context, attrs);
// Get control after layout is complete.
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
// Remove listener so it won't be called again
getViewTreeObserver().removeOnGlobalLayoutListener(this);
// Get the view we want to insert into the LinearLayut called "card_body" and
// remove it from the custom CardView.
View childView = getChildAt(0);
removeAllViews();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.expandable_card_view, ExpandableCardView.this, true);
// Insert the view into the LinearLayout.
((LinearLayout) findViewById(R.id.card_body)).addView(childView);
// And the rest of the stuff...
TextView headingTextView = findViewById(R.id.card_heading);
headingTextView.setText("THE HEADING");
// set collapse/expand click listener
ImageView collapseExpandButton = findViewById(R.id.collapse_expand_card_button);
collapseExpandButton.setOnClickListener((View v) -> toggleCardBodyVisibility());
}
});
}
private void toggleCardBodyVisibility() {
LinearLayout description = findViewById(R.id.card_body);
ImageView imageButton = findViewById(R.id.collapse_expand_card_button);
if (description.getVisibility() == View.GONE) {
description.setVisibility(View.VISIBLE);
imageButton.setImageResource(R.drawable.ic_arrow_up);
} else {
description.setVisibility(View.GONE);
imageButton.setImageResource(R.drawable.ic_arrow_down);
}
}
}
expandable_card_view.java
The CardView tag is changed to merge to avoid a CardView directly nested within a CardView.
<merge
android:id="#+id/expandable_card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="16dp"
android:animateLayoutChanges="true"
app:cardCornerRadius="4dp">
<RelativeLayout
android:id="#+id/card_header"
android:padding="12dp"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal" >
<TextView
android:id="#+id/card_heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="#color/colorPrimary"
android:layout_alignParentLeft="true"
android:text="HEADING"/>
<ImageView
android:id="#+id/collapse_expand_card_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
app:srcCompat="#drawable/ic_arrow_down"/>
</RelativeLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_body"
android:padding="12dp"
android:layout_marginTop="28dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:visibility="gone" >
</LinearLayout>
</merge>
activity_main.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.customcardview.ExpandableCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_android" />
<TextView
android:id="#+id/childView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Say my name."
android:textSize="12sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/imageView" />
</androidx.constraintlayout.widget.ConstraintLayout>
</com.example.customcardview.ExpandableCardView>
</LinearLayout>
So, why do I suggest that you use a custom attribute to include SomeView in the layout as I identified at the beginning? In the way outlined above, SomeView will always be inflated and there is some effort to switch the layout around although SomeView may never be shown. This would be expensive if you have a lot of custom CardViews in a RecyclerView for instance. By using a custom attribute to reference an external layout, you would only need to inflate SomeView when it is being shown and the code would be a lot simpler and easier to understand. Just my two cents and it may not really matter depending upon how you intend to use the custom view.

Android - How to make child LinearLayout match parent RelativeLayout's height

I am putting this LinearLayout inside RelativeLayout.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#66000000"
android:gravity="center">
<ImageView
android:layout_width="30dp"
android:layout_height="23dp"
android:src="#drawable/big_tick" />
</LinearLayout>
What I am trying to do is - to show which item has been chosen. I set LinearLayout's height and width match_parent. It is only matching parent(RelativeLayout)'s width, not height.
This is what I have intended to do:
This is what I am getting:
LinearLayout is not taking whole height of its parent.
There are 2 reasons, why I am using Relative layout as parent:
The LinearLayout should be in upside(should cover) book information with 40% black color
To show this symbol on the top of book
The whole XML looks like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<LinearLayout
android:id="#+id/llBook"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="6dp"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="5dp"
android:paddingLeft="11dp"
android:paddingRight="2dp"
android:paddingTop="8dp">
<ImageView
android:id="#+id/ivCover"
android:layout_width="95dp"
android:layout_height="146dp" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="#232425"
android:textSize="12sp" />
<TextView
android:id="#+id/tvAuthor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textColor="#848586"
android:textSize="10sp" />
</LinearLayout>
<ImageView
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignRight="#id/llBook"
android:layout_marginRight="6dp"
android:background="#drawable/shape_round_book_status"
android:padding="8dp"
android:src="#drawable/icon_new" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#66000000"
android:gravity="center">
<ImageView
android:layout_width="30dp"
android:layout_height="23dp"
android:src="#drawable/big_tick" />
</LinearLayout>
</RelativeLayout>
I am using this RelativeLayout in BaseAdapter class using which I am filling GridView with items.
public class LibraryAdapter extends BaseAdapter {
Context context;
RealmResults<RBook> rBooks;
LayoutInflater inflater;
public LibraryAdapter(Context context, RealmResults<RBook> rBooks) {
this.context = context;
this.rBooks = rBooks;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return rBooks.size();
}
#Override
public Object getItem(int position) {
return rBooks.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
RBook rBook = (RBook) getItem(position);
View view = convertView;
if(view == null) {
// new row is needed to inflate new row
view = inflater.inflate(R.layout.listitem_library_book, parent, false);
}
Bitmap bitmap = BitmapFactory.decodeByteArray(rBook.getCover() , 0, rBook.getCover().length);
ImageView ivCover = (ImageView) view.findViewById(R.id.ivCover);
ivCover.setImageBitmap(bitmap);
TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle);
tvTitle.setText(rBook.getTitle());
TextView tvAuthor = (TextView) view.findViewById(R.id.tvAuthor);
tvAuthor.setText(rBook.getAuthor());
return view;
}
}
EDIT:
Try1: as cj1098 suggested I have changed child LinearLayout to RelativeLayout. Unfortunately, no effect
Try2: as challenger suggested, I have used this inside my child LinearLayout, but effect was like this:
Try3: as codeMagic suggested, I have changed child LinearLayout's
gravity="center"
to ImageView's
layout_gravity="center"
In result, LinearLayout is not taking whole height.
So my question is how make child LinearLayout match parent RelativeLayout's height?
Try to add this to the LinearLayout:
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
Any way use can use this without even using the LinearLayout (with fixing the size of the drawable "big_tick" ):
<ImageView
android:layout_width="30dp"
android:background="#66000000"
android:layout_height="23dp"
android:src="#drawable/big_tick" />
I think that using this layout by itself is fine. It is the fact that you are putting it into a ListView is causing some sort a havoc.
However, you can force the overlay to align itself bottom and top with the book layout:
android:layout_alignBottom="#id/llBook"
android:layout_alignTop="#id/llBook"
After that maybe you still have a few margins to fix, but the two lines above will make the overlay be as big as the book layout.
it is taking the full height of its parent. Get rid of the padding on your child linear layout. Then if that doesn't work. Switch your linearLayout to a relativeLayout. (It's better anyway) another limitation is the actual images you are using. Do they have differing heights?
Remove the LinearLayout totally, use the imageview with src 'tick' as a direct child of the Relative layout with:
andriod:centerInParent=true
and then add View with the desired background transparency that has
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"

Android: setting text in each new view within a for loop

So I have an XML layout1 which is just a LinearLayout with three text views. I also have another XML layout2 with ScrollView and a LinearLayout inside it. I'm using this for loop to create several of the layout2 inside the LinearLayout of the ScrollView. It's working fine but I want to be able to set the text of each of the TextViews within the for loop. I'm not sure how to access these TextViews as I can only set one id within the XML file, will that not cause problems if I tried to access their id inside the for loop?
private void setUpResults() {
for (int i = 1; i < totalQuestions; i++) {
parent.addView(LayoutInflater.from(getBaseContext()).inflate(
R.layout.result_block, null));
}
}
Here is the result_block xml file (layout1) :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/layoutSelectedAnswer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/border"
android:orientation="horizontal"
android:paddingBottom="#dimen/option_padding_bottom"
android:paddingTop="#dimen/option_padding_top" >
<TextView
android:id="#+id/tvOptionALabel2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:text="#string/option_a"
android:textColor="#color/white"
android:textSize="#dimen/option_text_size" />
<TextView
android:id="#+id/tvSelectedAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:text="#string/option"
android:textColor="#color/white"
android:textSize="#dimen/option_text_size" />
</LinearLayout>
<LinearLayout
android:id="#+id/layoutCorrectAnswer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/border"
android:orientation="horizontal"
android:paddingBottom="#dimen/option_padding_bottom"
android:paddingTop="#dimen/option_padding_top" >
<TextView
android:id="#+id/tvOptionBLabel2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:text="#string/option_b"
android:textColor="#color/white"
android:textSize="#dimen/option_text_size" />
<TextView
android:id="#+id/tvCorrectAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:text="#string/option"
android:textColor="#color/white"
android:textSize="#dimen/option_text_size" />
</LinearLayout>
</LinearLayout>
Let's say I wanted to set the TextView with the id as tvCorrectAnswer to a different String value in each loop, how should I access it?
Sure, you can do it like this:
private void setUpResults () {
LayoutInflater i = LayoutInflater.from(getBaseContext());
for (int i = 1 /* should be zero? */; i < totalQuestions; i++) {
View view = i.inflate(R.layout.result_block, parent, false);
TextView correctAnswer = (TextView) view.findViewById(R.id.tvSelectedAnswer);
correctAnswer.setText("My Answer Text");
parent.addView(view);
}
}
The key is, inflate using the parent as the container, but don't attach it (the false parameter). Then you'll get a reference to the inflated view, which you can then directly reference to do your findViewById() calls (which will limit the search to that particular ViewGroup). Then add it to the parent and continue to the next item.
Once you have added all your views in your ViewGroup you can use ViewGroup.getChildAt(int) to get a one of the views you have inserted. Once you get one of the views you can access any of its inner views. Something like this.
for(int i = 0; i < parentView.getChildCount();++i) {
View v = parentView.getChildAt(i);
Textview tv = (TextView) v.findViewById(R.id.tvOptionALabel2);
//And so on...
}

Accessing the Custom View in android

I am trying to create a icon and a short description below it. I have created a customised View class with a ImageView and a TextView and i integrated it with my xml file, now the imageView and the default text appears in the screen,i don't know how to change the text content of the textview or the source of the imageview.
MyView.java
package sda.jk;
public class MyView extends LinearLayout{
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
LayoutInflater li=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v= li.inflate(R.layout.myview, this);
}
}
myview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_launcher"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="my view"/>
</LinearLayout>
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/sda.jk"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<sda.jk.MyView
android:id="#+id/myView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</sda.jk.MyView>
</LinearLayout>
Step-1 First assign id to image view and text view in myview. xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/myImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_launcher"
/>
<TextView
android:id="#+id/myText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="my view"/>
</LinearLayout>
Step-2
initialize your own view in oncreate method using
MyView mv = (MyView)findViewById(R.id.myView1);
step-3
initilize image view and text view using findViewById method of your own view
TextView textView = (TextView) mv.findViewById(R.id.myText);
ImageView imageView = (ImageView) mv.findViewById(R.id.myImage);
step-4
set text to text view using setText method
textView.setText("Sunil Kumar Sahoo");
set background image to image view using
imageView.setBackgroundResource(R.drawable.ic_launcher);
Your oncreate method will be like the following (from step-2 to step-4)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyView mv = (MyView)findViewById(R.id.myView1);
TextView textView = (TextView) mv.findViewById(R.id.myText);
textView.setText("Sunil Kumar Sahoo");
ImageView imageView = (ImageView) mv.findViewById(R.id.myImage);
imageView.setBackgroundResource(R.drawable.ic_launcher);
}
You write a function in sda.jk.MyView for setting text. For changing text, just call the function with a string parameter
Class MyView extends LinearLayout
{
//...
public void setUserText(String str)
{
textview.setText(str);
}
//...
}
You can add custom attributes by writing a custom attr.xml and loading the attributes in your custom view's constructor. For a full example check this page
http://javawiki.sowas.com/doku.php?id=android:custom-view-attributes
There is a useful feature in TextView called compund drawables, which allows you to incorporate a drawable to be drawn above, below, left or right of your text.
use it like so:
<TextView
android:id="#+id/txt"
android:text="my compound drawable textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="#drawable/xxxxx" />
you can use drawableBottom, drawableLeft etc.. as well.
this way you don't need to implement your own class.
For accessing individual elements from a View hierarchy, use the findViewById method. Refer to http://developer.android.com/reference/android/view/View.html#findViewById%28int%29
You would have to provide identifiers to your view elements in your XML thus:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/ic_launcher" />
<TextView
android:id="#+id/txtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="my view" />
</LinearLayout>
and refer them from your custom view class thus:
ImageView imageView = (ImageView)v.findViewById(R.id.imgView);
TextView textView = (TextView)v.findViewById(R.id.txtView);
Typically, you would like to keep the views as instance variables (members) so that you can change them from other methods.

What does LayoutInflater in Android do?

What is the use of LayoutInflater in Android?
The LayoutInflater class is used to instantiate the contents of layout XML files into their corresponding View objects.
In other words, it takes an XML file as input and builds the View objects from it.
What does LayoutInflator do?
When I first started Android programming, I was really confused by LayoutInflater and findViewById. Sometimes we used one and sometimes the other.
LayoutInflater is used to create a new View (or Layout) object from one of your xml layouts.
findViewById just gives you a reference to a view than has already been created. You might think that you haven't created any views yet, but whenever you call setContentView in onCreate, the activity's layout along with its subviews gets inflated (created) behind the scenes.
So if the view already exists, then use findViewById. If not, then create it with a LayoutInflater.
Example
Here is a mini project I made that shows both LayoutInflater and findViewById in action. With no special code, the layout looks like this.
The blue square is a custom layout inserted into the main layout with include (see here for more). It was inflated automatically because it is part of the content view. As you can see, there is nothing special about the code.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Now let's inflate (create) another copy of our custom layout and add it in.
LayoutInflater inflater = getLayoutInflater();
View myLayout = inflater.inflate(R.layout.my_layout, mainLayout, false);
To inflate the new view layout, all I did was tell the inflater the name of my xml file (my_layout), the parent layout that I want to add it to (mainLayout), and that I don't actually want to add it yet (false). (I could also set the parent to null, but then the layout parameters of my custom layout's root view would be ignored.)
Here it is again in context.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// inflate the main layout for the activity
setContentView(R.layout.activity_main);
// get a reference to the already created main layout
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.activity_main_layout);
// inflate (create) another copy of our custom layout
LayoutInflater inflater = getLayoutInflater();
View myLayout = inflater.inflate(R.layout.my_layout, mainLayout, false);
// make changes to our custom layout and its subviews
myLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
TextView textView = (TextView) myLayout.findViewById(R.id.textView);
textView.setText("New Layout");
// add our custom layout to the main layout
mainLayout.addView(myLayout);
}
}
Notice how findViewById is used only after a layout has already been inflated.
Supplemental Code
Here is the xml for the example above.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/activity_main_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<!-- Here is the inserted layout -->
<include layout="#layout/my_layout"/>
</LinearLayout>
my_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="#color/colorPrimary">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="5dp"
android:textColor="#android:color/white"
android:text="My Layout"/>
</RelativeLayout>
When do you need LayoutInflater
The most common time most people use it is in a RecyclerView. (See these RecyclerView examples for a list or a grid.) You have to inflate a new layout for every single visible item in the list or grid.
You also can use a layout inflater if you have a complex layout that you want to add programmatically (like we did in our example). You could do it all in code, but it is much easier to define it in xml first and then just inflate it.
When you use a custom view in a ListView you must define the row layout.
You create an xml where you place android widgets and then in the adapter's code you have to do something like this:
public MyAdapter(Context context, List<MyObject> objects) extends ArrayAdapter {
super(context, 1, objects);
/* We get the inflator in the constructor */
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
/* We inflate the xml which gives us a view */
view = mInflater.inflate(R.layout.my_list_custom_row, parent, false);
/* Get the item in the adapter */
MyObject myObject = getItem(position);
/* Get the widget with id name which is defined in the xml of the row */
TextView name = (TextView) view.findViewById(R.id.name);
/* Populate the row's xml with info from the item */
name.setText(myObject.getName());
/* Return the generated view */
return view;
}
Read more in the official documentation.
LayoutInflater.inflate() provides a means to convert a res/layout/*.xml file defining a view into an actual View object usable in your application source code.
basic two steps: get the inflater and then inflate the resource
How do you get the inflater?
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
How do you get the view assuming the xml file is "list_item.xml"?
View view = inflater.inflate(R.layout.list_item, parent, false);
Here is another example similar to the previous one, but extended to further demonstrate inflate parameters and dynamic behavior it can provide.
Suppose your ListView row layout can have variable number of TextViews. So first you inflate the base item View (just like the previous example), and then loop dynamically adding TextViews at run-time. Using android:layout_weight additionally aligns everything perfectly.
Here are the Layouts resources:
list_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/field1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"/>
<TextView
android:id="#+id/field2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
</LinearLayout>
schedule_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
Override getView method in extension of BaseAdapter class
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = activity.getLayoutInflater();
View lst_item_view = inflater.inflate(R.layout.list_layout, null);
TextView t1 = (TextView) lst_item_view.findViewById(R.id.field1);
TextView t2 = (TextView) lst_item_view.findViewById(R.id.field2);
t1.setText("some value");
t2.setText("another value");
// dinamically add TextViews for each item in ArrayList list_schedule
for(int i = 0; i < list_schedule.size(); i++){
View schedule_view = inflater.inflate(R.layout.schedule_layout, (ViewGroup) lst_item_view, false);
((TextView)schedule_view).setText(list_schedule.get(i));
((ViewGroup) lst_item_view).addView(schedule_view);
}
return lst_item_view;
}
Note different inflate method calls:
inflater.inflate(R.layout.list_layout, null); // no parent
inflater.inflate(R.layout.schedule_layout, (ViewGroup) lst_item_view, false); // with parent preserving LayoutParams
This class is used to instantiate layout XML file into its corresponding View objects. It is never be used directly -- use getLayoutInflater() or getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on. For example:
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
Reference: http://developer.android.com/reference/android/view/LayoutInflater.html
LayoutInflater is a class used to instantiate layout XML file into its corresponding view objects which can be used in Java programs.
In simple terms, there are two ways to create UI in android. One is a static way and another is dynamic or programmatically.
Suppose we have a simple layout main.xml having one textview and one edittext as follows.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/layout1"
>
<TextView
android:id="#+id/namelabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter your name"
android:textAppearance="?android:attr/textAppearanceLarge" >
</TextView>
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="14dp"
android:ems="10">
</EditText>
</LinearLayout>
We can display this layout in static way by
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
A dynamic way of creating a view means the view is not mentioned in our main.xml but we want to show with this in run time. For example, we have another XML in layout folder as footer.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/TextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Add your record"
android:textSize="24sp" >
</TextView>
We want to show this textbox in run time within our main UI. So here we will inflate text.xml. See how:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TextView t = (TextView)inflater.inflate(R.layout.footer,null);
lLayout = (LinearLayout)findViewById(R.id.layout1);
lLayout.addView(t);
Here I have used getSystemService (String) to retrieve a LayoutInflater instance. I can use getLayoutInflator() too to inflate instead of using getSystemService (String) like below:
LayoutInflator inflater = getLayoutInflater();
TextView t = (TextView) inflater.inflate(R.layout.footer, null);
lLayout.addView(t);
Inflating means reading the XML file that describes a layout (or GUI element) and to create the actual objects that correspond to it, and thus make the object visible within an Android app.
final Dialog mDateTimeDialog = new Dialog(MainActivity.this);
// Inflate the root layout
final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater().inflate(R.layout.date_time_dialog, null);
// Grab widget instance
final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
This file could saved as date_time_dialog.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/DateTimeDialog" android:layout_width="100px"
android:layout_height="wrap_content">
<com.dt.datetimepicker.DateTimePicker
android:id="#+id/DateTimePicker" android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout android:id="#+id/ControlButtons"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_below="#+id/DateTimePicker"
android:padding="5dip">
<Button android:id="#+id/SetDateTime" android:layout_width="0dip"
android:text="#android:string/ok" android:layout_weight="1"
android:layout_height="wrap_content"
/>
<Button android:id="#+id/ResetDateTime" android:layout_width="0dip"
android:text="Reset" android:layout_weight="1"
android:layout_height="wrap_content"
/>
<Button android:id="#+id/CancelDialog" android:layout_width="0dip"
android:text="#android:string/cancel" android:layout_weight="1"
android:layout_height="wrap_content"
/>
</LinearLayout>
This file could saved as date_time_picker.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content" `enter code here`
android:padding="5dip" android:id="#+id/DateTimePicker">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:baselineAligned="true"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/month_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="1dp"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="#+id/month_plus"
android:layout_width="45dp"
android:layout_height="45dp"
android:background="#drawable/image_button_up_final"/>
<EditText
android:id="#+id/month_display"
android:layout_width="45dp"
android:layout_height="35dp"
android:background="#drawable/picker_middle"
android:focusable="false"
android:gravity="center"
android:singleLine="true"
android:textColor="#000000">
</EditText>
<Button
android:id="#+id/month_minus"
android:layout_width="45dp"
android:layout_height="45dp"
android:background="#drawable/image_button_down_final"/>
</LinearLayout>
<LinearLayout
android:id="#+id/date_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0.5dp"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="#+id/date_plus"
android:layout_width="45dp"
android:layout_height="45dp"
android:background="#drawable/image_button_up_final"/>
<EditText
android:id="#+id/date_display"
android:layout_width="45dp"
android:layout_height="35dp"
android:background="#drawable/picker_middle"
android:gravity="center"
android:focusable="false"
android:inputType="number"
android:textColor="#000000"
android:singleLine="true"/>
<Button
android:id="#+id/date_minus"
android:layout_width="45dp"
android:layout_height="45dp"
android:background="#drawable/image_button_down_final"/>
</LinearLayout>
<LinearLayout
android:id="#+id/year_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0.5dp"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="#+id/year_plus"
android:layout_width="45dp"
android:layout_height="45dp"
android:background="#drawable/image_button_up_final"/>
<EditText
android:id="#+id/year_display"
android:layout_width="45dp"
android:layout_height="35dp"
android:background="#drawable/picker_middle"
android:gravity="center"
android:focusable="false"
android:inputType="number"
android:textColor="#000000"
android:singleLine="true"/>
<Button
android:id="#+id/year_minus"
android:layout_width="45dp"
android:layout_height="45dp"
android:background="#drawable/image_button_down_final"/>
</LinearLayout>
<LinearLayout
android:id="#+id/hour_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="#+id/hour_plus"
android:layout_width="45dp"
android:layout_height="45dp"
android:background="#drawable/image_button_up_final"/>
<EditText
android:id="#+id/hour_display"
android:layout_width="45dp"
android:layout_height="35dp"
android:background="#drawable/picker_middle"
android:gravity="center"
android:focusable="false"
android:inputType="number"
android:textColor="#000000"
android:singleLine="true">
</EditText>
<Button
android:id="#+id/hour_minus"
android:layout_width="45dp"
android:layout_height="45dp"
android:background="#drawable/image_button_down_final"/>
</LinearLayout>
<LinearLayout
android:id="#+id/min_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0.35dp"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="#+id/min_plus"
android:layout_width="45dp"
android:layout_height="45dp"
android:background="#drawable/image_button_up_final"/>
<EditText
android:id="#+id/min_display"
android:layout_width="45dp"
android:layout_height="35dp"
android:background="#drawable/picker_middle"
android:gravity="center"
android:focusable="false"
android:inputType="number"
android:textColor="#000000"
android:singleLine="true"/>
<Button
android:id="#+id/min_minus"
android:layout_width="45dp"
android:layout_height="45dp"
android:background="#drawable/image_button_down_final"/>
</LinearLayout>
<LinearLayout
android:id="#+id/meridiem_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="0.35dp"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
android:gravity="center"
android:orientation="vertical">
<ToggleButton
android:id="#+id/toggle_display"
style="#style/SpecialToggleButton"
android:layout_width="40dp"
android:layout_height="32dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="45dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
android:padding="5dp"
android:gravity="center"
android:textOn="#string/meridiem_AM"
android:textOff="#string/meridiem_PM"
android:checked="true"/>
<!-- android:checked="true" -->
</LinearLayout>
</LinearLayout>
</RelativeLayout>
The MainActivity class saved as MainActivity.java:
public class MainActivity extends Activity {
EditText editText;
Button button_click;
public static Activity me = null;
String meridiem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edittext1);
button_click = (Button)findViewById(R.id.button1);
button_click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view){
final Dialog mDateTimeDialog = new Dialog(MainActivity.this);
final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater().inflate(R.layout.date_time_dialog, null);
final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker);
// mDateTimePicker.setDateChangedListener();
((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDateTimePicker.clearFocus();
int hour = mDateTimePicker.getHour();
String result_string = mDateTimePicker.getMonth() +" "+ String.valueOf(mDateTimePicker.getDay()) + ", " + String.valueOf(mDateTimePicker.getYear())
+ " " +(mDateTimePicker.getHour()<=9? String.valueOf("0"+mDateTimePicker.getHour()) : String.valueOf(mDateTimePicker.getHour())) + ":" + (mDateTimePicker.getMinute()<=9?String.valueOf("0"+mDateTimePicker.getMinute()):String.valueOf(mDateTimePicker.getMinute()))+" "+mDateTimePicker.getMeridiem();
editText.setText(result_string);
mDateTimeDialog.dismiss();
}
});
// Cancel the dialog when the "Cancel" button is clicked
((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mDateTimeDialog.cancel();
}
});
// Reset Date and Time pickers when the "Reset" button is clicked
((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mDateTimePicker.reset();
}
});
// Setup TimePicker
// No title on the dialog window
mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set the dialog content view
mDateTimeDialog.setContentView(mDateTimeDialogView);
// Display the dialog
mDateTimeDialog.show();
}
});
}
}
What inflater does
It takes a xml layout as input (say) and converts it to View object.
Why needed
Let us think a scenario where we need to create a custom listview. Now each row should be custom. But how can we do it. Its not possible to assign a xml layout to a row of listview. So, we create a View object. Thus we can access the elements in it (textview,imageview etc) and also assign the object as row of listview
So, whenever we need to assign view type object somewhere and we have our custom xml design we just convert it to object by inflater and use it.
here is an example for geting a refrence for the root View of a layout ,
inflating it and using it with setContentView(View view)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater li=getLayoutInflater();
View rootView=li.inflate(R.layout.activity_main,null);
setContentView(rootView);
}
Layout inflater is a class that reads the xml appearance description and convert them into java based View objects.
LayoutInflater creates View objects based on layouts defined in XML. There are several different ways to use LayoutInflater, including creating custom Views, inflating Fragment views into Activity views, creating Dialogs, or simply inflating a layout file View into an Activity.
There are a lot of misconceptions about how the inflation process works. I think this comes from poor of the documentation for the inflate() method. If you want to learn about the inflate() method in detail, I wrote a blog post about it here:
https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/
my customize list hope it illustrate concept
public class second extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
// TextView textview=(TextView)findViewById(R.id.textView1);
// textview.setText(getIntent().getExtras().getString("value"));
setListAdapter(new MyAdapter(this,R.layout.list_item,R.id.textView1, getResources().getStringArray(R.array.counteries)));
}
private class MyAdapter extends ArrayAdapter<String>{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] objects) {
super(context, resource, textViewResourceId, objects);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.list_item,parent,false);
String[]items=getResources().getStringArray(R.array.counteries);
ImageView iv=(ImageView) row.findViewById(R.id.imageView1);
TextView tv=(TextView) row.findViewById(R.id.textView1);
tv.setText(items[position]);
if(items[position].equals("unitedstates")){
iv.setImageResource(R.drawable.usa);
}else if(items[position].equals("Russia")){
iv.setImageResource(R.drawable.russia);
}else if(items[position].equals("Japan")){
iv.setImageResource(R.drawable.japan);
}
// TODO Auto-generated method stub
return row;
}
}
}
LayoutInflater is a fundamental component in Android. You must use it all the time to turn xml files into view hierarchies.
Inflater actually some sort of convert to data, views, instances, to visible UI representation.. ..thus it make use of data feed into from maybe adapters, etc. programmatically. then integrating it with an xml you defined, that tells it how the data should be represented in UI

Categories

Resources