Views don`t appear on the screen - android

Clicking on the button creates a view. Then I add this view to layout, but it doesn`t appear on the screen.
private ArrayList<EditText> viewArray = new ArrayList<EditText>();
String str = "text";
LinearLayout linLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
linLayout = new LinearLayout(this);
linLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams linLayoutParam = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
setContentView(linLayout, linLayoutParam);
Button btnAdd = new Button(this);
btnAdd.setText("Add EditText");
LinearLayout.LayoutParams vParams = new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linLayout.addView(btnAdd, vParams);
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
viewArray.add( new EditText(getApplicationContext()) );
viewArray.get(viewArray.size()-1).setText(str + viewArray.size());
viewArray.get(viewArray.size()-1).setId(viewArray.size());
LinearLayout.LayoutParams vParams2 = new LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linLayout.addView(viewArray.get(viewArray.size()-1), vParams2);
Toast.makeText(getApplicationContext(),"size: " + viewArray.size(), Toast.LENGTH_LONG).show();
}
});
}
}
The application is not closed, there is no error, the view simply does not appear

Related

Cannot add View To the relative Layout

i am making a activity that takes int position from another activity to get a class formula that have the formula, some variables and the title , so i want to create the activity by taking that formula and setting the title , making some edit text views for variables so that the user add values for them and then i return the result by a dialogue the problem is that the views that i add programitically are not displayed, plz help
public class DisplayFomula extends AppCompatActivity {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_fomula);
DB db = new DB(this);
Bundle extra = getIntent().getExtras();
int pos = extra.getInt("id");
final Formula form = db.getFormula(pos);
RelativeLayout layout=new RelativeLayout(this);
TextView tw1 =(TextView) findViewById(R.id.textView11);
tw1.setText(form.title);
final String[] var = form.var;
int i=0;
final EditText[] ed = new EditText[50];
for(;i<var.length;i++){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
ed[i]= new EditText(this);
ed[i].setId(i);
ed[i].setHint(var[i]);
ed[i].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
ed[i].setLayoutParams(params);
if(i!=0) params.addRule(RelativeLayout.BELOW,ed[i-1].getId());
else params.addRule(RelativeLayout.BELOW,R.id.textView11);
layout.addView(ed[i],params);}
Button btn = new Button(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
btn.setId(i);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
btn.setLayoutParams(params);
btn.setText("Go!");
layout.addView(btn,params);
params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
addContentView(layout,params);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double[] varin=new double[var.length];
for(int i =0;i<var.length;i++){
Double dbl = Double.parseDouble(ed[i].getText().toString());
varin[i]=dbl;
}
String res = String.valueOf(form.result(varin));
}
});
}
}
You are adding all the views to RelativeLayout layout. But i think u have'nt add layout view to any activity_display_fomula view.
get a viewgroup from activity_display_fomula and add your RelativeLayout layout to it..

Adding onClick to buttons that are created programmatically

A TextView and Button are programmatically created and added to a pre-existing vertical layout making it look like a vertical list of views. These views are only created based off the user entering data into an edittext and that data being saved into an ArrayList.
How can I add an onClick function to my 'trash' buttons that are programmatically created that would allow them to remove the view they are associated with.
public static ArrayList<String> deckNameArray = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.mainLayout);
for(int i = 0; i < deckNameArray.size(); i++)
{
LinearLayout layout = new LinearLayout(this);
if ((i % 2) == 0) {
layout.setBackgroundColor(Color.CYAN);
} else {
layout.setBackgroundColor(Color.WHITE);
}
layout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(layoutParams);
layout.setPadding(10, 5, 10, 5);
layout.setWeightSum(5);
mainLayout.addView(layout);
LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 4f);
TextView deckName = new TextView(this);
deckName.setText(deckNameArray.get(i));
deckName.setTextColor(Color.BLACK);
deckName.setTextSize(18);
deckName.setGravity(Gravity.CENTER_VERTICAL);
deckName.setLayoutParams(textViewParams);
layout.addView(deckName);
LinearLayout.LayoutParams imageButtonParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, 1f);
ImageButton remove = new ImageButton(this);
remove.setImageResource(R.mipmap.trash);
if ((i % 2) == 0) {
remove.setBackgroundColor(Color.CYAN);
} else {
remove.setBackgroundColor(Color.WHITE);
}
remove.setLayoutParams(imageButtonParams);
layout.addView(remove);
}
remove.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
See http://developer.android.com/reference/android/widget/Button.html
You can set a click listener on any View, using code similar to the sample below:
View myView;
myView.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
// TODO your logic here
}
}

how do i align image view left of button programically?

how do i align image view left of button programically? in this code below i genrate button and image view programicallybut image view is show below of buton how do i set right of button image view??
public class MainActivity1 extends Activity {
public static Bitmap yourSelectedImage = null;
ImageView imageView1;
ContentValues newCon = new ContentValues();
public static byte[] blob = null;
public static long reqId;
int i;
LinearLayout btnLO;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
btnLO = new LinearLayout(MainActivity1.this);
LinearLayout.LayoutParams paramsLO = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// button margins
paramsLO.setMargins(0, 0, 0, 0);
// button height/width *pixels*
paramsLO.height = 75;
paramsLO.width = 75;
btnLO.setOrientation(LinearLayout.VERTICAL);
btnLO.setBackgroundColor(5); // not working correctly
//buttons
for (i =0;i <j;i++)
{
final Button b1 = new Button(MainActivity1.this);
final ImageView imageView = new ImageView(MainActivity1.this);
b1.setText(reqdata[i].getSpinnerText());
b1.setTag(reqdata[i].getValue());
btnLO.addView(b1, paramsLO);
btnLO.addView(imageView, paramsLO);
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
reqId =
Long.valueOf(reqdata[btnLO.indexOfChild(b1)/2].getValue()).longValue();
Toast.makeText(MainActivity1.this, reqId+"",
Toast.LENGTH_SHORT).show();
}
final Button b2 = new Button(MainActivity1.this);
b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
}
});
btnLO.addView(b2, paramsLO);
btnLO.setGravity(Gravity.LEFT | Gravity.CENTER_HORIZONTAL);
this.addContentView(btnLO, new LayoutParams());
}
LinearLayout li=new LinearLayout(this);
li.setOrientation(LinearLayout.HORIZONTAL);
final Button b1 = new Button(MainActivity1.this);
final ImageView imageView = new ImageView(MainActivity1.this);
b1.setText(reqdata[i].getSpinnerText());
b1.setTag(reqdata[i].getValue());
li.addView(b1, paramsLO);
li.addView(imageView, paramsLO);
btnLO.addView(li);
ScrollView sc=new ScrollView(this);
sc.addView(btnLO);
remember this must be done outside for loop.
this is how you need to add button and image to your layout inside for loop

refresh activity with dynamic content

I have an activity with some dynamic content.
For each item of an array, there is a different content (number of textViews, checkboxes, ..)
The user clicks on a "save" button and then the screen has to refresh itself to display the content of the next item.
I was wondering if it was a good practice to reload my activity like this :
Intent refresh = new Intent(this, conflictActivity.class);
startActivity(refresh)
finish()
instead of removing all the views in my layouts, etc ...
I think it's easier to reload it.
Is there another way to do it ?
EDIT : added Code.
public class ConflicFieldTest extends Activity {
private int nbField;
private int nbChecked;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.conflict);
final Button saveButton = (Button) findViewById(R.id.save);
final LinearLayout leftLayout = (LinearLayout) findViewById(R.id.leftLayout);
final LinearLayout rightLayout = (LinearLayout) findViewById(R.id.rightLayout);
final TextView fieldName = new TextView(this);
final LinearLayout editLayoutRight = new LinearLayout(this);
final LinearLayout editLayoutLeft = new LinearLayout(this);
final LinearLayout fieldRight = new LinearLayout(this);
final LinearLayout fieldLeft = new LinearLayout(this);
final ArrayList<String> allIdInConflict = getAllIdInConflict();
for (int i = 0; i < allIdInConflict.size(); i++) {
new AccountSyncTask() {
#Override
public void onPostExecute(
final ArrayList<ArrayList<String>> result) {
nbField = 0;
nbChecked = 0;
final Map<String, Object> fieldsInConflict = conflict
.conflictWithFields(memoAccountMap,
serverAccountMap, modifiedAccountMap);
for (Iterator<Map.Entry<String, Object>> field = fieldsInConflict
.entrySet().iterator(); field.hasNext();) {
final Map.Entry<String, Object> entry = field.next();
fieldName.setText(entry.getKey() + " : ");
final EditText[] editTextArrayRight = new EditText[fieldsInConflict
.size()];
final EditText[] editTextArrayLeft = new EditText[fieldsInConflict
.size()];
final CheckBox[] checkboxRight = new CheckBox[fieldsInConflict
.size()];
final CheckBox[] checkboxLeft = new CheckBox[fieldsInConflict
.size()];
checkboxRight[nbField] = new CheckBox(
ConflicFieldTest.this);
checkboxLeft[nbField] = new CheckBox(
ConflicFieldTest.this);
editLayoutLeft.setGravity(Gravity.CENTER_HORIZONTAL);
editLayoutRight.setGravity(Gravity.CENTER_HORIZONTAL);
fieldRight.setGravity(Gravity.CENTER_HORIZONTAL);
fieldLeft.setGravity(Gravity.CENTER_HORIZONTAL);
editLayoutRight.setOrientation(LinearLayout.HORIZONTAL);
fieldRight.setOrientation(LinearLayout.VERTICAL);
fieldLeft.setOrientation(LinearLayout.VERTICAL);
rightLayout
.addView(
editLayoutRight,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
leftLayout
.addView(
editLayoutLeft,
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editTextArrayRight[nbField] = new EditText(
ConflicFieldTest.this);
editTextArrayRight[nbField].setText((String) entry
.getValue());
editTextArrayRight[nbField].setTextColor(Color.BLACK);
editTextArrayRight[nbField].setFocusable(false);
editTextArrayRight[nbField].setClickable(false);
editTextArrayRight[nbField].setWidth(180);
editTextArrayRight[nbField].setPadding(0, 10, 0, 0);
editTextArrayLeft[nbField] = new EditText(
ConflicFieldTest.this);
editTextArrayLeft[nbField]
.setText((String) serverAccountMap.get(entry
.getKey()));
editTextArrayLeft[nbField].setTextColor(Color.BLACK);
editTextArrayLeft[nbField].setFocusable(false);
editTextArrayLeft[nbField].setClickable(false);
editTextArrayLeft[nbField].setWidth(180);
editTextArrayLeft[nbField].setPadding(0, 10, 0, 0);
final int i1 = nbField;
checkboxLeft[i1]
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
checkboxRight[i1]
.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
editLayoutLeft.addView(fieldName);
editLayoutRight
.addView(
editTextArrayRight[nbField],
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editLayoutLeft
.addView(
editTextArrayLeft[nbField],
new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
editLayoutRight.addView(checkboxRight[nbField]);
editLayoutLeft.addView(checkboxLeft[nbField]);
nbField++;
}
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//save data & update UI
}
}
.execute(appState.getSessionName(), id, "getObjectOnServer");
}
}
Sorry for the code, it is a litle bit dirty (i have deleted some parts), i am reworking it.
int flag = 0;
public void updateUI() {
if(flag == 0) {
//your normal codes...
} else {
//display view with user given data
}
}
Call this function in oncreate. At first flag will be set to zero. When u enter the data in textview and tick checkboxes, update the flag with some value. Then on save Button click call this function again. Now flag is set. So it will display the updated UI.
I think this will give u an idea..

How to add a button dynamically in Android?

How to add a button dynamically in Android?
Button myButton = new Button(this);
myButton.setText("Push Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
Have a look to this example
try this:
for (int i = 1; i <= 20; i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setId(i);
final int id_ = btn.getId();
btn.setText("button " + id_);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
linear.addView(btn, params);
btn1 = ((Button) findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
}
Try this:
LinearLayout ll = (LinearLayout)findViewById(R.id.layout);
Button btn = new Button(this);
btn.setText("Manual Add");
btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(btn);
for (int k = 1; k < 100; k++) {
TableRow row = new TableRow(this);
innerloop:
for (int l = 1; l < 4; l++) {
btn = new Button(this);
TableRow.LayoutParams tr = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.setWeightSum(12.0f);
tr.weight = 0;
btn.setLayoutParams(tr);
btn.setTextColor(a);
btn.setHeight(150);
btn.setWidth(150);
btn.setId(idb);
btn.setText("Button " + idb);
row.addView(btn);
}
}
try this
private void createLayoutDynamically(int n) {
for (int i = 0; i < n; i++) {
Button myButton = new Button(this);
myButton.setText("Button :"+i);
myButton.setId(i);
final int id_ = myButton.getId();
LinearLayout layout = (LinearLayout) findViewById(R.id.myDynamicLayout);
layout.addView(myButton);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(DynamicLayout.this,
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
}
Try this code
Button btn=new Button(this);
btn.setId(btn);
btn.setBackgroundResource(R.drawable.image);
btn.setMinimumHeight(150);
btn.setMinimumWidth(150);
Relativelayout.addView(btn);
Check this up.
LinearLayout ll_Main = new LinearLayout(getActivity());
LinearLayout ll_Row01 = new LinearLayout(getActivity());
LinearLayout ll_Row02 = new LinearLayout(getActivity());
ll_Main.setOrientation(LinearLayout.VERTICAL);
ll_Row01.setOrientation(LinearLayout.HORIZONTAL);
ll_Row02.setOrientation(LinearLayout.HORIZONTAL);
final Button button01 = new Button(getActivity());
final Button button02 = new Button(getActivity());
final Button button03 = new Button(getActivity());
final Button button04 = new Button(getActivity());
ll_Row01.addView(button01);
ll_Row01.addView(button02);
ll_Row02.addView(button03);
ll_Row02.addView(button04);
ll_Main.addView(ll_Row01);
ll_Main.addView(ll_Row02);
button04.setVisibility(View.INVISIBLE);
button04.setVisibility(View.VISIBLE);
Button btn = new Button(this);
btn.setText("Submit");
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams buttonlayout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.addView(btn, buttonlayout);
Try this code. It will work fine..
public class DynamicViewsActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_dynamic_views);
ScrollView scrl=new ScrollView(this);
final LinearLayout ll=new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(100, 500, 100, 200);
scrl.addView(ll);
Button add_btn=new Button(this);
add_btn.setText("Click Here");
ll.addView(add_btn, layoutParams);
final Context context = this;
add_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, App2Activity.class);
startActivity(intent);
}
});
this.setContentView(scrl);
}
}
Try following code.
LinearLayout layout = (LinearLayout) findViewById(R.id.llayout);
layout.setOrientation(LinearLayout.VERTICAL);
Button btn = new Button(this);
btn.setText("Button1");
layout.add(btn);
btn = new Button(this);
btn.setText(Button2);
layout.add(btn);
like this you add Buttons as per your requirements.
public void add_btn() {
lin_btn.setWeightSum(3f);
for (int j = 0; j < 3; j++) {
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params1.setMargins(10, 0, 0, 10);
params1.weight = 1.0f;
LinearLayout ll;
ll = new LinearLayout(this);
ll.setGravity(Gravity.CENTER_VERTICAL);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setLayoutParams(params1);
final Button btn;
btn = new Button(DynamicActivity.this);
btn.setText("A"+(j+1));
btn.setTextSize(15);
btn.setId(j);
btn.setPadding(10, 8, 10, 10);
ll.addView(btn);
lin_btn.addView(ll);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v.getId()==0)
{
txt_text.setText("Hii");
}else if(v.getId()==1)
{
txt_text.setText("hello");
}else if(v.getId()==2)
{
txt_text.setText("how r u");
}
}
});
}
}
Actually I add to the xml layout file anything that could be used! Then from the source code of the specific Activity I get the object by its id and I "play" with the visibility method.
Here is an example:
((Spinner)findViewById(R.id.email_spinner)).setVisibility(View.GONE);
I've used this (or very similar) code to add several TextViews to a LinearLayout:
// Quick & dirty pre-made list of text labels...
String names[] = {"alpha", "beta", "gamma", "delta", "epsilon"};
int namesLength = 5;
// Create a LayoutParams...
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.FILL_PARENT);
// Get existing UI containers...
LinearLayout nameButtons = (LinearLayout) view.findViewById(R.id.name_buttons);
TextView label = (TextView) view.findViewById(R.id.master_label);
TextView tv;
for (int i = 0; i < namesLength; i++) {
// Grab the name for this "button"
final String name = names[i];
tv = new TextView(context);
tv.setText(name);
// TextViews CAN have OnClickListeners
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
label.setText("Clicked button for " + name);
}
});
nameButtons.addView(tv, params);
}
The main difference between this and dicklaw795's code is it doesn't set() and re-get() the ID for each TextView--I found it unnecessary, although I may need it to later identify each button in a common handler routine (e.g. one called by onClick() for each TextView).
Button myButton = new Button(this);
myButton.setId(123);
myButton.setText("Push Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(DynamicLayout.this,
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
If you want to add dynamically buttons try this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
for (int i = 1; i <= 5; i++) {
LinearLayout layout = (LinearLayout) findViewById(R.id.myLinearLayout);
layout.setOrientation(LinearLayout.VERTICAL);
Button btn = new Button(this);
btn.setText(" ");
layout.addView(btn);
}
}
You could create a base layout for your button and dynamically change only what is specific, like this project I made to run different exercises from a Material Design course I'm taking:
In this example, I use a preconfigured AppCompatButton:
layout_base_button.xml
<android.support.v7.widget.AppCompatButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/btn_base"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
style="#style/RaisedButton"
>
</android.support.v7.widget.AppCompatButton>
<style name="RaisedButton" parent="Widget.AppCompat.Button.Colored">
<item name="android:textSize">11sp</item>
<item name="android:textStyle">bold</item>
</style>
And in the MainActivity I created some instances and changed what I need, like the button text and onClick event:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="udemy.android.materialdesign.MainActivity">
<LinearLayout
android:id="#+id/base_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</ScrollView>
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout baseLayout = findViewById(R.id.base_layout);
baseLayout.addView(createButton("TextFields", baseLayout,
view -> startActivity(createIntent(TextFieldsActivity.class))
));
baseLayout.addView(createButton("Buttons", baseLayout,
view -> startActivity(createIntent(ButtonsActivity.class))
));
baseLayout.addView(createButton("Toolbar", baseLayout,
view -> startActivity(createIntent(ToolbarActivity.class))
));
}
private View createButton(String text, LinearLayout baseLayout, View.OnClickListener onClickEvent) {
View inflated = LayoutInflater.from(this).inflate(R.layout.layout_base_button, baseLayout, false);
AppCompatButton btnBase = inflated.findViewById(R.id.btn_base);
btnBase.setText(text);
btnBase.setOnClickListener(onClickEvent);
return btnBase;
}
private Intent createIntent(Class<?> cls) {
return new Intent(this, cls);
}
}
Sorry for being late...
I needed to create buttons even more dynamically, not just in runtime but by pressing another button. So clicking this button will dynamically create more buttons under it. I recommend having a ScrollView on the activity or limit the number of clicks - so no buttons go offscreen.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="675dp">
<LinearLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/newItemButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout); //Screen layout
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final Button newItemButton = findViewById(R.id.newItemButton);
newItemButton.setText("Create new button");
newItemButton.setOnClickListener(new View.OnClickListener() {
int pressCount = 1; //Count how many times button was pressed
public void onClick(View v) {
newItemButton.setText("Button Clicked: "+pressCount);
createButton(pressCount, params, ll); //Click to create new button
pressCount++;
}
});
} //end of onCreate
public void createButton(int id, LinearLayout.LayoutParams inputParams, LinearLayout inputLL) {
Button outButton = new Button(this);
outButton.setId(id);
final int id_ = outButton.getId();
outButton.setText("Button " + id_);
inputLL.addView(outButton, inputParams);
}
}//end of AppCompatActivity
This will give you an activity with a button.
When you click on that button, you spawn a new button underneath it.
If you spawn so many that they do not fit on the screen, the scrollView will take care of that.
In mainactivity.xml write:
<Button
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:visibility="invisible"/>
In main.java write:
Button buttonSearch;
buttonSearch = (Button)findViewById(R.id.search);
buttonSearch.setVisibility(View.VISIBLE);

Categories

Resources