Android: popUp and button to dismiss doesnt work

送分小仙女□ 提交于 2019-12-13 05:28:11

问题


I have:

popUp.xml

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"

            ....
    <Button
        android:id="@+id/ok_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ok" 
        android:gravity="left"
        />
</LinearLayout>

main.java

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ListView listView = (ListView)findViewById(R.id.list);
    listView.setOnItemClickListener(new OnItemClickListener()
                {
                public void onItemClick(AdapterView<?> parent, View v,
                int position, long id)
                {
                    popUp();    

                }
       }); 

and I get force close here

public void popUp(){
            LayoutInflater inflater = (LayoutInflater) project.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.popup,null, false),300,400,true);
            ok_button = (Button) findViewById(R.id.ok_button);
            pw.showAtLocation(findViewById(R.id.list), Gravity.BOTTOM, 0,10);
            ok_button.setOnClickListener(new OnClickListener() { //here I get FC
                @Override
               public void onClick(View v) {

                 pw.dismiss();

              }
    });
        }


    } 

When I use button (in popUp();) from main.xml instead of popUp.xml everything is working. What is wrong with using the button from not main.xml


回答1:


I think that the problem is here:

ok_button = (Button) findViewById(R.id.ok_button);

it is looking for the button view inside the main layout instead of looking inside the popup layout. So probably ok_button is null.

Try to move out the inflate call from the constructor, like this:

View v = inflater.inflate(R.layout.popup,null, false);
final PopupWindow pw = new PopupWindow(v,300,400,true);

and then:

ok_button = (Button) v.findViewById(R.id.ok_button);


来源:https://stackoverflow.com/questions/8595427/android-popup-and-button-to-dismiss-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!