Using findViewById is more efficient

I am currently using the following code and wondering if there is a more efficient way to do this with a function?

showDisplay = (LinearLayout)findViewById(R.id.display1);
if (isA)
{ 
{ showDisplay.setVisibility(0);}
else
{ showDisplay.setVisibility(8); }


showDisplay = (LinearLayout)findViewById(R.id.display2);
if (isB)
{ showDisplay.setVisibility(0);}
else
{ showDisplay.setVisibility(8); }

showDisplay = (LinearLayout)findViewById(R.id.display3);
if (isC)
{ showDisplay.setVisibility(0);}
else
{ showDisplay.setVisibility(8); }
+3
source share
3 answers

I would do it like this:

// Do this in your onCreate method and store the references as class member variables
showDisplay1 = (LinearLayout)findViewById(R.id.display1);
showDisplay2 = (LinearLayout)findViewById(R.id.display2);
showDisplay3 = (LinearLayout)findViewById(R.id.display3);

// Do this somehwere in your code
showDisplay1.setVisibility(isA?View.VISIBLE:View.GONE);
showDisplay2.setVisibility(isB?View.VISIBLE:View.GONE);
showDisplay3.setVisibility(isC?View.VISIBLE:View.GONE);

For efficiency, it’s important to store links as member variables, since calling findViewById is quite expensive (compared to accessing a member variable) because you only need to call it once when the application is created (this also takes into account orientation changes, since the action is destroyed and recreated again).

. if- , .

myFunction((expression)?if_value:else_value);

int value = 0;
if(expression) {
    value = if_value;
} else {
    value = else_value;
}
myFunction(value);

( ), , . .

myFunction((someVariable>3)?View.VISIBLE:View.GONE);

Edit2:

int value = 0;
if(somveVariable > 3) {
    value = View.VISIBLE;
} else {
    value = View.GONE;
}
myFunction(value);

, , , .

Edit: Oh btw: , 0 8 View.setVisibility(...). , - . View.VISIBLE public static final int, , View.VISIBLE 0. , 0, , - , SDK, , 0 8 !

+1

, , .. .

setChildVisibility(R.id.display1, isA);
setChildVisibility(R.id.display2, isB);
setChildVisibility(R.id.display3, isC);

:

protected void setChildVisibility(int id, boolean visible) {
    View view = findViewById(id);
    if (view != null) {
        view.setVisibility(visible?View.VISIBLE:View.GONE);
    }
}
+2

I would do something like this:

public void showDisplay(int displayId, boolean show) {
    if (show) {
      ((LinearLayout)findViewById(displayId)).setVisibility(0);
    }
    else {
      ((LinearLayout)findViewById(displayId)).setVisibility(8);
    }
}

showDisplay(R.id.display1, isA);
showDisplay(R.id.display2, isB);
showDisplay(R.id.display3, isC);

The code becomes more readable, no more efficient.

+1
source

Source: https://habr.com/ru/post/1777059/


All Articles