Android: dynamic text creation? - java

Let's say I have some strings in Java that I've retrieved from a web script. It doesn't matter really, they're just strings stored in variables.
Now my question is how to dynamically append them to the application (to show the user) and possibly style their position, from Java.
To draw an analogy, I want to do something similar to the following in JavaScript:
var text = document.createElement('div');
text.appendChild(document.createTextNode("some string"));
text.style.position = "whatever";
// etc, more styling
theDiv.appendChild(text); // add this new thing of text I created to the main application for the users to see
I've looked into the TextView, and I don't seem to be using it properly (I don't understand the constructor I guess?). What I want to try right now is to have the user press a button in my application and then have some text dynamically generated. Here's what I've been trying:
search_button = (Button) findViewById (R.id.backSearchButton);
search_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String test = new String("testing!");
TextView test2 = new TextView(this); //constructor is wrong, this line gives me an error
test2.setText(test);
setContentView(test2);
}
});
As you can probably tell, I don't come from much of a Java background. I'm just trying to draw parallels to stuff I would want to do for a web app.
Thanks for the help.

Try:
TextView test2 = new TextView(ParentActivity.this);
replace "ParentActivity" with the name of your activity.

your this pointer is a reference to the OnClickListener that you have anonymously created. You need a pointer to the containing Activity.
You would probably be better constructing your text view in the onCreate of your activity and just setting the text from your onClick method

I'm new to Java and Android, myself. But I'll give your question a try.
You have to decide if you want to create the TextView in XML or dynamically in Java. I think creating it in XML in the layout creator is better.
I don't think you should be using setContentView(test2).
If you create a TextView dynamically, I don't think you need to put anything in its constructor. But you do have to add the TextView to the parent view. In other words, let's say you have a LinearLayout somewhere in your layout. You have to do: linearLayout1.add(myTextView) or something.
The rest of your code seems fine. But then again, I'm still new to this, myself. Let me know how helpful this answer is, I'll try Googling for more help if it's not enough.

Related

Click listener for multiple buttons ive created dynamically Android Studio

Okay so I am making an android application, and I have a list of goals let's say to make it easy to explain. A goal consists of a string. This data will be coming from a database so in the future, the length of the list may be slightly longer or slightly shorter. Each goal is placed inside the text of a button.
I have made this loop to create the buttons at run time due to the changing length of the list depending on whats happened before and this all works perfectly, i can create the buttons and they are placed where i want etc. This is the code I used to do this.
for (int i = 0; i < goals.size(); i++){
buttons[i] = new Button(this.getContext());
buttons[i].setLayoutParams(params);
buttons[i].setPadding(0,150,0,150);
buttons[i].setGravity(Gravity.CENTER);
buttons[i].setText(goals.get(i));
buttons[i].setBackgroundResource(R.drawable.btn_back);
buttons[i].setTextSize(30);
buttons[i].setTransformationMethod(null);
linear.addView(buttons[i]);
}
Now my issue is I want the click of each button to do a slightly different thing - depending on the goal ie, the text of the button. I really am struggling with setting up the click event so that different buttons will do different things even tho i have created all of them dynamically.
I can give more detail into the setup I am in in the android studio, but I feel I've given enough insight into my issue.
I appreciate any help.
My best guess is that if you already know what the function of each button should be according to the text, couldn't you just take the text of the button and then use it in switch (or something else) to get specific functionality like:
buttons[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
//Put whatever is common between buttons outside of the switch
switch(((Button)view).getText().toString()){
//And then just assign a case for whatever functionality you need specifically for each goal
}
}
});

How to use dynamic buttons with array data

I am still working on my first android app and hope you can help me once more. I use the YouTube API to get all the content from my channel and create the following list:
Now my problem is I do not know how I can tell the buttons in the middle of each thumbnail to start the according video. I have the correct video ID for each element (provided in a textview on the right during troubleshooting...) but when I try to connect this information to the button onclick method it will just use the first textview content on the screen, so it is always just opening the first video => for every single button.
public void jumpin(View view) {
TextView textViewHelper = (TextView) findViewById(R.id.videoIdTester);
String textViewHelperString = textViewHelper.getText().toString();
Intent intent = YouTubeStandalonePlayer.createVideoIntent(this, API_KEY, textViewHelperString);
startActivity(intent);
}
My basic problem is that the buttons are not filled with the video ID information like the textviews for example. The buttons are just created and I call the onclick method which needs the video id then which is not reachable from my perspective as soon as the list is created.
I think this is by far too complicated at the moment but I have no plan how to solve that. I can provide more code if you need it but I think this problem is more about button and api/array behaviour in general.
Anwered by myself, using an onitemclick listener instead of the buttons ...

How to link a new textview created on java with its xml characteristics in android studio?

In Java, I have created a TextView whose text is the string written by the customer on an EditText in a previous activity. In the XML of the activity, I wrote the characteristics I want this TextView to have. My code creates a new TextView without those characteristics, anyone knows how to link them? I attach the java and XML codes. javacode xmlcodeThanks in advance!
You need to define the textview properly.
In oncreate method add
TextView text_message_1;
text_message_1=(TextView) findViewById(R.id.text_message_01);
Then set the text you get from other activity.
Since you are creating a TextView dynamically, so there is no need define a TextView tag in XML. You can simply set properties of that TextView in Java and add it to any ViewGroup or Table or anything you want.
And you can also try using findViewById() method for that TextView.
If you still face any problem, let me know.
I hope it answers well.

Why do i have to cast a Button?

This must be a really dumb question because I cant find an answer online.... I know that casting is changing one datatype to another. How is this button ever changing it's data dype? Button button = (Button)findViewById(R.Bla.Bla) Why cant we just write Button button = New Button() And then assign the xml to it another way? Please explain, I'm lost.
You can set a Button to a new button.
But findViewById returns a view. If you want to access any of its Buttonosity, you must cast, otherwise the reference isn't a button. There are times that may be okay, of course.
See In Android You can create the UI Elements in two ways:
1. create UI elements through layouts (.xml) files.
And to use them in java class map them to their corresponding class.
And to do so we have to call method findViewById(int id); which returns the view of that perticuler element with given id.and thus we have to type cast it to respective component.
And thus if you have created a element already in xml why will you create a different object again at java end. so just map the element created with xml file.
2. crate UI elements through java end.
To use this feature use have to create the elements in java with new keywords ex. Button button = new Button(); and then set the all properties on that object.
But But But,
According to android philosophy you should create UI in xml, and write your core business logic in java end. And with this concept you can write neet and clean application code.
But it is only recommended not compulsory at all. now its up to you....
and i think at starting you feel it different but after some time you will start loving it...
Thats the beauty of android.
Thanks. i hope, i answered your question throughly.
Also, remember that Button is a subclass of View. The findViewById() method returns a generic View (any View or subclass of View that you put in a layout file). The cast to Button is saying "It's okay - I know this is a Button, not just a regular View," which allows you to access properties and methods of the Button that aren't available in the View superclass.
final Button callButton = (Button) findViewById(R.id.callButton);
I believe that when finding an XML view using findViewbyId(), it returns the view in the UI, but the returned view must be cast in order to be used as a button within the Java code, and have access to the button methods.
There are ways to create a button in the Java code without specifying it in the XML, but this practice differentiates the UI from the logic.
Plus, declaring UI elements in the XML is better because it is makes the process changing entire layouts easy through usage of of setContentView().
You have two options to create View component in android including Button
1- Define it in a layout XML file and access it using (Button) findViewById(R.id.button)
2- Create it dynamically in the code e.g. Button button = new Button();
both has their own advantages and disadvantages, for example, defining the UI in layout xml makes your Activity concise and and give you more flexibility by separating the UI from the actual code
Dynamic UI creation is useful in many applications that needs to create Views on-the-fly

Android/java - need to find the ID of the current layout - how?

I'm creating an app for the Android OS, and I'm running into a bit of a stumbling block on one issue. Here's what I want to do:
I'm currently capturing the "Back" button event just fine, but I need it to behave slightly differently, depending on the current layout the user is viewing. I have four layouts that I'm using, and if the user is on layout 1, 2, or 3, I want "Back" to take them to layout 1; but if they are on layout 4, I want them to go back to layout 3 instead.
The problem is, I can't for the life of me figure out the code that will return the id of the CURRENT layout. I'm sure this is a pretty simple problem, so I'm hoping someone will have a quick solution.
Thanks for the pointers - for some reason I'm having trouble getting getCurrentFocus() to work, though...probably due to my own ineptitude in programming Java.
I've broken it down into the following:
View thisView = getCurrentFocus();
if (thisView != null){
int viewID = thisView.getId();
toastLong(Integer.toString(viewID));
} else {
toastLong("thisView is null.");
}
The problem now is that thisView is always null - it's not returning any values. I tried putting in the activity name that I'm using in place of myActivity (making it:
View thisView = myActivityName.getCurrentFocus();
but the IDE gives me the following error and won't compile:
Cannot make a static reference to the non-static method getCurrentFocus from the type Activity.
I'm obviously missing something, and my assumption is that it's a very basic something that I'm missing. Any pointers?
I had this problem too and found a very simple solution. Though this is an old question, I'll post it here for people who are searching for help for this problem.
Just create an integer as attribute in your class:
int layoutId;
Then override the setContentView method and save the ID from the parameter:
#Override
public void setContentView(int layoutResID) {
this.layoutId = layoutResID;
super.setContentView(layoutResID);
}
Very simple trick!
You can use ViewFlipper to hold your layouts and implement a simple state machine to control transitions.
another option might be creating a separate Activity for every one of your layouts - hard to tell without exact knowledge about what your app is doing.

Categories

Resources