简体   繁体   中英

Change value in layout.xml conditionally in Android

I'm trying to get android:layout_marginEnd="-6dp" to change to 2dp conditionally in:

<FrameLayout
    android:id="@+id/wifi_combo"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
android:layout_marginEnd="-6dp"
    >

My condition is:

if (mSignalClusterStyle == STYLE_ALWAYS) {
            mMobileType.setVisibility(View.VISIBLE);
        } else if (mWifiVisible) {
            mMobileType.setVisibility(View.GONE);
        }

I would like to add a line to the if statement that overrides the -6dp with 2dp in the xml file.

I have explored setMarginEnd(), but there are very few resources on this, seeing as it is only a year old, and I keep getting a compile error with it.

What is the best way to change android:layout_marginEnd on a condition programmatically?

  FrameLayout layout = (FrameLayout) findViewById(R.id.wifi_combo);      
        FrameLayout.LayoutParams params = (LayoutParams) layout.getLayoutParams();
        params.setMarginEnd(2);

The correct way to set the endMargin is using setMarginEnd() only, added in API 17.

http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html#setMarginEnd(int)

BTW, what compile errors you are getting?

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