简体   繁体   中英

How to set Textview's attributes programmatic way?

How can I set the value for the attributes for Textview in a programmatic way from XML code?

  <TextView
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_margin="3dp"
    android:layout_weight="0.5"
    android:background="@color/colorPrimary"
    android:gravity="center"
    android:text="text1" />

  <TextView
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_margin="3dp"
    android:layout_weight="0.5"
    android:background="@color/colorPrimary"
    android:gravity="center"
    android:text="text2" />
    TextView textView = new TextView(this);

    //set layout weight like this where 0.5 f is layout_weight
    LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 0.5f); 
        params.setMargins(10, 0, 5, 0);
        textView.setLayoutParams(params);
        textView.setBackgroundColor(Color.WHITE);
        textView.setGravity(Gravity.CENTER);
        textView.setText("Text");

Basic information for your knowledge: Each view that you take in XML layout is actually a class object that you are taking. Yes so those are classes like LinearLayout, TextView, Button, etc.

Now as said above those are classes so to access those programmatically, you can create an object of the particular view, access and apply available methods:

For example:

TextView textView = new TextView(this);
textView.setText("Hello World!");
textView.setId(randomId);
textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

if you want to change width, height, gravity,... u have to use LayoutParams object of your textView

https://developer.android.com/reference/android/view/ViewGroup.LayoutParams

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