【问题标题】:position views programmatically in Android在 Android 中以编程方式定位视图
【发布时间】:2012-10-31 13:16:39
【问题描述】:

我有一个在垂直 LinearLayout 中创建 3 个 textView 的方法:

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 的右侧并垂直居中。这可能吗?

【问题讨论】:

    标签: android textview android-linearlayout


    【解决方案1】:

    single LinearLayout 无法实现所需的输出。我建议你使用RelativeLayout。它更灵活。您可以通过向视图添加规则来在所需位置向RelativeLayout 添加更多子视图。 查看这篇文章,了解如何在运行时使用 Relative Layout 时添加规则:How to lay out Views in RelativeLayout programmatically?

    【讨论】:

      【解决方案2】:
      <LinearLayout  orientation="horizontal">
        <LinearLayout orientation="vertical">
          <TextView view1/>
          <TextView view1/>
          <TextView view1/>
        </LinearLayout>
        <ImageView height=fill_parent scaleType="center"/>
      </LinearLayout>
      

      我认为或多或少是你想要的

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-01
        • 1970-01-01
        • 2015-09-11
        • 2016-02-22
        • 1970-01-01
        • 1970-01-01
        • 2012-05-26
        相关资源
        最近更新 更多