Вопрос об Android-деятельности - PullRequest
0 голосов
/ 09 августа 2011

Где я могу объявить пользовательскую кнопку в моем основном классе активности?Может ли это быть в методе onStart или он будет работать только в методе onCreate?

Любая справка будет признательна?

Также для дальнейшей иллюстрации того, о чем я говорю: Вот мой класс активности.

public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if(D) Log.e(TAG, "+++ ON CREATE +++");
            setContentView(R.layout.main);



            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (mBluetoothAdapter == null) {
                Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
                finish();
                return;
                }        
        }
    @Override
        public void onStart() {
            super.onStart();
            if(D) Log.e(TAG, "++ ON START ++");
            // If BT is not on, request that it be enabled.
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
                } 
            else {
                startApp();
                }
            }
private void startApp(){

        View Patient_Button = findViewById(R.id.patientButton);
        Patient_Button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            //case R.id.patientButton:
                //Intent b = new Intent(getApplicationContext(), Detailed_ModeActivity.class);
                //startActivity(b);
                //break;
                }
            }
        );
        View Doctor_Button = findViewById(R.id.doctorButton);
        Doctor_Button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent a = new Intent(getApplicationContext(), Detailed_ModeActivity.class);
                startActivity(a);
                //break;
                }
            }
        );
        View About_Option = findViewById(R.id.aboutButton);
        About_Option.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent c = new Intent(getApplicationContext(), About.class);
                startActivity(c);
                //break;
                }
            }
        );

*

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@color/background"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="85dip" 
    android:orientation="horizontal">
    <LinearLayout 
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_gravity="center" android:orientation="vertical">
        <TextView 
            android:text="@string/mainTitle"
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:layout_gravity="center"
            android:layout_marginBottom="25dip"
            android:textSize="24.5sp"/>


        <!-- Patient Option -->
        <Button android:layout_width="fill_parent"
                android:layout_height="wrap_content" 
                android:layout_weight="1"
            android:text="@string/patientButton"
            android:id="@+id/patientButton">
        </Button>

        <!-- Doctor Option -->
        <Button android:layout_width="fill_parent"
            android:layout_height="wrap_content" 
            android:text="@string/doctorButton"
            android:layout_weight="1"
            android:id="@+id/doctorButton">
        </Button>

        <!-- Exit Mode -->
        <Button android:text="@string/exit" 

         android:layout_weight="1"
         android:id="@+id/exit" 
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content"></Button>

         <!-- About Mode -->
        <Button android:text="@string/aboutButton" 

         android:layout_weight="1"
         android:id="@+id/aboutButton" 
         android:layout_width="fill_parent" 
         android:layout_height="wrap_content"></Button>

    </LinearLayout>



</LinearLayout>

Ответы [ 2 ]

2 голосов
/ 09 августа 2011

Я считаю, что в Android принято объявлять кнопку в методе onCreate ().Как сказал @Mike D, вы также можете создать контроллер и создать его экземпляр в этом методе onCreate ().Хотя ваш вопрос не слишком ясен в отношении того, с какой проблемой вы сталкиваетесь, кажется, что вы просто ищете ответ между этими вариантами выбора - onStart () и onCreate ().

Например,

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button sampleButton = (Button) findViewById(R.id.sampleButton);
} 

В этом случае вы бы объявили кнопку в вашем файле main.xml, а идентификатор этой кнопки был бы sampleButton.

Кроме того, для дальнейшего использования очень важно, чтобы вы посмотрели на диаграмму на этой странице, чтобы увидеть жизненный цикл Android Activity и что и где разместить.Это не только ответит на этот вопрос, но и даст вам возможность самостоятельно изучить такую ​​концепцию.

0 голосов
/ 04 апреля 2013

Дайте RoboGuice попытку ускорить разработку, чтобы вам не пришлось слишком много беспокоиться об этих мелких деталях.

...