简体   繁体   中英

Android tutorial “Create the second activity” doesn't work with Android Studio, or

what am I doing wrong... ;-)

In the tutorial, I'm supposed to "Create the second activity", the screenshot of the tutorial shows how to do it in Eclipse, but I'm using AS. Anyway, I've added a new blank activity from within Android Studio and the generated DisplayMessageActivity.java file looks identical with the one in the tutorial.

Then the tutorial says to add the following code in the onCreate method:

if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
}

Q1: here the word 'container' in R.id.container is marked in red in AS; that is, can not resolve symbol 'container'. The tutorial doesn't say anything about it and I haven't got a clue how to declare it. What is it?

Further down in the DisplayMessageActivity I'm supposed to add:

public static class PlaceholderFragment extends Fragment {
    public PlaceholderFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_display_message, container, false);
        return rootView;
    }
}

Q2: What on earth is R.layout.fragment_display_message? All I've got is R.layout.activity_display_message.

Any advice is appreciated, thank you!

here the word 'container' in R.id.container is marked in red in AS; that is, can not resolve symbol 'container'.

That is because you did not have a container id layout in your activity_display_message.xml to be displayed when fragment is inflated/created.

sample:

in your activity_display_message

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container" <--- that is the id you must have --->
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true" >



</RelativeLayout>

.

 What on earth is R.layout.fragment_display_message??

it is the layout for your fragment so when it is inflated it will add to the top of your activity_main layout.

solution:

create a layout in your layout folder named fragment_display_message.xml

Replace

View rootView = inflater.inflate(R.layout.fragment_display_message,container, false);

with

View rootView = inflater.inflate(1,container, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM