How to create another button in android dynamically - android

As the title states, I am looking to find out how to create a button dynamically when another button in another activity is pressed. This is being done with the Android SDK.
Basically, I have two activities, MainActivity and SecondaryActivity, within the SecondaryActivity you enter some information, title, text, id, so on and so forth. When you click the "Save" button it sends some, information to MainActivity(not the issue). As well as sending the information, I need to create an entirely new button within the MainActivity.
Any suggestions on how this should be accomplished?
Thanks.
Edit 1
public void CreateNewButton(View view)
{
LinearLayout lineLayout = (LinearLayout)findViewById(R.id.linear_layout);
TextView newTextView = new TextView(this);
int id = rand.nextInt(100);
int newId;
newTextView.setVisibility(View.VISIBLE);
newTextView.setId( R.id.new_button + id );
newTextView.setText("New Item");
newTextView.setTextSize(35);
newTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(getBaseContext(), SecondActivity.class);
startActivity(intent);
}
});
lineLayout.addView(newTextView);
}
This code generates the new TextView( Decided to change it up ) but now the issue I have, is newTextView.setText(); needs to get the text from the other activity
newTextView.setText(i.getData().toString());
putting this in the CreateNewButton(View view) methods causes an error since technically there is no data in the field that it is trying to grab from.
The problem at hand is I need to create the new TextView field WITH the name of the new account that has yet to be created. If that makes any sense.

I'm going to assume you want to add this button to a LinearLayout:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);
Button button = new Button(this);
button.setText("I'm a button!");
// add whatever other attributes you want to the button
linearLayout.addView(button);

Related

Trying to add buttons dynamically to Activity, Buttons aren't showing up until swapping activity

So right now I am trying to create a App for Android. I am already pretty far but I encountered one big issue. To understand it, I'll give some context on what the app does:
It's basically some app where a teacher can add schoolclasses, and in those school classes the teacher can add students.
When clicking the already existing button "add class", the user can input the name of the class, which then gets added as a button with the following method:
public void addButton(final String s) {
if(!existingButtons.contains(s)) {
Button button = new Button(getContext());
button.setText(s);
LinearLayout linearLayout = view.findViewById(R.id.linearlayout);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
//linearLayout.addView(button, params);
button.setLayoutParams(params);
linearLayout.addView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), SchoolClassActivity.class);
intent.putExtra("currentClassName", s);
Objects.requireNonNull(getActivity()).startActivity(intent);
}
});
existingButtons.add(s);
ClassesFragment test = new ClassesFragment();
}
}
Now the issue is as follows:
The button does get added upon confirming the input, but it only shows up, when I switch activity or swipe to the right most fragment (3 tabs with Viewpager, left is the page where you can add classes). I would like to know if there is any way to have the button show up, upon confirming the input, so without switching fragments/activities.
Thank you in advance

Android: Dynamically create image button with click event

I'm new to android and I require to have a list of image buttons in an activity which are created based on the data in a database. I haven't created anything like this in android before and so far I've been using HTML tables to show my data in a grid view. I'm not asking for any special code, I'm just clueless on how to implement this. I wanna know what the best approach is.
One problem I've faced is with the click events(in the way I've been doing them so far) which do not take in any EventArg, so I can't get the name of the button out of them.
If you're sure that the OnClickListener instance is applied to a Button, then you could just cast the received view to a Button and get the text:
public void onClick(View v) {
// 1) Possibly check for instance of first
Button b = (Button)v;
String buttonText = b.getText().toString();
}
// create the layout params that will be used to define how your button will be displayed
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// Create Button
final Button btn = new Button(this);
// Give button an ID
btn.setId(someinteger);
btn.setText("Add Text");
// set the layoutParams on the button
btn.setLayoutParams(params);

TableLayout, Different Button actions depending on data in TableRow

I have the following problem:
I have a TableLayout along with several TableRows, which are dynamically created.
On the right side of every row I create a button, which should call another activity.
Now I want to pass some information with intent.putExtra(). In this case I want so pass the row number, which is also the first information in the row.
Here is a picture of the current state:
This is how I create the buttons during run-time (in a loop):
Button b1 = new Button (this, null, android.R.attr.buttonStyleSmall);
b1.setId(1000+grButtonId);
b1.setText("Request GR");
b1.setLayoutParams(params);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// Some code, taken out for clarity
// See next code snippet
}
});
grButtonId++;
tr.addView(b1);
My idea so far is to use the id of the button (of course), and get the line number by the value of grButtonId.
Now comes my problem, let's have a detailed look at my onClickmethod:
#Override
public void onClick(View view) {
// finished is true, as soon as GRRequest has recieved the data
if(!finished & !dataRequested){
new GRRequest().execute(getIntent().getLongExtra("poNr", 0),(long)view.getId());
b1.setText("Show GR");
Log.d("DataList", detailList.toString());
dataRequested=true;
}
else{
if (dataRequested){
b1.setText("Show GR");
}
Intent intent = new Intent(DataTableCreater.this, GRTableCreater.class);
intent.putExtra("lineNr",view.getId());
intent.putExtra("dataList", detailList);
startActivity(intent);
}
}
When I request my data, the button I clicked on gets set to "Show GR" , as intended. The other buttons stay on "Request GR", this is also fine. But now I want these Buttons to Change to "Show GR" when tapped first and on second tap start the activity.
By now, the buttons change to "Show GR" and directly start the activity.
What would be a solution, to make this work?
Create a boolean Array clickedOnce[] = new boolean[grButtonId+1] one field for every Button.
Then have this
public void onClick(View view) {
if(!finished){
new GRRequest().execute(getIntent().getLongExtra("poNr", 0),(long)view.getId());
b1.setText("Show GR");
Log.d("DataList", detailList.toString());
clickedOnce[Integer.parseInt(String.valueOf(view.getId()).substring(1,4))]=true; //sets the clickedOnce for this button to true, substring(1,4) is needed to cancle the leading 1 from the id
}
else{
//Checks, if the button was clicked once
if (!clickedOnce[Integer.parseInt(String.valueOf(view.getId()).substring(1,4))]){
b1.setText("Show GR");
clickedOnce[Integer.parseInt(String.valueOf(view.getId()).substring(1,4))]=true;
}
else{
Intent intent = new Intent(DataTableCreater.this, GRTableCreater.class);
intent.putExtra("lineNr",view.getId());
intent.putExtra("dataList", detailList);
startActivity(intent);
}
}
}

Clear previous View and show new View on button click in the same Activity

I have created an activity with two buttons at the top. One button to show "SMS Logs" and second to show "Call Logs".
On clicking "SMS Logs" button, i am dynamically creating textviews and linear layout to show sms logs.
On Clicking "Call Logs", i am dynamically creating another textviews and linear layout to show call logs.
But the problem is that, once if we click "sms log" button and then we click "call log" button, the previously created linear layouts are not removed and the both(previous layouts and the current layouts) are shown simultaneously.
But i want that the previous layouts should be removed on clicking the second button.
Which function, should i use to remove the previous viewgroups or the layouts. Tell me if you need to read my class file.
Edit:
This is my Activity's code,
public class General extends Activity
{
String phone, message;
TextView Logs;
View layout, callLayout;
TextView data, callData, line, callLine;
Button smsLog, callLog;
LinearLayout ll, callll;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.general_main);
Logs = (TextView)findViewById(R.id.Logs);
layout = findViewById(R.id.layout);
callLayout = findViewById(R.id.layout);
smsLog = (Button)findViewById(R.id.smsLogs);
callLog = (Button)findViewById(R.id.callLogs);
smsLog.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
callLayout.setVisibility(View.GONE);
ll = new LinearLayout(getApplicationContext());
ll.setOrientation(LinearLayout.VERTICAL);
data = new TextView(getApplicationContext());
data.setText("First Line");
data.setTextColor(Color.YELLOW);
line = new TextView(getApplicationContext());
line.setText("Second Line");
((ViewGroup) ll).addView(data);
((ViewGroup) layout).addView(line);
((ViewGroup) layout).addView(ll);
}
});
callLog.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
layout.setVisibility(View.GONE);
callll = new LinearLayout(getApplicationContext());
callll.setOrientation(LinearLayout.VERTICAL);
callData = new TextView(getApplicationContext());
callLine = new TextView(getApplicationContext());
callData.setText("Third Line");
callLine.setText("Fourth Line");
((ViewGroup) callll).addView(callData);
((ViewGroup) callLayout).addView(callLine);
((ViewGroup) callLayout).addView(callll);
}
});
}
}
I have removed the extra code and made it simple to understand.
You can use FrameLayout to solve your problem. But I recommend you to use tabview.Here is the link that demonstrates how to develop tabbed applications.Good Luck
You could implement a TabView.
But having your current setup just change the visibility of one view group to GONE and the other to VISIBLE.
GONE will make the view invisible and it won't take up any space anymore.
EDIT based on the code added to the question
Both your layout and callLayout are using the same XML view. Implement 2 identical views in your xml and keep one visible and one gone. This way when you set layout or callLayout visibility to GONE they are 2 different ones not the same. So your onClick() will have something like this:
for smsLog:
layout.setVisibility(View.GONE);
callLayout.setVisibility(View.VISIBLE);
for callLog:
callLayout.setVisibility(View.GONE);
callLayout.setVisibility(View.VISIBLE);

Creating texts and buttons with listeners successively?

I will try to explain my problem. The code below as you can see try to add some textviews and buttons as the array get from another class.
public class Breakfast extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
sv.addView(ll);
if (extras != null) {
String food[]=extras.getStringArray("food");
String foodCateg[]=extras.getStringArray("foodCateg");
int K=0;
for (int i = 0; i < food.length/3; i++) {
TextView foodDay = new TextView(this);
foodDay.setText("Day "+ (i+1));
ll.addView(foodDay);
for (int j=K;j<K+3;j++){
Button contfood= new Button(this);
contfood.setText(food[j]);
ll.addView(contfood);
}
K=K+3;
}
this.setContentView(sv);
}
}
My question is how can I know what of this buttons are clicked on the screen?? Because in the case of what one of them are clicked (getting the text that have write before), I will do something or other thing.
ahhhhhhhhhhhhhhhhh yes I know how to do a ListActivity. But first I think in doing by hand because I don´t think how to symplify this...
Thank you for the answers of trying to build with everything a listview and then the method OnListItemClick, but I think that isn´t the solution.
I said that because when I insert the day for example (I Don´t put hear all the code...) but I do .setgravity .setSize .setbackgroundResource etc. And with the food for that day I use a diferent .setgravity and more parameters. So I think that with listview everything would have the same specifications... and that´s what I don´t like.
so... to know what button is pressed on the screen?
You could use contfood.setId(i) and work your way from there.
But what you are doing looks like you really want to create a ListActivity and use it's OnItemClickListener.
What you should do is put an id to each button "contfood". And then when you click on a button retrieve the id back to do the action you want.
Another way is to create the button and attach the method public void onClick(View view):
for (int j=K;j<K+3;j++){
Button contfood= new Button(this);
contfood.setText(food[j]);
ll.addView(contfood);
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), xxx.class);
startActivityForResult(myIntent, 0);
}
}
and add the parameters within the method.

Categories

Resources