【问题标题】:Dynamically adding textviews to layout and adjusting accordingly动态地将文本视图添加到布局并进行相应调整
【发布时间】:2012-04-26 20:08:44
【问题描述】:

我正在使用代码动态添加 TextView。现在我正在使用具有水平方向的 LinearLayout,我认为当 textviews 不适合该行时会添加一个新行。我错了。

问题是我不知道会有多少行,因为它取决于用户输入。因此 GridView 感觉不对,因为我无法指定列数。而且我不知道每个 TextView 的每个大小,如果 TextView 很长并且我想要每行 3 个 TextView,这可能会使它看起来很糟糕。

我确信有一个简单的解决方案,我只想知道最好的解决方案。当我向其中添加 TextView 时应该使用哪种布局,以便在达到屏幕宽度时在第一个下方创建一个新行?

谢谢!

【问题讨论】:

  • 请问您想通过使用多个文本视图而不是仅一个文本视图来实现什么?
  • 移除部件的可能性。每个文本视图都会有一个名称,用户可能会决定删除一些名称,同时保留一些其他名称。

标签: android android-layout textview xamarin.android


【解决方案1】:

看这个:

package us.simpleit;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SimpleGUI extends Activity {
    TextView tv;
    EditText et;
    LinearLayout ll;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //LinearLayout ll = new LinearLayout(this);
        ll = new LinearLayout(this);
        ll.setOrientation(android.widget.LinearLayout.VERTICAL);
        ll.setLayoutParams(new ViewGroup.LayoutParams(-1,-1));
        // ARGB: Opaque Red
        ll.setBackgroundColor(0x88ff0000);

        tv = new TextView(this);
        tv.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
        tv.setText("sample text goes here");
        // ARGB: Opaque Green
        tv.setBackgroundColor(0x5500ff00);
        ll.addView(tv);

        et = new EditText(this);
        et.setLayoutParams(new ViewGroup.LayoutParams(-1,-2));
        et.setText("edit me please");
        // ARGB: Solid Blue
        et.setBackgroundColor(0xff0000ff);
        ll.addView(et);

        Button btn = new Button(this);
        btn.setText("Go!");
        btn.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                tv.setText(et.getText().toString());
            }
        });

        ll.addView(btn);
        setContentView(ll);

        //setContentView(R.layout.main);
    }
}

在这里,我采用了一个 TextView 和一个 EditText。取而代之的是,您可以采用两个 TextView 或您想要的任意数量的视图。

享受。 :)

【讨论】:

  • 这只是用新的 textview 替换旧的 textview 。如何在旧文本视图旁边添加新文本视图?
【解决方案2】:

您可以做的就是使您的主要 LinearLayout 具有垂直方向和许多 LinearLayout 子级具有水平方向 当您想添加 TextView 时,请获取主布局的最后一个子项以了解此子项是否可以包含您新的 TextView。如果没有,则添加一个水平方向的新 LinearLayout

【讨论】:

  • 也是一个解决方案,不过我会选择机器人。
猜你喜欢
  • 1970-01-01
  • 2016-11-17
  • 1970-01-01
  • 2016-06-05
  • 1970-01-01
  • 1970-01-01
  • 2017-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多