About how to add listener methods to controls in ListView

                    Regarding ListView, it is a relatively common control in android. In ListView, we usually need a template. This template does not refer to the module, but to configure what is displayed in the ListView. When I was working on a project today, I found that I wanted to add an ImageView monitoring method. , found that it collapsed, maybe it's been a long time that the ListView has not been moved and has forgotten that it cannot directly call the controls of other xml files in the xml file of the main UI, even if the ListView uses this xml file.

[Error example]:

Directly calling the ImageView control is a ListView control. It is called directly in the non-mastering View java class file, and it crashes directly. I didn't know this problem before.

msg=(ImageView).findViewById(R.id.msg);
			    msg.setOnClickListener(new OnClickListener() {
				
					
					}
				});

 【How to get】:

public class CallListen implements OnItemClickListener{

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                          msg=(ImageView)view.findViewById(R.id.msg);
			    msg.setOnClickListener(new OnClickListener() {
				
					@Override
					public void onClick(View v) {
}
}
}

}

 Use the monitoring method of the control in the ListView monitoring method. The most important thing is to click on the ListView to get the parent class View of all the controls in it.

In this case, we can get our control through msg=(ImageView)view.findViewById(R.id.msg);, the view inside is very important, and this involves a knowledge, if my activity setcontentview is not What if I currently want to use the control's View?

The function of LayoutInflater is to instantiate the xml layout file of the layout as a View class object.

There are three ways to get LayoutInflater :

 

?
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main, null );
 
LayoutInflater inflater = LayoutInflater.from(context); (该方法实质就是第一种方法,可参考源代码)
View layout = inflater.inflate(R.layout.main, null );
 
LayoutInflater inflater = getLayoutInflater();(在Activity中可以使用,实际上是View子类下window的一个函数)
View layout = inflater.inflate(R.layout.main, null );

At this point you may be wondering:

setContentView 和Inflate

Difference: Once
setContentView()
is called , the layout will display the UI immediately ; while inflate will only form the Layout into an object implemented with the view class, and then use setContentView(view) to display it when necessary. Generally , the interface is displayed through setContentView() in the activity , but if how to set the layout of the control in the non- activity , this requires LayoutInflater to dynamically load.

 这一节课内容很重要, 因为很多时候遇到的坑都是没看这篇文章

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326103232&siteId=291194637