android savedinstancestate null啥原因
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android savedinstancestate null啥原因相关的知识,希望对你有一定的参考价值。
参考技术A package cn.teachcourse.main;import cn.teachcourse.bean.WeatherBean;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.view.Menu;import android.view.MenuItem;import android.widget.TextView;public class MainActivity extends ActionBarActivity private TextView mTextView; private WeatherBean mBean; @Override protected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); private void initView() mTextView = (TextView) findViewById(R.id.textview1); @Override public boolean onCreateOptionsMenu(Menu menu) // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; @Override public boolean onOptionsItemSelected(MenuItem item) // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) return true; return super.onOptionsItemSelected(item); @Override protected void onSaveInstanceState(Bundle outState) super.onSaveInstanceState(outState); // 保存天气状态 outState.putSerializable("WeatherBean", new WeatherBean("2016-01-19", "广州")); @Override protected void onRestoreInstanceState(Bundle savedInstanceState) super.onRestoreInstanceState(savedInstanceState); // 获取保存的状态 mBean = (WeatherBean) savedInstanceState.getSerializable("WeatherBean"); if (savedInstanceState != null) mTextView.setText(mBean.getCity() + ";" + mBean.getDate());android如何获取控件宽度
如下列代码,经测试,Toast显示width2确实为控件TextView的宽度,但显示的width1仍然为初始值0,如何将width2的值赋给全局变量width1呢?求大神们指教!
public class MainActivity extends Activity
private TextView txt = null;
private int width1 = 0;
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.txt);
ViewTreeObserver vto = txt.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
public boolean onPreDraw()
int width2 = txt.getMeasuredWidth();
Toast.makeText(getApplication(), "width2:" + width2, Toast.LENGTH_SHORT).show();
width1 = width2;
return true;
);
Toast.makeText(getApplication(), "width1:" + width1, Toast.LENGTH_SHORT).show();
android的控件一般是继承的android.View这个类,所以可以直接用View#getWidth()方法获取控件宽度。另外这个方法是final方法,无法被子类覆盖,所以可以安心调用 参考技术B 是不是第二个Toast比第一个先输出? 如果是,问题就在于监听器的回调方法执行时间比第二个Toast晚。追问
我是想在程序一开始运行的时候就能获取width2的值并用于其它计算,请问该如何获取width2的值?
追答把你的逻辑代码写在onPreDraw回调方法里
本回答被提问者采纳以上是关于android savedinstancestate null啥原因的主要内容,如果未能解决你的问题,请参考以下文章