假設我想要讓TextView在RelativeLayout中水平置中,那麼其XML碼應如下
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="1" />
</RelativeLayout>
如果,其中的TextView是動態產生的,那麼,應使用如下的程式碼
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.view.Gravity;
:
:
View v = new View(getActivity());
v = inflater.inflate(R.layout.fragment_name, container, false);
RelativeLayout lay1 = (RelativeLayout) v.findViewById(R.id.layout_name);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
TextView t = new TextView(lay1.getContext());
t.setText("string");
t.setLayoutParams(params);
t.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
lay1.addView(t);
