【问题标题】:How to add a fix Linear Layout programmatically in Android?如何在 Android 中以编程方式添加修复线性布局?
【发布时间】:2015-11-16 20:22:54
【问题描述】:

我需要这样的东西:

线性布局(修复)
- 按钮
线性布局
- 滚动视图
- 文本视图
- 文本视图
- 文本视图

我希望修复第一个 LinearLayout(如标题)。当有人试图向下滚动时,我希望 TextView 位于修复 LinearLayout 的后面。我希望该按钮始终可见。使用此代码,一切都在向下滚动。 这是我的代码:

    ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);

    final LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setOrientation(linearLayout.VERTICAL);
    scrollView.addView(linearLayout);

    final LinearLayout topLinearLayout = new LinearLayout(this);
    topLinearLayout.setOrientation(topLinearLayout.VERTICAL);
    linearLayout.addView(topLinearLayout);

    final Button button = new Button(this);
    button.setText(R.string.button);
    topLinearLayout.addView(button);

    TextView title = new TextView(this);
    title.setText(R.string.title);
    title.setGravity(Gravity.CENTER);
    linearLayout.addView(title);

【问题讨论】:

  • 您可以将其创建为布局 xml,然后对其进行膨胀。那会更容易处理。 LayoutInflater inflater = LayoutInflater.from(getContext()); View view = inflater.inflate(R.layout.yourLayout, yourContainer, attachToRootOrNot);
  • 我该怎么做呢?你能说得更具体点吗?
  • 只需通过布局编辑器或手动编写 xml 为您的视图创建一个布局,然后像我写的那样调用它。比通过例如Button button = view.findViewById(R.id.btn); 调用儿童视图编辑:您可以在 betone.co.uk 上查看我的应用程序视频。如果其中一个屏幕就像您想要实现的那样,我可以将那部分代码分享给您

标签: java android android-layout android-linearlayout android-scroll


【解决方案1】:

您正在将您的topLinearLayout 添加到您的linearLayout,您正在添加到您的scrollView。这不是你想要的。

在另一个LinearLayout中添加scrollViewtopLinearLayout

final LinearLayout mainlinearLayout = new LinearLayout(this);
mainlinearLayout.setOrientation(linearLayout.VERTICAL);

ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);

final LinearLayout topLinearLayout = new LinearLayout(this);
topLinearLayout.setOrientation(topLinearLayout.VERTICAL);

mainlinearLayout.addView(topLinearLayout); 
mainlinearLayout.addView(scrollView);

final LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(linearLayout.VERTICAL);
scrollView.addView(linearLayout);

final Button button = new Button(this);
button.setText(R.string.button);
topLinearLayout.addView(button);

TextView title = new TextView(this);
title.setText(R.string.title);
title.setGravity(Gravity.CENTER);
linearLayout.addView(title);

【讨论】:

  • 谢谢,但它不起作用。我有这个错误:Unable to start activity ComponentInfo{com.example.alexm.iqtest/com.example.alexm.iqtest.IqTest}: java.lang.NullPointerException
  • this解决的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-08
相关资源
最近更新 更多