0
我學到書「6的Android Studio開發版綱要」第29" 章一個非常簡單的動畫樣本,並得到一個錯誤的logcat的文件,如:setLayoutParams對空對象引用
顯示java.lang.NullPointerException:試圖調用虛擬方法「無效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)」上的錯誤代碼位置,但我無法解決此問題。任何人都可以幫助我。 感謝
myButton1是在activity_transition_demo.xml中創建的,因此它被View view = findViewById(R.id.myButton1)引用; –
請將'activity_transition_demo.xml' – NoChinDeluxe