2

layout_oneのボタンにonClickリスナーを設定するにはどうすればよいですか?コードはどこに置きますか?onCreateViewに入れると、エラーが発生します。

public class LayoutOne extends Fragment {

    Button button;

    public static Fragment newInstance(Context context) {
        LayoutOne f = new LayoutOne();

        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ViewGroup root = (ViewGroup) inflater.inflate(R.layout.layout_one, null);

        return root;

    }
4

3 に答える 3

2

レイアウト属性android:clickable="true"を設定android:focusable="true"android:focusableInTouchMode="true"、xmlまたはsetClickable(true)コードから設定します。onClickListenerを次のように設定します。

((LinearLayout)findViewById(R.id.layout_one_id)).setClickable(true);   ((LinearLayout)findViewById(R.id.layout_one_id)).setOnClickListener(layoutOnClickListener);

    private OnClickListener layoutOnClickListener = new OnClickListener() {
            public void onClick(View v) {
               //Get Click here
            }
        };  
于 2012-07-27T06:04:29.047 に答える
1

このようなことをしても、エラーは発生しません

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    ViewGroup root = (ViewGroup) inflater
            .inflate(R.layout.layout_one, null);
    Button button_one=(Button)root.findViewById(R.id.button_one);// button_one is the id of the button in your xml file
    button_one.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    });

    return root;

}
于 2012-07-27T06:08:31.350 に答える
1

あなたのボタンが何と呼ばれているのかわかりませんが、onCreateView()あなたはそうします:

button = (Button)root.findViewById(R.id.layout_one_id);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        //stuff goes in here
    }
});

あなたの他のオプションは、xmlでそれを行い、それを使用するメソッドを作成することです. たとえば、Buttonsandroid:onClick="onButtonClicked"属性を設定すると、コードではメソッドは次のようになります。

public void onButtonClicked(View v) { /*Stuff*/ }
于 2012-07-27T06:09:38.570 に答える