动态地将按钮添加到对话框 [英] dynamically add buttons to dialog

查看:45
本文介绍了动态地将按钮添加到对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向对话框动态添加可变数量的Button.因此,由于按钮数量不固定,因此无法将其添加到布局文件中.

I want to dynamically add a variable amount of Buttons to a dialog. So because the amount of buttons isn't fix I can't add them to the layout file.

这是我尝试的方式:

 private void oeffne_dialog ( String[] prediction_array ) {
    //GestureAnyWhere gestureAnyWhere = null;
    // Activity activity = gestureAnyWhere.get_activity ();

    // TODO: bessere Lösung finden, als das Flag setzen zu müssen. Falscher Context
    Dialog dialog = new Dialog ( getApplicationContext () );
    dialog.getWindow ().setType ( WindowManager.LayoutParams.TYPE_SYSTEM_ALERT );
    Log.d ( "dialog", "dialog " + dialog + "|" + HintergrundService.this /*+ "|" + activity*/ );
    dialog.setContentView ( R.layout.multiple_predictions_layout );

    dialog.setTitle ( "Bitte die zu startende Anwendung auswählen" );

    // Button button_id = (Button)dialog.findViewById ( R.id.button_ID );

    Button button;

    for ( int i = 0 ; i < prediction_array.length ; i++ ) {

        /*
        button_id = new Button ( getApplicationContext () );
        button_id.setText ( prediction_array [i] );
        */

        Log.d ( "aufrufe", "aufrufe " + i + prediction_array[ i ] );
        button = new Button ( getApplicationContext () );
        button.setText ( prediction_array[ i ] );
        button.setId ( i );

    }


    dialog.show ();
}

但是使用此代码,对话框中将不会显示任何按钮.

But with this code no Button will appear in the dialog.

感谢您的帮助.

推荐答案

您只需要先为视图充气,然后从要向其中添加子对象的View获取ViewGroup.

You just need to inflate the view first and get the ViewGroup from that View that you want to add childs into.

Dialog dialog = new Dialog ( MainActivity.this );
dialog.getWindow ().setType ( WindowManager.LayoutParams.TYPE_SYSTEM_ALERT );
View view = getLayoutInflater().inflate(R.layout.empty_basket, null);

dialog.setTitle ( "Bitte die zu startende Anwendung auswählen" );

Button button;
LinearLayout ll = (LinearLayout) view.findViewById(R.id.ll);

for ( int i = 0 ; i < 10 ; i++ ) {
    Log.d ( "aufrufe", "aufrufe " + i);
    button = new Button ( MainActivity.this );
    button.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    button.setText (String.valueOf(i));
    button.setId (i);
    ll.addView(button);
}

dialog.setContentView (view);
dialog.show ();

别忘了添加权限TYPE_SYSTEM_ALERT

Don't forget to add the permission TYPE_SYSTEM_ALERT

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

这篇关于动态地将按钮添加到对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆