在活动中调用片段方法?

乔治·科姆吉耶夫(Georgi Koemdzhiev)

我正在尝试从活动中调用片段方法,但它会导致OutOfMemoryError。我正在关注本教程链接

Error reporting crash
                                                                   java.lang.OutOfMemoryError: Failed to allocate a 6289456 byte allocation with 4315368 free bytes and 4MB until OOM
                                                                       at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
                                                                       at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:125)
                                                                       at java.lang.StringBuffer.append(StringBuffer.java:278)
                                                                       at java.io.StringWriter.write(StringWriter.java:123)
                                                                       at com.android.internal.util.FastPrintWriter.flushLocked(FastPrintWriter.java:358)
                                                                       at com.android.internal.util.FastPrintWriter.appendLocked(FastPrintWriter.java:303)
                                                                       at com.android.internal.util.FastPrintWriter.write(FastPrintWriter.java:625)
                                                                       at com.android.internal.util.FastPrintWriter.append(FastPrintWriter.java:658)
                                                                       at java.io.PrintWriter.append(PrintWriter.java:691)
                                                                       at java.io.PrintWriter.append(PrintWriter.java:687)
                                                                       at java.io.Writer.append(Writer.java:198)
                                                                       at java.lang.Throwable.printStackTrace(Throwable.java:324)
                                                                       at java.lang.Throwable.printStackTrace(Throwable.java:300)
                                                                       at android.util.Log.getStackTraceString(Log.java:343)
                                                                       at com.android.internal.os.RuntimeInit.Clog_e(RuntimeInit.java:61)
                                                                       at com.android.internal.os.RuntimeInit.-wrap0(RuntimeInit.java)
                                                                       at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:86)
                                                                       at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
                                                                       at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)

在片段xml中呈现问题: 在此处输入图片说明

这是我的片段xml:[ current_forefast_fragment ]

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/bg_gradient">

<fragment
    android:id="@+id/current_fragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:name="koemdzhiev.com.stormy.Current_forecast_fragment"/>

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/iconImageView"
    android:src="@mipmap/clear_night"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    android:contentDescription="@string/weatherIconDesc"
    android:layout_above="@+id/locationLabel"
    android:layout_marginBottom="20dp"
    android:layout_centerHorizontal="true"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="requesting current location..."
    android:id="@+id/locationLabel"
    android:textColor="@android:color/white"
    android:textSize="22sp"
    android:layout_above="@+id/timeLabel"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="51dp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="--"
    android:id="@+id/temperatureLabel"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:textColor="@android:color/white"
    android:textSize="125sp"/>

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/degreeImageView"
    android:layout_alignTop="@+id/temperatureLabel"
    android:layout_toRightOf="@+id/temperatureLabel"
    android:layout_toEndOf="@+id/temperatureLabel"
    android:src="@mipmap/degree"
    android:layout_marginTop="27dp"
    android:layout_marginLeft="10dp"/>

</RelativeLayout>

这是我的片段代码:

public class Current_forecast_fragment extends Fragment {
private MainActivity mActivity;
@InjectView(R.id.timeLabel)
TextView mTimeLabel;
@InjectView(R.id.temperatureLabel)
TextView mTemperatureLabel;
@InjectView(R.id.humidityValue)
TextView mHumidityValue;
@InjectView(R.id.precipValue)
TextView mPrecipValue;
@InjectView(R.id.summaryLabel)
TextView mSummaryLabel;
@InjectView(R.id.locationLabel)
TextView mLocationLabel;
@InjectView(R.id.windSpeedValue)
TextView mWindSpeedValue;
@InjectView(R.id.iconImageView)
ImageView mIconImageView;
@InjectView(R.id.refreshImageView)
ImageView mRefreshImaveView;
@InjectView(R.id.progressBar)
ProgressBar mProgressBar;
@InjectView(R.id.degreeImageView)
ImageView mDegreeImageView;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mActivity = ((MainActivity) getActivity());
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.current_forefast_fragment, container, false);
    ButterKnife.inject(this, v);


    return v;
}


public void toggleRefresh() {
    if (mProgressBar.getVisibility() == View.INVISIBLE) {
        mProgressBar.setVisibility(View.VISIBLE);
        mRefreshImaveView.setVisibility(View.INVISIBLE);
    } else {
        mProgressBar.setVisibility(View.INVISIBLE);
        mRefreshImaveView.setVisibility(View.VISIBLE);
    }

    // updates the dysplay with the data in the CUrrentWeather locaal object

}

public void updateDisplay() {
    Current current = mActivity.mForecast.getCurrent();
    //setting the current weather details to the ui
    mTemperatureLabel.setText(current.getTemperature() + "");
    mTimeLabel.setText("At " + current.getFormattedTime() + " it will be");
    mHumidityValue.setText(current.getHumidity() + "%");
    mPrecipValue.setText(current.getPrecipChange() + "%");
    mSummaryLabel.setText(current.getSummery());
    mWindSpeedValue.setText(current.getWindSpeed() + "");
    mLocationLabel.setText(current.getTimeZone());
    mActivity.getLocationName();
    Drawable drawable = ContextCompat.getDrawable(mActivity, current.getIconId());
    mIconImageView.setImageDrawable(drawable);

}

}

这是主要活动中导致空指针异常的代码。当我尝试将片段转换为Current_forecast_fragment时,会发生这种情况:

public class MainActivity extends AppCompatActivity {
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Current","Hourly","Daily"};
int Numboftabs =3;
Current_forecast_fragment mCurrent_forecast_fragment;

public static final String TAG = MainActivity.class.getSimpleName();
public static final String LOCATION_KEY = "location_key";
public Forecast mForecast;
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
//default coordinates - Gotse Delchev, UK Lati:57.156866 ; Long:
private double latitude = 41.5667;
private double longitude = 23.7333;
private LocationManager locationManager;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //-----------MY CODE STARTS HERE-----------------

    mCurrent_forecast_fragment = (Current_forecast_fragment) getSupportFragmentManager().findFragmentById(R.id.current_fragment);
    //Log.d("MainActivity",mCurrent_forecast_fragment.getTag() + "Georgi");
    getLocation();

    // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
    adapter =  new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

    // Assigning ViewPager View and setting the adapter
    pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);

    // Assiging the Sliding Tab Layout View
    tabs = (SlidingTabLayout) findViewById(R.id.tabs);
    tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

    // Setting Custom Color for the Scroll bar indicator of the Tab View
    tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.tabsScrollColor);
        }
    });

    // Setting the ViewPager For the SlidingTabsLayout
    tabs.setViewPager(pager);




}

有什么建议?

飞行助手

您已将片段布局放置在片段内current_forefast_fragment.xml这对您Current_forecast_fragment造成了循环影响OutOfMemoryError因此,请从中删除此行current_forefast_fragment.xml

<fragment
    android:id="@+id/current_fragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:name="koemdzhiev.com.stormy.Current_forecast_fragment"/>

为了获得片段引用,您将需要修改您MainActivity想要保留的片段类和其他片段类Current_forecast_fragment我假设您有两个片段Tab1.javaCurrent_forecast_fragment.java在第一个中,我们需要Callback使用适当的方法定义接口:

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

/**
 * Created by hp1 on 21-01-2015.
 */
public class Tab1 extends Fragment {

    private Callback callback;

    public interface Callback{
        Current_forecast_fragment getCurrentForecastFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v =inflater.inflate(R.layout.tab_1,container,false);

        Button btn1 = (Button) v.findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callback.getCurrentForecastFragment();
            }
        });
        return v;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        callback = (Callback) activity;
    }
}

之后Callback在课堂上提到的工具MainActivity

public class MainActivity extends AppCompatActivity implements Tab1.Callback {
    ViewPager pager;
    ViewPagerAdapter adapter;
    SlidingTabLayout tabs;
    CharSequence Titles[] = {"Current", "Hourly", "Daily"};
    int Numboftabs = 3;
    Current_forecast_fragment mCurrent_forecast_fragment;

    public static final String TAG = MainActivity.class.getSimpleName();
    public static final String LOCATION_KEY = "location_key";
    public static final String DAILY_FORECAST = "DAILY_FORECAST";
    public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
    //default coordinates - Gotse Delchev, UK Lati:57.156866 ; Long:
    private double latitude = 41.5667;
    private double longitude = 23.7333;
    private LocationManager locationManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //-----------MY CODE STARTS HERE-----------------

        //mCurrent_forecast_fragment = (Current_forecast_fragment) getSupportFragmentManager().findFragmentById(R.id.current_fragment);
        //Log.d("MainActivity",mCurrent_forecast_fragment.getTag() + "Georgi");
        //getLocation();

        // Creating The ViewPagerAdapter and Passing Fragment Manager, Titles fot the Tabs and Number Of Tabs.
        adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, Numboftabs);

        // Assigning ViewPager View and setting the adapter
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        // Assiging the Sliding Tab Layout View
        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width

        // Setting Custom Color for the Scroll bar indicator of the Tab View
        tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
            @Override
            public int getIndicatorColor(int position) {
                return getResources().getColor(R.color.tabsScrollColor);
            }
        });

        // Setting the ViewPager For the SlidingTabsLayout
        tabs.setViewPager(pager);


    }

    public Current_forecast_fragment getCurrentForecastFragment() {
        // second argument is position of Current_forecast_fragment in ViewPagerAdapter
        mCurrent_forecast_fragment = (Current_forecast_fragment) adapter.instantiateItem(pager, 1);
        return mCurrent_forecast_fragment;
    }
}

现在,您可以通过调用接口方法来访问您的Current_forecast_fragment实例Tab1.javacallback.getCurrentForecastFragment()

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

从活动中调用片段方法

来自分类Dev

从活动中调用动态片段方法

来自分类Dev

如何从活动中调用片段内部的方法?

来自分类Dev

如何从片段中调用活动方法?

来自分类Dev

如何在活动中调用片段方法

来自分类Dev

活动中父片段中子片段中的调用方法

来自分类Dev

活动中父片段中子片段中的调用方法

来自分类Dev

从活动中调用片段

来自分类Dev

从片段调用父活动方法

来自分类Dev

从片段调用父活动方法

来自分类Dev

从基础活动中的抽屉片段中调用方法

来自分类Dev

如何从我的活动中调用片段中的方法?

来自分类Dev

如何从活动中调用片段

来自分类Dev

在活动中调用片段布局

来自分类Dev

在主活动中调用片段

来自分类Dev

从活动中调用选项卡式片段方法

来自分类Dev

从活动中调用片段方法,但视图为null

来自分类Dev

从活动中调用片段方法,但视图为null

来自分类Dev

从另一个活动中调用一个活动中的片段方法

来自分类Dev

在同一活动中添加新片段时,将调用当前片段的哪种方法

来自分类Dev

来自另一个片段/活动的片段中的调用方法

来自分类Dev

在同一活动中添加新片段时,将调用当前片段的哪种方法

来自分类Dev

从片段中的父活动中调用AsyncTask

来自分类Dev

从活动android标签调用片段方法

来自分类Dev

从活动中调用片段时应用崩溃

来自分类Dev

在活动/片段中调用多个暂停函数

来自分类Dev

如何在活动中调用片段类?

来自分类Dev

按钮从片段中调用主要活动

来自分类Dev

从活动中调用片段时应用崩溃