在Android开发中,有时候需要使用动态TextView,增加灵活布置布局。动态TextView的好处就是代码量少,加载灵活。可以根据数据量大小加载。套一层ScrollView就是实现了滚动效果,把TextView数组所在的布局,比如Lineaout放在Scrollview中就可以了。请转发学习。
先看有段代码:
TextView[] tView;//这个放在类里定义
下面的代码放在一个函数中即可,只要在onCreate()中调用即可。
tView = new TextView[MAX_SEN_NUM];for (int i = 0; i < MAX_SEN_NUM; i++) {tView[i] = new TextView(this);tView[i].setTag(i);tView[i].setTextColor(stateData.textColor);tView[i].setBackgroundResource(R.drawable.word_color);//set the textView background colorInitTextView(tView[i]);// this is my function, you can init it with your own function,for example, you can set text Size...}LinearLayout layoutText=(LinearLayout)findViewById(R.id.word_lay_text);
// define the layout which can be used to add the textView array.
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);//define textView parameters tView[i].setLayoutParams(lparams); layoutText.addView(tView[i]);//load the textView into layoutText. //---------------------------------------//gesture process tView[i].setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if(event.getAction()==MotionEvent.ACTION_UP){// add touch event to the textView. // here can add you code. } } return mGestureDetector.onTouchEvent(event); } }); tView[i].setLongClickable(true);//set clickable //---------------------------------------
//相应布局文件中部分
<ScrollView android:id="@+id/scrollView" android:padding="5dp" android:layout_width="fill_parent" android:layout_marginBottom="180px" android:layout_height="0.0dip" android:layout_weight="16.0"> <LinearLayout android:orientation="vertical" android:id="@+id/layout_text"//注意:你的textView数组会自动加载在这个地方,如果要达到文本数组滚动的目的,外面套上一层 <ScrollView </ScrollView> android:layout_width="fill_parent" android:layout_height="fill_parent" /> </ScrollView>