Nishant Bhakta Nishant Bhakta - 4 years ago 140
Android Question

Without "TextView" in code, "LinearLayout.LinearParams" not increasing margin

In this code i just wanted to change the margin when i click on button. but the problem is that this code is working until this line

((TextView)findViewById(R.id.textView)).setText("Changed at runtime!");
is presented in code. if I remove this line the margin is not increasing when i am pressing the button.

This example is from a book "Android Application Development Cookbook", but there is no explanation for this and I didn't find any any thing much helpful about
LinearLayout.LinearParams
on android website. so any help is appreciated.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
((TextView)findViewById(R.id.textView)).setText("Changed at runtime!");
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)view.getLayoutParams();
params.leftMargin += 5;
}
});
}
}


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click"
android:id="@+id/button"/>
</LinearLayout>

Answer Source

You should set the LayoutParams again to the view like this,

 LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)view.getLayoutParams();
    params.leftMargin += 5;
    view.setLayoutParams(params);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download