Проблемы с созданием новой Android MainActivity

Я новичок в программировании для Android и пытаюсь создать новое основное действие для своего приложения (взято с обучающего сайта Android). Моя исходная основная деятельность называется «MainActivity». Новое действие, которое я хочу сделать своим основным действием, называется «Домашняя страница» и должно содержать кнопку, которая при нажатии создает «MainActivity». Я не уверен, что и где я должен включать в манифест информацию о новой странице «домашняя страница», homepage.xml и кнопке. Конкретный код приветствуется.

Домашняя страница:

package com.myphoneapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class HomePage extends Activity {

    private Button ScheduleBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homepage);

         ScheduleBtn = (Button) findViewById(R.id.home_btn);

        ScheduleBtn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub


                Intent myIntent = new Intent(HomePage.this, MainActivity.class);
                HomePage.this.startActivity(myIntent);


            }
        });
    }   


}

домашняя страница.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button 

    android:layout_width="wrap_content" 

    android:layout_height="wrap_content" 

    android:text="Welcome to ClearLight" 

    android:id="@+id/home_btn"

    />

</LinearLayout>

Основная деятельность:

package com.myphoneapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;


    public class MainActivity extends Activity {

    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the message from the intent
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        // Create the text view
        TextView textView = new TextView(this);
        textView.setTextSize(40);
        textView.setText(message);

        // Set the text view as the activity layout
        setContentView(textView);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        // Do something in response to button
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }

    }

Манифест:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myphoneapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.myphoneapp.MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.myphoneapp.DisplayMessageActivity"
            android:label="@string/title_activity_display_message"
            android:parentActivityName="com.example.myphoneapp.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.myphoneapp.MainActivity" />
        </activity>
        <activity
            android:name="com.myphoneapp.HomePage"
            android:label="@string/homepage" android name="MainActivity"
            android:parentActivityName="com.example.myphoneapp.MainActivity" >

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.myphoneapp.MainActivity" />
        </activity>
    </application>

</manifest>

person Nick    schedule 11.03.2013    source источник


Ответы (3)


Чтобы сделать HomePage своим первым действием, отредактируйте файл манифеста, чтобы в нем был фильтр намерений для action.MAIN. И вам не нужно ничего определять о макетах в файле манифеста. Только объявление Activity (которое у вас уже есть)

Таким образом, ваш новый файл манифеста будет выглядеть так:

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.myphoneapp.MainActivity"
            android:label="@string/title_activity_main" >

        </activity>
        <activity
            android:name="com.myphoneapp.DisplayMessageActivity"
            android:label="@string/title_activity_display_message"
            android:parentActivityName="com.example.myphoneapp.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.myphoneapp.MainActivity" />
        </activity>
        <activity
            android:name="com.myphoneapp.HomePage"
            android:label="@string/homepage" 
            android:parentActivityName="com.example.myphoneapp.MainActivity" >

            <!-- Move the intent filter to HomePage -->
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.myphoneapp.MainActivity" />
        </activity>
    </application>

</manifest>

А для кнопки запуска mainActivity вы уже сделали это в HomePage.java

ScheduleBtn = (Button) findViewById(R.id.home_btn);
ScheduleBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent myIntent = new Intent(HomePage.this, MainActivity.class);
        HomePage.this.startActivity(myIntent);
    }
});

Этот код (взятый из вашего HomePage.java открывает MainActivity из намерения

person Ahmed Aeon Axan    schedule 11.03.2013
comment
Привет, спасибо за вашу помощь, я использовал код, который вы мне предоставили, однако я все еще получаю ошибки для этой строки: android:label="@string/homepage" android:name="MainActivity" - person Nick; 11.03.2013
comment
Если бы вы могли опубликовать точные ошибки в своем вопросе, это было бы здорово - person Ahmed Aeon Axan; 11.03.2013
comment
Да. вы должны удалить оттуда этот дополнительный android:name=.MainActivity. Это была ошибка в коде. см. мой пересмотренный код. - person Ahmed Aeon Axan; 11.03.2013
comment
После ввода вашего измененного кода android:label="@string/homepage" теперь выдает ошибку: Не найден ресурс, соответствующий заданному имени (на метке со значением '@string/homepage'). - person Nick; 11.03.2013
comment
убедитесь, что в вашем файле strings.xml определена строка с именем homepage. - person Ahmed Aeon Axan; 11.03.2013

Измените файл манифеста следующим образом

  <?xml version="1.0" encoding="utf-8"?>
   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myphoneapp"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.myphoneapp.MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name=".HomePage"

    </activity>
</application>

person user1835052    schedule 11.03.2013

в файле манифеста ваша активность на домашней странице должна быть вашей основной активностью, поэтому ваш манифест должен выглядеть так:

 <activity
        android:name="com.myphoneapp.MainActivity"
        android:label="@string/homepage" android name="MainActivity"
        android:parentActivityName="com.example.myphoneapp.MainActivity" >

        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myphoneapp.MainActivity" />
    </activity>
<activity
        android:name="com.myphoneapp.HomePage"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
person Adil    schedule 11.03.2013