Created
September 7, 2017 10:26
-
-
Save Binary-Finery/39851f98563aeeaa8bb56bedff3ab535 to your computer and use it in GitHub Desktop.
Simple example of creating UI dynamically in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.Bundle; | |
import android.support.v7.app.AppCompatActivity; | |
import android.text.TextUtils; | |
import android.view.View; | |
import android.widget.Button; | |
import android.widget.EditText; | |
import android.widget.LinearLayout; | |
import android.widget.TextView; | |
import android.widget.Toast; | |
import java.util.Locale; | |
public class BuildUIDynamically extends AppCompatActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
LinearLayout rootLayout = new LinearLayout(this); | |
rootLayout.setOrientation(LinearLayout.VERTICAL); | |
final EditText et1 = new EditText(this); | |
et1.setHint("Enter percent"); | |
final EditText et2 = new EditText(this); | |
et2.setHint("Enter number"); | |
Button btnConfirm = new Button(this); | |
btnConfirm.setText("Calculate"); | |
final TextView tvOutput = new TextView(this); | |
rootLayout.addView(et1); | |
rootLayout.addView(et2); | |
rootLayout.addView(btnConfirm); | |
rootLayout.addView(tvOutput); | |
setContentView(rootLayout); | |
rootLayout.setPadding(16, 16, 16, 16); | |
et1.setInputType(2); | |
et2.setInputType(2); | |
btnConfirm.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
String p = extract(et2), n = extract(et1); | |
if (TextUtils.isEmpty(p) || TextUtils.isEmpty(n)) | |
Toast.makeText(getApplicationContext(), "missing info!", Toast.LENGTH_SHORT).show(); | |
else | |
tvOutput.setText(calculate(Double.parseDouble(p), Double.parseDouble(n))); | |
} | |
}); | |
} | |
private String calculate(double... d) { | |
return String.format(Locale.getDefault(), "Answer: %.2f", (d[0] / 100) * d[1]); | |
} | |
public String extract(EditText et) { | |
return et.getText().toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment