gpt4 book ai didi

java - OnClickListener 中的空指针异常

转载 作者:行者123 更新时间:2023-12-01 11:51:35 25 4
gpt4 key购买 nike

我对 Android 还很陌生。我有以下代码来在用户单击按钮时显示自定义对话框。这是代码:

MainActivity.java

public class MainActivity extends ActionBarActivity implements View.OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button customBtn = (Button)findViewById(R.id.custombtn);
customBtn.setOnClickListener(this);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v)
{
if(v == findViewById(R.id.custombtn))
{
String message = "This is a Custom Dialog.";

Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_layout);
dialog.setTitle("Custom Dialog");

TextView texter = (TextView)findViewById(R.id.text);
texter.setText(message);

ImageView image = (ImageView)findViewById(R.id.image);
//image.setImageResource(R.drawable.abc_spinner_mtrl_am_alpha);
dialog.show();
}
}
}

这是 custom_layout.xml 文件

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp" />

<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="@color/accent_material_light"/>
</LinearLayout>

每当我运行应用程序并单击自定义按钮时,应用程序都会崩溃并出现以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.adhish.onclicklisten.MainActivity.onClick(MainActivity.java:105)

我对 Android 还很陌生,不知道这意味着什么。我尝试过谷歌搜索,但对我来说不起作用。

请帮忙。

最佳答案

使用dialogcustom_layout布局访问 View :

    TextView texter = (TextView)dialog.findViewById(R.id.text);
texter.setText(message);
ImageView image = (ImageView)dialog.findViewById(R.id.image);

关于java - OnClickListener 中的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28779593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com