null对象引用上的setLayoutParams

时间:2016-02-22 19:19:35

标签: java android

我从Book“Android Studio Development edition 6,Essentials”第29章“学习了一个非常简单的动画示例”,并收到了logcat文件中显示的错误:

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.view.View.setLayoutParams(android.view.ViewGroup $ LayoutParams)'。

我的示例代码已成功编译,如下所示:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class TransitionDemoActivity extends AppCompatActivity {
    ViewGroup myLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transition_demo);

        myLayout=(ViewGroup)findViewById(R.id.myLayout);
        myLayout.setOnTouchListener(
                new RelativeLayout.OnTouchListener() {
                    public boolean onTouch(View v, MotionEvent m) {

                        handleTouch();
                          return true;
                    }
                });

    }
    public void handleTouch() {
        Toast.makeText(this,"Touching",Toast.LENGTH_LONG).show();//for listener test

       View view = findViewById(R.id.myButton1);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams
                (RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);

       params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,
                RelativeLayout.TRUE);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,
                RelativeLayout.TRUE);

       **view.setLayoutParams(params);**

        ViewGroup.LayoutParams lparams = view.getLayoutParams();

        lparams.width = 500;
        lparams.height = 350;
        view.setLayoutParams(lparams);
    }
}

我跟踪代码行以找到“view.setLayoutParams(params)上的错误代码位置,但我无法解决此问题。任何人都可以帮助我。 感谢

1 个答案:

答案 0 :(得分:0)

这意味着您的视图myButton1不存在,因此您的行View view = findViewById(R.id.myButton1);返回null。确保您的布局xml文件中确实有一个Button或其他视图,其ID为myButton1