简体   繁体   中英

How to add a fix Linear Layout programmatically in Android?

I need something like this:

LinearLayout (fix)
- Button
LinearLayout
- ScrollView
- TextView
- TextView
- TextView

I want the first LinearLayout to be fix (like a header). When someone tries to scroll down, i want the TextView to go behind the fix LinearLayout. I want that button always to be visible. With this code, everything is scrolling down. Here is my code:

    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);

You are adding your topLinearLayout into your linearLayout , which you are adding in your scrollView . this is not you want.

add scrollView and topLinearLayout in another LinearLayout

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM