[英]LinearLayout with 2 textviews added dynamically with alignment problem
我有一個LinearLayouts列表,這些列表具有水平方向,每個列表包含兩個動態添加的textview。 最終,此LinearLayout被包裝到主LinearLayout中。
我希望每個線性布局的第二個textview在程序上正確對齊。 我該如何動態地做到這一點。
這是示例代碼:
LinearLayout placeHolderLinearLayout = (LinearLayout)findViewById(R.id.listhosts);
//Several such layouts with 2 text views will be added to placeholder
LinearLayout l = new LinearLayout(this);
l.setClickable(true);
TextView h = new TextView(this);
h.setText("left");
h.setSingleLine(true);
TextView t = new TextView(this);
t.setText("right");
t.setSingleLine(true);
l.addview(h);
l.addview(t);
placeHolderLinearLayout.addView(l);
有android:layout_alignParentRight屬性。 但是在這種情況下如何動態設置。 有什么線索嗎?
如果android:layout_alignParentRight
只有其視圖是RelativeLayout
則只能應用於該視圖。 將您的容器更改為該容器,這2個子視圖可以使用任何layout_alignParent*
屬性。
如果您不能以編程方式執行此操作(我看不到如何快速執行此操作),則始終可以在xml中定義內部布局(可以輕松地正確獲取布局),並通過以下方式手動進行填充:
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View l = vi.inflate(R.layout.inner_relative_layout, null);
TextView leftTextView = (TextView) l.findViewById(R.id.left_text);
leftTextView.setText("left");
// ... fill in right text too
placeHolderLinearLayout.addView(l);
編輯:添加布局定義
使用這樣的布局,並在上面的代碼中將其充氣:
<RelativeLayout android:id="@+id/inner_relative_layout" android:layout_width="fill_parent" android:layout_height="wrap_content">
<TextView android:id="@+id/left_text" android_alignParentLeft="true" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<TextView android:id="@+id/right_text" android_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RelativeLayout>
您將為要添加到列表中的每個項目創建多個布局。
這是一個簡單易懂的答案::
public class MainActivity extends Activity {
TextView text[];
TextView texto[];
CheckBox check[];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view = findViewById(R.id.layout);
text = new TextView[5];
texto = new TextView[5];
check = new CheckBox[5];
for (int i = 0; i < 5; i++) {
text[i] = new TextView(this);
text[i].setText("First one is::" + i);
texto[i] = new TextView(this);
texto[i].setText("sennd one ibs::" + i);
check[i] = new CheckBox(this);
((ViewGroup) view).addView(check[i]);
((ViewGroup) view).addView(text[i]);
((ViewGroup) view).addView(texto[i]);
}
}
}
請在下面嘗試
LinearLayout placeHolderLinearLayout = (LinearLayout)findViewById(R.id.listhosts);
//Several such layouts with 2 text views will be added to placeholder
LinearLayout l = new LinearLayout(this);
l.setClickable(true);
TextView h = new TextView(this);
txt1.setGravity(Gravity.LEFT);
h.setText("left");
h.setSingleLine(true);
TextView t = new TextView(this);
txt1.setGravity(Gravity.RIGHT);
t.setText("right");
t.setSingleLine(true);
l.addview(h);
l.addview(t);
placeHolderLinearLayout.addView(l);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.