gpt4 book ai didi

java - 使用 LayoutInflator() 时出现空指针异常?

转载 作者:行者123 更新时间:2023-12-02 05:25:59 25 4
gpt4 key购买 nike

我正在使用 LayoutInflator 尝试让用户的文本显示在 TableLayout 中(它是 scrollView 的子级) )但到目前为止,它只是不断抛出空指针异常。所有 ID 都工作正常,我尝试清理该项目以查看是否有帮助,但无济于事,有人可以帮助我吗?

顺便说一下,它告诉我错误出现在两个地方,reminderListTextView.setText(text);inflate("test");

代码:

public class MainActivity extends ActionBarActivity {

private TableLayout reminderTableScrollView;

// TextView and Button added
EditText reminderEditText;

Button addReminderButton;



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

reminderTableScrollView = (TableLayout) findViewById(R.id.reminderTableScrollView);

reminderEditText = (EditText) findViewById(R.id.reminderEditText);

addReminderButton = (Button) findViewById(R.id.enterButton);
addReminderButton.setOnClickListener(reminderClickListener);
}

private OnClickListener reminderClickListener = new Button.OnClickListener() {

@Override
public void onClick(View v) {
if (reminderEditText.getText().toString() == null || reminderEditText.getText().toString() == "") {
Toast.makeText(getApplicationContext(), "Enter reminder", Toast.LENGTH_SHORT).show();
} else {
inflate("Test");
reminderEditText.setText("");
}
}
};

public void inflate(String text) {
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View reminder = inflator.inflate(R.layout.reminder_layout, null);

TextView reminderListTextView = (TextView) findViewById(R.id.reminderListTextView);
reminderListTextView.setText(text);

reminderTableScrollView.addView(reminder);
}

@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.menuAdd) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

最佳答案

实际上只有一个地方会出现异常:reminderListTextView.setText(text);,这两行是告诉您在 reminderListTextView 处收到错误的跟踪。 setText(text);inflate("test"); 被调用时。

尝试 reminder.findViewById(...);,您需要使用在其中扩充布局的 View 才能从中检索元素。

关于java - 使用 LayoutInflator() 时出现空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26003801/

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