简体   繁体   中英

creating text view programmatically(not in xml)

I want to create more then one TextView based on the condition of a for loop. how to do it programmatically?

Template :

app name: facebook

duration: 2 

app name: messaging

duration: 4

app name: temple run

duration: 2 

You can just create a TextView like this:

TextView myTextView = new TextView(this);
myTextView.setText("A TextView");

then you can add this view to your layout

Add an id field in layout in xml. Take reference of layout in your class. Create views and add it to layout.

LinearLayout linearLayout = (LinearLayout) findViewById (R.id.YourID);        
TextView textView = new TextView (this);     
textView. setText ("YourText");     
linearLayout. addView (textView);     

You can use this code to create text view programmaticaly:

TextView mTextView = new TextView(this);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mTextView.setLayoutParams(params);

rootView.addView(mTextView, 0);

What I understoond:

You have two array 1.appname 2. duration then try following code.

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.YourID);
    for (int i = 0; i < appname.length; i++) 
    {
        TextView textAppname = new TextView(this);
        TextView textDuration = new TextView(this);
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        textAppname.setLayoutParams(params);
        textDuration.setLayoutParams(params);

        textAppname.setText(appname[i]);
        textDuration.setText(duration[i]);
        linearLayout.addView(textAppname);
        linearLayout.addView(textDuration);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM