Проблемы с кнопками в диалоге - PullRequest
0 голосов
/ 14 ноября 2011

У меня есть собственный диалог, который показывает несколько кнопок. Идея состоит в том, чтобы иметь прокручиваемый диалог, в котором можно выбрать число или букву от 0 до 9, от 0 до F или от 0 до Z ...

Итак, моя первая проблема заключается в том, как добавить эти кнопки с помощью кода, а не XML, так как каждый раз имеется переменное количество кнопок. Даже самый простой код вылетает из-за меня, поэтому я, вероятно, ничего не делаю правильно.

Также код, который у меня есть с несколькими кнопками xml, зависает, когда я нажимаю на кнопки, говоря, что он не может найти функцию onClick. Как вы можете видеть, у меня есть android: onClick = "onClickDialogbutton" в моей кнопке xml, и эта функция существует в моем java-коде, но все равно она падает.

Надеюсь, кто-то может взглянуть на код и помочь мне с программным добавлением кнопок и заставить работать onClick.

Вот мой код:

DialogTestActivity.java:

package com.test.dialog;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
public class DialogTestActivity extends Activity {
    Dialog dialog;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void onClickStartDialog( View view ) {
        dialog = new Dialog( this );
        dialog.requestWindowFeature( Window.FEATURE_NO_TITLE );
        dialog.setContentView( R.layout.dialog );
        dialog.setCancelable( true );
        dialog.show();
        // I here wish to add buttons through code and not xml.
        // This gives an error as it is now.
        Button button = new Button( this );
        ( ( LinearLayout )findViewById( R.id.Buttons ) ).addView( button );
    }
    public void onClickDialogButton( View view ) {
        dialog.dismiss();
    }
}

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:onClick="onClickStartDialog"
        android:text="Start Dialog" />
</LinearLayout>

Dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="54dip"
    android:layout_height="150dip"
    android:gravity="center" >
    <ScrollView
        android:layout_width="48dip"
        android:layout_height="144dip" >
        <LinearLayout
            android:id="@+id/Buttons"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >
            <Button
                android:id="@+id/ButtonId0"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:onClick="onClickDialogbutton"
                android:text="0"
                android:textSize="32dip" />
            <Button
                android:id="@+id/ButtonId1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:onClick="onClickDialogbutton"
                android:text="1"
                android:textSize="32dip" />
            <Button
                android:id="@+id/ButtonId2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:onClick="onClickDialogbutton"
                android:text="2"
                android:textSize="32dip" />
            </LinearLayout>
    </ScrollView>
</RelativeLayout>

1 Ответ

1 голос
/ 14 ноября 2011

Вам, вероятно, нужно позвонить findViewById на dialog. Простой вызов findViewById внутри вашего Activity попытается найти представление или дочернее представление, отображаемое в данный момент в вашей активности с указанным идентификатором. В этом случае это, вероятно, возвращает null, следовательно, сбой. Попробуйте еще раз с dialog.findViewById...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...