2012-07-31 64 views
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片段。我计算图像bottons与此代码工作:

@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); 
     } 
    }); 

}

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

谢谢。

回答

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包含在你的片段布局中。

+0

所以我只是直接添加: return(LinearLayout)inflater.inflate(R.layout.rdmon,container,false); } – 2012-07-31 17:30:20

+0

不是'onCreateView'方法的一部分......一个新的方法,但仍然在片段类中。 – Barak 2012-07-31 17:56:15

+0

我再拿到2个错误: 说明\t资源\t路径\t位置\t类型 方法findViewById(INT)是未定义的类型rdmon \t rdmon.java \ 说明\t资源\t路径\t位置\t类型 的方法Intent(rdmon,Class )未定义为新的类型View.OnClickListener(){} \t rdmon.java – 2012-07-31 18:04:39