我有以下代码问题是当我运行这个所有文本框都没有显示在屏幕上所以我想我需要在scrollview中添加所有文本框但我不知道如何。我也可以使用listview做到这一点但我必须通过在java代码中以编程方式添加scrollview来帮助任何人
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] textArray={"one","two","asdasasdf", "asdf" ,"dsdaa","fsvs","sd"};
int length=textArray.length;
LinearLayout layout = new LinearLayout(this);
setContentView(layout);
layout.setOrientation(LinearLayout.VERTICAL);
for(int i=0;i<length;i++)
{
TextView tv=new TextView(getApplicationContext());
tv.setText(textArray[i]);
tv.setTextSize(40);
tv.setTextColor(Color.BLACK);
tv.setPadding(20, 50, 20, 50);
tv.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL);
layout.addView(tv);
//tv.setMovementMethod(new ScrollingMovementMethod());
}
}
}
答案 0 :(得分:0)
在xml文件中的LinearLayout
下定义一个ScrollView
。将id
字段提供给LinearLayout
:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/<ID> >
</LinearLayout>
</ScrollView>
在您的班级中映射LinearLayout
:
LinearLayout layout = (LinearLayout) findViewById(R.id.<ID>);
在此处动态添加TextBox
:
TextView textBox = new TextView(context);
layout.addView(textBox);
答案 1 :(得分:0)
// try this way,hope this will help you...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] textArray={"one","two","asdasasdf", "asdf" ,"dsdaa","fsvs","sd"};
int length=textArray.length;
ScrollView scrollView = new ScrollView(this);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
for(int i=0;i<length;i++)
{
TextView tv=new TextView(getApplicationContext());
tv.setText(textArray[i]);
tv.setTextSize(40);
tv.setTextColor(Color.WHITE);
tv.setPadding(20, 50, 20, 50);
tv.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL);
layout.addView(tv);
//tv.setMovementMethod(new ScrollingMovementMethod());
}
scrollView.addView(layout,new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
setContentView(scrollView);
}