簡體   English   中英

在Android中以編程方式定位視圖

[英]position views programmatically in Android

我有一個在垂直LinearLayout中創建3個textViews的方法:

public LinearLayout CreateLayout() {

    LinearLayout aLap = new LinearLayout(this);

    LinearLayout.LayoutParams TextParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);

    TextView txtName = new TextView(this);
    txtName.setText(result1);

    txtName.setLayoutParams(TextParams);
    txtName.setGravity(Gravity.CENTER);
    txtName.setPadding(20, 8, 20, 4);
    txtName.setTextSize(20);
    txtName.setTextColor(Color.parseColor("#000000"));

    TextView txtTime = new TextView(this);
    txtTime.setText(result2);
    txtTime.setLayoutParams(TextParams);
    txtTime.setGravity(Gravity.CENTER);
    txtTime.setTextSize(20);
    txtTime.setPadding(20, 4, 10, 4);
    txtTime.setTextColor(Color.parseColor("#000000"));

    android.view.ViewGroup.LayoutParams Params = new ViewGroup.LayoutParams(
            android.view.ViewGroup.LayoutParams.MATCH_PARENT, 150);

    TextView rep = new TextView(this);
    String Rep = sharedPrefs.getString("R_PREFS", "2");

    rep.setLayoutParams(TextParams);
    rep.setGravity(Gravity.CENTER);
    rep.setTextSize(20);
    rep.setPadding(20, 4, 10, 4);
    rep.setTextColor(Color.parseColor("#000000"));
    rep.setText("Test: " + Rep);

    aLap.setLayoutParams(Params);
    aLap.setBackgroundResource(R.drawable.bg);
    aLap.setOrientation(LinearLayout.VERTICAL);
    aLap.setPadding(3, 3, 3, 3);
    aLap.addView(txtName);
    aLap.addView(txtTime);
    aLap.addView(rep);

    return aLap;

}

我使用垂直布局,因為我希望textViews相互放置。 現在,我希望將ImageView放置在此textViews的右側並垂直居中。 那可能嗎?

您無法通過單個 LinearLayout獲得所需的輸出。 我建議您使用RelativeLayout 更靈活。 您可以在規則位置添加更多子視圖到RelativeLayout的所需位置。 查看這篇文章,了解如何在運行時使用Relative Layout時添加規則: 如何以編程方式在RelativeLayout中布局視圖?

<LinearLayout  orientation="horizontal">
  <LinearLayout orientation="vertical">
    <TextView view1/>
    <TextView view1/>
    <TextView view1/>
  </LinearLayout>
  <ImageView height=fill_parent scaleType="center"/>
</LinearLayout>

我想的是或多或少

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM