将文本get从listView.onItemClick更新为按钮

时间:2017-11-22 16:13:08

标签: android listview button

我确实设法从listView.onItemClick获取文本,而当我将文本设置为按钮时,我收到错误:

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.Button.setText(java.lang.CharSequence)'

更新以下完整代码: SubjectDialogActivity.java

package x.reminder;

import ...;

public class SubjectDialogActivity extends Activity {

    ListView listViewSubject;
    ArrayList<String> arrayListSubject;
    ArrayAdapter<String> arrayAdapterSubject;
    String subjectText;
    Button btnSub;

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

        //Sizing...

        //Create list...

        //Errorrrrrrrrrrrrrrr
        //Set On Click
        listViewSubject.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                btnSub = (Button)findViewById(R.id.btnSubject);
                String selectedText = listViewSubject.getItemAtPosition(position).toString(); 
                btnSub.setText(selectedText);

            }
        });
    }


    public void addSubjectClick(View v){
        ...
        intent.setClass(SubjectDialogActivity.this, AddSubjectActivity.class);
        ...
    }

    @Override
    protected void onActivityResult...
    }
}

xml - activity_add.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout ...">

<LinearLayout
  ...>

<Button
android:id="@+id/btnSubject"
...
android:text="Subject"
android:onClick="showDialogSubjectList"/>

</LinearLayout>

</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

我个人认为,当您将属性连接到xml时,应该在onCreate方法的开头处完成。

对于错误,您需要找到null对象,在这种情况下是您的按钮。尝试在onCreate中移动findviewbyid部分

答案 1 :(得分:0)

String selectedText = arrayListSubject.get(position);