1

我正在关注如何使用片段制作标签的教程。每个选项卡在 java 文件中都有这个:

公共类 rdfri 扩展片段 {

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if (container == null) {
        // We have different layouts, and in one of them this
        // fragment's containing frame doesn't exist.  The fragment
        // may still be created from its saved state, but there is
        // no reason to try to create its view hierarchy because it
        // won't be displayed.  Note this is not needed -- we could
        // just run the code below, where we would create and return
        // the view hierarchy; it would just never be used.
        return null;
    }
   return (LinearLayout)inflater.inflate(R.layout.rdfri, container, false);
}

}

我想尝试在片段中获取一个 imageButton。我认为图像按钮可以使用以下代码:

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

ImageButton Rainbowbook = (ImageButton) findViewById(R.id.imageButton1);

    rainbowbook.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

            Intent myIntent = Intent(rdmon.this, RainbowBookActivity.class);
            rdmon.this.startActivity(myIntent);
        }
    });

}

那么我将如何在片段代码中获取按钮代码呢?

谢谢。

4

1 回答 1

0

将按钮代码放在onActivityCreated片段类中的重写方法中。

@Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState);   
    ImageButton rainbowbook = (ImageButton) findViewById(R.id.imageButton1);

    rainbowbook.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View view) { 
        Intent myIntent = Intent(rdmon.this, RainbowBookActivity.class); 
        rdmon.this.startActivity(myIntent); 
       } 
    }); 
}

这当然假设您的 imagebutton 包含在您的片段布局中。

于 2012-07-31T16:28:33.343 回答