cancello tutti i LinearLayout "figli"...
<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="horizontal" tools:context="com.example.lab10.MainActivity" > </LinearLayout>
Ora cerchiamo di procedere alla creazione di un nuovo layout.
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout ll=new LinearLayout(this); setContentView(ll); }Questo funziona.
Adesso devo trovare come dare gli attributi al layout programmaticamente.
Sarebbero questi:
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"E proviamo...
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout ll=new LinearLayout(this); ll.setOrientation(LinearLayout.HORIZONTAL); ll.setBackground(getResources().getDrawable(R.drawable.sky)); LayoutParams llParams=new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT); setContentView(ll,llParams); }E ottengo il risultato voluto:
Ho impostato quindi:
- l'orientamento;
- l'immagine di fondo;
- i LayoutParams, ossia width e height, ambedue impostati a MATCH_PARENT, come nel file 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="horizontal" android:background="@drawable/sky" tools:context="com.example.lab10.MainActivity" > </LinearLayout>
Adesso inserisco i due "layout figli", come ho fatto da xml in precedenza, questa volta programmaticamente:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout ll=new LinearLayout(this); ll.setOrientation(LinearLayout.HORIZONTAL); ll.setBackground(getResources().getDrawable(R.drawable.sky)); LayoutParams llParams=new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT); setContentView(ll,llParams); LinearLayout child=new LinearLayout(this); child.setOrientation(LinearLayout.HORIZONTAL); child.setBackground(getResources().getDrawable(R.drawable.w)); LayoutParams childParams=new LayoutParams(0,LayoutParams.MATCH_PARENT,1); ll.addView(child,childParams); LinearLayout child1=new LinearLayout(this); child1.setOrientation(LinearLayout.HORIZONTAL); child1.setBackground(getResources().getDrawable(R.drawable.w3)); LayoutParams childParams1=new LayoutParams(0,LayoutParams.MATCH_PARENT,1); ll.addView(child1,childParams1); }...ci sono impazzito un po' perché avevo commesso qualche errore banale, ma corretto il tutto funziona:
Nessun commento:
Posta un commento