Home  >  Article  >  Java  >  Summary of the use of global variables and local variables in Android

Summary of the use of global variables and local variables in Android

伊谢尔伦
伊谢尔伦Original
2016-11-26 10:03:121214browse

Global variables, as the name implies, are variables that can be called in the entire class or in multiple functions. Also called external variables. Local variables are variables that can be accessed within a specific procedure or function. It is very easy to declare a variable, but when it comes to using it, it is not as simple as imagined. As for me, I often define global variables for use, but just because of this, I define global variables. It also spared a lot of twists and turns.

Summary of the use of global variables and local variables in Android

When using Adapter, usually the adapter is always used with listView, because a listView basically has a layout of listView's Items. The following scenario is: there will be one in each Item. ImageView, when I click on an item, I need to change the background color of the Item's ImageView or change it to another background image. One situation that may occur at this time is that if you click on the first item, you will find that the The picture of the third or second line has also changed. This is because you define a global variable. The code part is as follows:

public class  Adapter extends BaseAdapter {
private ImageView img;
 
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(R.layout.group_listview_item,null);
img = (ImageView) convertView.findViewById(R.id.logo);
 
return convertView;
 
} }

In the above part, ImageView is a global variable. At this time, we need to define ImageView as a local variable,

 public class  Adapter extends BaseAdapter {
 
 public View getView(int position, View convertView, ViewGroup parent) {
     convertView = mInflater.inflate(R.layout.group_listview_item,null);
     ImageView  img = (ImageView) convertView.findViewById(R.id.logo);
 
    return convertView;
 
} }

At this time, it represents the ImageView in each Item. Another situation is that when making a shopping cart, you can click the plus or minus icon to change the number of items in the shopping cart. When you define the quantity num, it must also be defined as a local variable. It would be better if you can use ViewHolder.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn