Dynamically Add A TextView - Android - android

How can I dynamically add a TextView to this? The commented out code doesn't work.
public class myTextSwitcher extends Activity {
private TextView myText;
public myTextSwitcher(String string){
//myText = new TextView(this);
//myText.setText("My Text");
}
}

You're creating a text view and setting its value but you're not specifying where and how it should be displayed. Your myText object needs to have a container of some sort which will make it visible.
What you're trying to do is dynamically layout a view. See here for a good starter article. From the article:
// This is where and how the view is used
TextView tv = new TextView(this);
tv.setText("Dynamic layouts ftw!");
ll.addView(tv);
// this part is where the containers get "wired" together
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);

First of all, you shouldn't be adding it in the constructor, non-default constructors are pretty much useless for an Activity. Finally, you are correctly creating a new TextView but you are not adding it anywhere. Get ahold of some layout in your content view (probably with findViewById), and call layout.addView(myText) with it.

Did you add the your text view to the activity using setContentView(myText);
make this
myText = new TextView(this);
myText.setText("foo");
setContentView(myText);

in oncreate() method
final TextView tv1 = new TextView(this);
tv1.setText("Hii Folks");
tv1.setTextSize(14);
tv1.setGravity(Gravity.CENTER_VERTICAL);
LinearLayout ll = (LinearLayout) findViewById(R.id.lin);
ll.addView(tv1);
Your activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:orientation="horizontal">
</LinearLayout>

Related

How to show TextView programmatically?

I have a RelativeLayout called current_layout which I place my views on. When I attempt to addView(TextView) , nothing is displayed. However when adding an ImageView, it works just fine. Why is my TextView not displaying?
public static void draw_shard(int x, int y, int amount_collected){//X and Y are GAMESURFACE values. Needs to increment by gamesurface y.
ImageView shard = create_iv(); // Creates a new instance of an ImageView (parameter is the context of MainActivity)
shard.setBackgroundDrawable(shard_icon);
shard.setX(x);
shard.setY(y+ImageLoader.get_score_bar_height());
TextView tv = new TextView(MainActivity.current_context);
tv.setX(shard.getX() + shard.getWidth());
tv.setY(shard.getY());
tv.setTypeface(Variables.joystix);
tv.setTextSize(shard.getHeight());
tv.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
tv.setText("+" + amount_collected);
tv.setTextColor(Color.WHITE);
current_layout.addView(shard);
current_layout.addView(tv);
}
I am adding the TextView on top of a black background also.
The problem was with shard.getWidth() and shard.getHeight() , which were returning 0.
An alternate and easy way to do that is:
Add the TextView in the layout file and set its visibility to gone, and when you need to show the TextView, just change the visibility of that TextView.
Sample code for XML file:
<TextView
android:id="#+id/textview"
android:layout_height="wrap_content"
android:layout-width="wrap_content"
android:visibility="gone">
<!-- Add other attributes too -->
And when you need that TextView, add this line of code:
findViewById("textview").setVisibility(View.VISIBLE);
findViewById("textview").setText("" + amount_collected);
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
// Create TextView
TextView product = new TextView(this);
product.setText(" Product");
ll.addView(product);
Please try it.
But why are you adding TextView using java code?
You can easily do it in XML.
<TextView
android:layout_width="wrap_content"
android:id="#+id/textView"
android:layout_height="wrap_content"
android:text="Hello World!"
android:background="#color/colorPrimary"
android:textColor="#color/colorPrimary" />
It will help you to understand
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
textView.setText("Your Text that you want to add");
linearLayout.addView(textView);
Thanks

method returning Layout or View

The app I am trying to make, has got a lot of similar LinearLayouts and textViews that need to be created programmatically and placed on the screen in a specific order.
So I decided to define a method which returns one element, and for the furthur uses,I will put the method in some loop to produce the others. but when I create a view or layout this way, nothing shows up or sometimes the app crashes, as if it's been sent null to addView(). It only works when I create the View/Layout in onCreate() and then I use it right there afterwards.So , any ideas that I can use the method to creat my Layout/View? Because they are too many and it's not possible to create them one by one in onCreate()
Here's the method:
public LinearLayout createLinearLayout(){
TextView tv_day = new TextView(this);
tv_day.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
tv_day.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
tv_day.setGravity(Gravity.END);
tv_day.setText("27");
LinearLayout ll_horizontal = new LinearLayout(getBaseContext());
LinearLayout.LayoutParams ll_horizontal_params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
ll_horizontal.setLayoutParams(ll_horizontal_params);
ll_horizontal.setOrientation(LinearLayout.HORIZONTAL);
ll_horizontal.addView(tv_day);
return ll_horizontal;
}
and this is onCreate() which doesn't add any linear layouts with a textView in it :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_month_view);
LinearLayout ll= createLinearLayout();
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.activity_month_view);
mainLayout.addView(ll);
}
I think this should help
- add an empty linear layout in XML with some id.
- reference that layout in code
- add elements to that layout dynamically
Hey was just checking your code. Its working perfectly now just try this method.
public LinearLayout createLinearLayout(){
TextView tv_day = new TextView(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv_day.setLayoutParams(layoutParams);
tv_day.setGravity(Gravity.CENTER);
tv_day.setText("27");
LinearLayout ll_horizontal = new LinearLayout(getBaseContext());
LinearLayout.LayoutParams ll_horizontal_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
ll_horizontal.setLayoutParams(ll_horizontal_params);
ll_horizontal.setOrientation(LinearLayout.HORIZONTAL);
ll_horizontal.addView(tv_day);
return ll_horizontal;
}

Adding TextView to LinearLayout in Android

I have 2 TextViews and I want to add those to LinearLayout, but when I ran the project, only one TextView appreared.
Here's my code:
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("Thank you, Jesus!");
textView.setTextColor(Color.BLACK);
TextView textView2 = new TextView(this);
textView.setText("Dont give up on me!");
textView.setTextColor(Color.BLACK);
LinearLayout layout = new LinearLayout(this);
layout.setBackgroundColor(Color.WHITE);
layout.addView(textView);
layout.addView(textView2);
setContentView(layout);
}
}
After running, textView2 was the only view present in the LinearLayout.
Can someone explain to me what was going on?
Use textView2 for calling setText and setTextColor method for textView2 because currently you are using textView :
TextView textView2 = new TextView(this);
textView2.setText("Dont give up on me!");
textView2.setTextColor(Color.BLACK);
Suggestion also set height/width for all views by calling setLayoutParams method
Another Suggestion : Add Orientation to Linear layout by using: layout.setOrientation(LinearLayout.VERTICAL);

LinearLayout with 2 textviews added dynamically with alignment problem

I have lists of LinearLayouts with horizontal orientation each one containing two textviews added dynamically.
This LinearLayout is finally wrapped into master LinearLayout.
I want the second textview of each linear layout to be right aligned progrmatically. How can I do this dynamically.
Here's sample code:
LinearLayout placeHolderLinearLayout = (LinearLayout)findViewById(R.id.listhosts);
//Several such layouts with 2 text views will be added to placeholder
LinearLayout l = new LinearLayout(this);
l.setClickable(true);
TextView h = new TextView(this);
h.setText("left");
h.setSingleLine(true);
TextView t = new TextView(this);
t.setText("right");
t.setSingleLine(true);
l.addview(h);
l.addview(t);
placeHolderLinearLayout.addView(l);
There is android:layout_alignParentRight attribute. But how to set this dynamically in this case. Any clue?
The android:layout_alignParentRight can only be applied to a view if its parent is a RelativeLayout. Change your container to that, and the 2 sub-views can use any of the layout_alignParent* attributes.
If you can't do this programatically (which I can't see how to do quickly), then you could always define your inner layout in xml (where you can easily get the layout correct) and inflate manually via:
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View l = vi.inflate(R.layout.inner_relative_layout, null);
TextView leftTextView = (TextView) l.findViewById(R.id.left_text);
leftTextView.setText("left");
// ... fill in right text too
placeHolderLinearLayout.addView(l);
Edit: added layout definition
Use a layout like this, and inflate it in the code as above:
<RelativeLayout android:id="#+id/inner_relative_layout" android:layout_width="fill_parent" android:layout_height="wrap_content">
<TextView android:id="#+id/left_text" android_alignParentLeft="true" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="#+id/right_text" android_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RelativeLayout>
You will be creating multiple of these layouts for each item you're adding to your list.
this one is woking and simple answer::
public class MainActivity extends Activity {
TextView text[];
TextView texto[];
CheckBox check[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.layout);
text = new TextView[5];
texto = new TextView[5];
check = new CheckBox[5];
for (int i = 0; i < 5; i++) {
text[i] = new TextView(this);
text[i].setText("First one is::" + i);
texto[i] = new TextView(this);
texto[i].setText("sennd one ibs::" + i);
check[i] = new CheckBox(this);
((ViewGroup) view).addView(check[i]);
((ViewGroup) view).addView(text[i]);
((ViewGroup) view).addView(texto[i]);
}
}
}
Please try below
LinearLayout placeHolderLinearLayout = (LinearLayout)findViewById(R.id.listhosts);
//Several such layouts with 2 text views will be added to placeholder
LinearLayout l = new LinearLayout(this);
l.setClickable(true);
TextView h = new TextView(this);
txt1.setGravity(Gravity.LEFT);
h.setText("left");
h.setSingleLine(true);
TextView t = new TextView(this);
txt1.setGravity(Gravity.RIGHT);
t.setText("right");
t.setSingleLine(true);
l.addview(h);
l.addview(t);
placeHolderLinearLayout.addView(l);

Android: Add a view to a specific Layout from code

I want to dynamically add some views to a LinearLayout that is already defined in XML.
I'm able to add views to the screen but they are not being placed 'inside' the right LinearLayout.
How can I get a reference to this specific Layout from code, similar to getting a View by using findViewById()?
As Marcarse pointed out you can do
ViewGroup layout = (ViewGroup) findViewById(R.id.your_layout_id);
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tv.setText("Added tv");
layout.addView(tv);
The LinearLayout class extends ViewGroup which itself extends the View class. This makes acquiring a reference to a layout as easy as getting a reference to another View.
This should work:
LinearLayout layout = (LinearLayout) findViewById(R.id.your_layout_id);
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tv.setText("Added tv");
layout.addView(tv);
Better Version:
To add another layout in activity/Fragment
LayoutInflater mInflater = LayoutInflater.from(getActivity());
View mProgressBarFooter = mInflater.inflate(R.layout.spinner, null, false);
textLoader = (TextView) mProgressBarFooter.findViewById(R.id.footer_label);
Happy Coding(-:

Categories

Resources