在片段中使用上下文

Using context in fragments

我是 Android 的初学者。在这里,尝试将列表视图添加到我的项目中,其中片段用于导航抽屉。因此,我遇到了以下错误。下面是我的 activity 代码:

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class Menu1 extends Fragment {
    private ArrayList<Property> rentalProperties = new ArrayList<>();


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //returning our layout file
        //change R.layout.yourlayoutfilename for each of your fragments
        return inflater.inflate(R.layout.fragment_all, container, false);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //you can set the title for your toolbar here for different fragments different titles
        getActivity().setTitle("All");
        //create property elements

    }
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_all);

        //create our property elements
        rentalProperties.add(new Property(10, "Smith Street", "Sydney", "NSW", "A large 3 bedroom apartment right in the heart of Sydney! A rare find, with 3 bedrooms and a secured car park.", 450.00, "property_image_1", 3, 1, 1, false));
        rentalProperties.add(new Property(66, "King Street", "Sydney", "NSW", "A fully furnished studio apartment overlooking the harbour. Minutes from the CBD and next to transport, this is a perfect set-up for city living.", 320.00, "property_image_2", 1, 1, 1, false));
        rentalProperties.add(new Property(1, "Liverpool Road", "Liverpool", "NSW", "A standard 3 bedroom house in the suburbs. With room for several cars and right next to shops this is perfect for new families.", 360.00, "property_image_3", 3, 2, 2, true));
        rentalProperties.add(new Property(567, "Sunny Street", "Gold Coast", "QLD", "Come and see this amazing studio apartment in the heart of the gold coast, featuring stunning waterfront views.", 360.00, "property_image_4" , 1, 1, 1, false));

        //create our new array adapter
        ArrayAdapter<Property> adapter = new propertyArrayAdapter(this, 0, rentalProperties);

        //Find list view and bind it with the custom adapter
        ListView listView = (ListView) findViewById(R.id.customListView);
        listView.setAdapter(adapter);


        //add event listener so we can handle clicks
        AdapterView.OnItemClickListener adapterViewListener = new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Property property = rentalProperties.get(position);

                Intent intent = new Intent(Menu1.this, DetailActivity.class);
                intent.putExtra("streetNumber", property.getStreetNumber());
                intent.putExtra("streetName", property.getStreetName());
                intent.putExtra("suburb", property.getSuburb());
                intent.putExtra("state", property.getState());
                intent.putExtra("image", property.getImage());

                startActivityForResult(intent, 1000);
            }
        };
        //set the listener to the list view
        listView.setOnItemClickListener(adapterViewListener);


    }


}

显示了三个错误,它们是:

1) setContentView(R.layout.fragment_all);

Error:(43, 9) error: cannot find symbol method setContentView(int)

2) ListView listView = (ListView) findViewById(R.id.customListView);

   Error:(55, 40) error: cannot find symbol method findViewById(int)

3) ArrayAdapter 适配器 = new propertyArrayAdapter(this, 0, 出租物业);

Error:(52, 67) error: incompatible types: Menu1 cannot be converted to 
  Context

4) Intent intent = new Intent(Menu1.this, DetailActivity.class);

Error:(67, 33) error: no suitable constructor found for 
   Intent(Menu1,Class<DetailActivity>)
   constructor Intent.Intent(String,Uri) is not applicable
   (argument mismatch; Menu1 cannot be converted to String)
   constructor Intent.Intent(Context,Class<?>) is not applicable
   (argument mismatch; Menu1 cannot be converted to Context)

以上给出的问题已通过下面给出的答案进行修正,标记为答案。但是在这里我遇到了布局问题。布局不适合屏幕,每一边都有一些空白 space。在布局中尝试了不同的方法,但没有改变。布局代码如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="700dp"
    android:layout_height="400dp"
    android:orientation="vertical"
    android:paddingTop="-10dp"
    android:paddingBottom="10dp">

    <LinearLayout
        android:id="@+id/infoSection"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:weightSum="1">

        <TextView
            android:id="@+id/filename"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:text="Filename"
            android:textSize="15dp"
            android:layout_weight="2.35" />

        <ProgressBar
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/progressBar"
            android:layout_weight="2.35"
            android:layout_marginTop="-10dp"/>

    </LinearLayout>

    <RelativeLayout
        android:id="@+id/pricingSection"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/infoSection"
        android:orientation="vertical">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <TextView
                    android:text="Status"
                    android:layout_width="172dp"
                    android:layout_height="wrap_content"
                    android:id="@+id/status" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="15dp"
                    android:text="Size:"
                    android:layout_weight="1.07" />

                <TextView
                    android:text="sz"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/size"
                    android:layout_weight="1" />
            </LinearLayout>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </LinearLayout>

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="15dp"
                    android:layout_toRightOf="@id/size"
                    android:text="Progress:"
                    android:layout_weight="0.36" />

                <TextView
                    android:text="pg"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/progress"
                    android:layout_weight="1.65" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Speed:"
                    android:layout_marginLeft="25dp"
                    android:layout_toRightOf="@+id/progress"
                    android:layout_weight="0.87" />

                <TextView
                    android:text="sp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/speed"
                    android:layout_weight="1.86" />
            </LinearLayout>
        </LinearLayout>

    </RelativeLayout>

</RelativeLayout>

1) 片段中的 setContentView(R.layout.fragment_all); 替换为 return inflater.inflate(R.layout.fragment_all, container, false);

2) ListView listView = (ListView) findViewById(R.id.customListView); 将其替换为:ListView listView = (ListView) getActivity().findViewById(R.id.customListView);

3) ArrayAdapter adapter = new propertyArrayAdapter(this, 0, rentalProperties); 将其替换为 ArrayAdapter adapter = new propertyArrayAdapter(getActivity(), 0, rentalProperties); // getActivity() it's ur context

4) Intent intent = new Intent(Menu1.this, DetailActivity.class); 将其替换为 4) Intent intent = new Intent(getActivity(), DetailActivity.class);

希望有所帮助:)

1) setContentView(R.layout.fragment_all);

对于 fragment,您必须在 onCreateView() 中膨胀视图。不要将 setContentView(R.layout.fragment_all); 用于 fragment;

2) ListView listView = (ListView) findViewById(R.id.customListView);

您必须在片段中将视图作为父视图的子视图。在下面的代码中,rootView 是父级,所以我将 ListView 初始化为:

 ListView listView = (ListView) rootView.findViewById(R.id.customListView);

3) ArrayAdapter adapter = new propertyArrayAdapter(this, 0, rentalProperties);

您必须获取包含片段的 activity 的上下文:

ArrayAdapter adapter = new propertyArrayAdapter(getActivity(), 0, rentalProperties);

4) Intent intent = new Intent(Menu1.this, DetailActivity.class);

将其替换为:

 Intent intent = new Intent(getActivity(), DetailActivity.class);

最后将所有代码从onCreate()移动到onCreateView()如下:

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //returning our layout file
        //change R.layout.yourlayoutfilename for each of your fragments
        View rootView = inflater.inflate(R.layout.fragment_all, container, false);
        rentalProperties.add(new Property(10, "Smith Street", "Sydney", "NSW", "A large 3 bedroom apartment right in the heart of Sydney! A rare find, with 3 bedrooms and a secured car park.", 450.00, "property_image_1", 3, 1, 1, false));
        rentalProperties.add(new Property(66, "King Street", "Sydney", "NSW", "A fully furnished studio apartment overlooking the harbour. Minutes from the CBD and next to transport, this is a perfect set-up for city living.", 320.00, "property_image_2", 1, 1, 1, false));
        rentalProperties.add(new Property(1, "Liverpool Road", "Liverpool", "NSW", "A standard 3 bedroom house in the suburbs. With room for several cars and right next to shops this is perfect for new families.", 360.00, "property_image_3", 3, 2, 2, true));
        rentalProperties.add(new Property(567, "Sunny Street", "Gold Coast", "QLD", "Come and see this amazing studio apartment in the heart of the gold coast, featuring stunning waterfront views.", 360.00, "property_image_4" , 1, 1, 1, false));

        //create our new array adapter
        ArrayAdapter<Property> adapter = new propertyArrayAdapter(getActivity(), 0, rentalProperties);

        //Find list view and bind it with the custom adapter
        ListView listView = (ListView)rootView. findViewById(R.id.customListView);
        listView.setAdapter(adapter);


        //add event listener so we can handle clicks
        AdapterView.OnItemClickListener adapterViewListener = new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Property property = rentalProperties.get(position);

                Intent intent = new Intent(getActivity(), DetailActivity.class);
                intent.putExtra("streetNumber", property.getStreetNumber());
                intent.putExtra("streetName", property.getStreetName());
                intent.putExtra("suburb", property.getSuburb());
                intent.putExtra("state", property.getState());
                intent.putExtra("image", property.getImage());

                startActivityForResult(intent, 1000);
            }
        };
        //set the listener to the list view
        listView.setOnItemClickListener(adapterViewListener);
        return rootView;
    }

希望这对您有所帮助。