Reputation: 5615
I've a piece of code that is called at the start of onCreate()
(5th line after super.onCreate
) in my Main Activity that I suspect is slowing down the start (and debugging).
It's a loop used to assign 10 buttons along with Click listeners for each of them. Here's the snippet-
//expostate is a boolean and is always false at start of activity
//checkLength(Screen) will always return true at start of activity
//expression is of String data type
//Screen is a TextView
for(int i=0; i<10; i++){
String btnid = "btn" + i;
int resourceid = getResources().getIdentifier(btnid, "id", getPackageName());
numbuttons[i] = findViewById(resourceid);
final String value = String.valueOf(i);
numbuttons[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (checkLength(Screen) && !expostate) {
if (expression.equals("0")) {
expression = "";
Screen.setText("");
}
Screen.append(value);
expression += value;
presentop = false;
}
else if (checkLength(Screen) && expostate) {
if (expression.equals("0")) {
expression = "";
Screen.setText("");
}
Screen.append(getSuperscript(value));
expression += value;
presentop = false;
}
}
});
}
Is there a better/faster way to achieve this same task?
Upvotes: 0
Views: 60
Reputation: 5615
So, I found out that a less janky way to do this is assigning android:onClick
to each of the 10 buttons along with an android:tag
to extract value.
The Code:-
public void onNumpress(View v){
buttonFlash((Button) v);
String value = getResources().getResourceEntryName(v.getId()).replace("btn", "");
if (expression.equals("0")) {
expression = "";
Screen.setText("");
}
if (checkLength(Screen)) Screen.append(expostate ? getSuperscript(value) : value);
expression += value;
presentop = false;
}
The xml layout of one of the buttons:-
<Button
android:id="@+id/btn0"
android:layout_width="78dp"
android:layout_height="85dp"
android:layout_marginBottom="8dp"
android:background="@color/colorPrimary"
android:text="@string/btn0"
android:textColor="@color/colorSecondary"
android:textSize="24sp"
android:onClick="onNumpress"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toEndOf="@+id/btnans" />
Upvotes: 0
Reputation: 164139
An improvement I would suggest is for the onClick()
method.
Your logic can be written like this:
public void onClick(View view) {
if (expression.equals("0")) {
expression = "";
Screen.setText("");
}
if (checkLength(Screen)) Screen.append(expostate ? getSuperscript(value) : value);
expression += value;
presentop = false;
}
Upvotes: 1
Reputation: 3481
If the ID's of the buttons are known at runtime you would be better off just creating an array with the ID's instead of doing the getResources()-call.
Upvotes: 0