我正在尝试开发一个非常基本的Android应用程序。尽管我进行了正确的分配和声明,但我仍然收到错误。我尝试过不同的解决方案,例如使缓存无效并重新启动,但都没有成功。
拆分为声明和赋值已经完成,这实际上是编译器自动建议的。如果有任何其他替代解决方案,请告诉我。我也重建了我的项目,但效果并不好。
package com.example.javadesignapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu ;
import android.view.Menu ;
import android.view.MenuItem ;
import android.widget.RelativeLayout ;
import android.widget.Button ;
import android.graphics.Color ;
import android.widget.EditText ;
import android.content.res.Resources ;
import android.util.TypedValue ;
import android.widget.TextView ;
import android.view.View ;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout ahsansLayout = new RelativeLayout(this);
ahsansLayout.setBackgroundColor(Color.WHITE);
Button redButton = new Button(this);
redButton.setText(" !! Login now !! ");
redButton.setBackgroundColor(Color.WHITE);
redButton.setId(1);
Button ahsansbutton = (Button) findViewById(R.id.ahsansbutton);
//Username input
EditText username = new EditText(this);
username.setId(2) ;
RelativeLayout.LayoutParams buttonDetails = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
RelativeLayout.LayoutParams usernameDetails = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
// Give rules to position widgets
usernameDetails.addRule(RelativeLayout.ABOVE, redButton.getId()) ;
usernameDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
usernameDetails.setMargins(0,0,0,50);
buttonDetails.addRule(RelativeLayout.CENTER_HORIZONTAL) ;
buttonDetails.addRule(RelativeLayout.CENTER_VERTICAL) ;
Resources r = getResources() ;
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,200,
r.getDisplayMetrics()
);
username.setWidth(px);
ahsansLayout.addView(redButton,buttonDetails);
ahsansLayout.addView(username, usernameDetails);
setContentView(ahsansLayout);
}
}
最佳答案
将 setContentView(ahsansLayout);
替换为
setContentView(R.layout.ahsansLayout)
P/S : 如果你想为按钮分配一个 id,你需要创建一个自定义布局并将其填充到 MainActivity
中。不要忘记在 ahsansLayout.xml
中将 ahsansbutton
id 分配给您的 Button
。
关于java - Android Studio : Cannot find the symbol variable error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56949851/