android - 以编程方式创建水平 ScrollView 不起作用

标签 android android-view android-scrollview

我试图在我的第一个 Activity 的 onCreate() 方法中创建一个 horizo​​ntalscrollview,因为我想制作大量的 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/

相关文章:

android - 在 API 23 中关闭对话框时出现 DeadObjectException

android - 以编程方式为 TableRow 数组设置边框

Android - ScrollView 内的 WebView 在底部留下空白

Android 两种方式 View - Horizo​​ntal Recyclerview inside Vertical Recyclerview

android - RecyclerView - computeHorizo​​ntalScrollRange 和 computeHorizo​​ntalScrollExtent 之间的区别?

java - 静态存储系统服务会导致内存泄漏吗?

Android + Google Fit 数据上传 : error 5002 - DataType's name does not match package name

android - 不调用getDrawable方法检查ImageView是否有图片

android - View中 "getScrollX and getScrollY"是什么意思

android - 操作栏在 fragment 内重叠滚动条