3

Почему-то не отображается кнопка при программном написании кода, хотя тот же TextView исправно отображается. В чем может быть проблема?

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

        TextView tv = new TextView(this);
        tv.setText("TextView");
        tv.setLayoutParams(params);
        layout.addView(tv);

        Button btn = new Button(this);
        btn.setText("Button");
        btn.setLayoutParams(params);

        layout.addView(btn);


        setContentView(layout, params);
    }
}

1 ответ 1

7

Проблема в том, что первая добавленная вами View (TextView) занимает всё пространство контейнера и для кнопки не осталось места. Вы это задали через LayoutParams.MATCH_PARENT.

Засим вам надо заменить MATCH_PARENT на WRAP_CONTENT

1
  • точно, спасибо!
    – I. Smirnov
    4 фев 2016 в 22:13

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.