Dynamic dimensional android

I want to change the width of one fragment in the main operation? perhaps because I cannot find "layoutparams" to change the default value:

public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); int widthFfragment=300; Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); widthTot = size.x; heightTot = size.y; findViewById(R.id.f1).getLayoutParams().width = widthTot-widthFfragment; 

}}

this is the fragment code:

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/f1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#330000" android:gravity="center_horizontal|center_vertical" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Fragment 1" android:textAppearance="?android:attr/textAppearanceLarge" /> 

Fragment1.java

 public class Fragment1 extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //---Inflate the layout for this fragment--- return inflater.inflate( R.layout.fragment1, container, false); } 

}

thanks

+4
source share
2 answers

You can do this by working with the LayoutParams View instance obtained from Fragment.getView (). My sample code is:

 private void resizeFragment(Fragment f, int newWidth, int newHeight) { if (f != null) { View view = f.getView(); RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(newWidth, newHeight); view.setLayoutParams(p); view.requestLayout(); } } 

And can be used as follows:

 resizeFragment(myFragment, 200, 500); resizeFragment(otherFragment, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); 
+9
source

On the right, the Fragment does not have LayoutParams, because it is a conceptual container, you either need to configure the layout parameters of the inflated view in the fragment, or in the container to which you attach the fragment.

 public class Fragment1 extends Fragment{ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup view = (ViewGroup) inflater.inflate( R.layout.fragment1, container, false); // TODO Adjust layout params of inflated view here return view; } 

The example assumes you are inflating a ViewGroup.

Hope this helps.

+4
source

Source: https://habr.com/ru/post/1413714/


All Articles