我试图在我的第一个 Activity 的 onCreate() 方法中创建一个 horizontalscrollview,因为我想制作大量的 TextView 来滚动浏览。这是我目前所拥有的:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.ViewGroup.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
LinearLayout linscrollview;
HorizontalScrollView scrollview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrollview = (HorizontalScrollView) findViewById(R.id.scrollview_layout);
linscrollview = new LinearLayout(this);
for(int i=0; i<5; i++) {
TextView tv = new TextView(this);
tv.setWidth(LayoutParams.WRAP_CONTENT);
tv.setHeight(LayoutParams.WRAP_CONTENT);
tv.setText("" + i);
tv.setTextSize(20);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
params.setMargins(10, 0, 10, 0);
tv.setLayoutParams(params);
tv.setId(i);
linscrollview.addView(tv);
}
scrollview.addView(linscrollview);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
我没有收到任何错误,但是没有显示 TextView 。
最佳答案
您的问题可能与 setWidth 和 setHeight 方法有关。它们以像素为单位设置 TextView 宽度和高度的精确值,如文档中所述:
Makes the TextView exactly this many pixels wide. You could do the same thing by specifying this number in the LayoutParams.
http://developer.android.com/reference/android/widget/TextView.html#setWidth(int)
您要做的是为 TextView 设置 LayoutParams,因为您已经稍微深入了代码。因此,只需摆脱这两个方法调用,它就可以工作。
关于android - 以编程方式创建水平 ScrollView 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21105906/