今天我尝试使用片段活动创建一个项目。我有一个MainActivity范围FragmentActivity。 MainActvity有布局。
activity_main.xml中:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="2dip"
android:background="#000" />
<FrameLayout
android:id="@+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
布局有2个按钮,FrameLayout用于替换Fragment。在MainActivity onCreate中我插入一个片段。
MainAcivity.java
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.e("Button", "click--------------");
}
);
getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, fragment).addToBackStack(null).commit();
}
}
当我将片段插入R.id.frame_layout时,我尝试触摸button1但它没有响应。我在logcat中看不到它
请帮帮我!感谢
答案 0 :(得分:1)
使用:
你的XML:
<Button
android:id="@+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="yourmethod"
android:text="Login" />
您的代码:
public void yourmethod(View v){
//dosomthing
}
答案 1 :(得分:0)
将您的代码更改为
Button btn = (Button) getActivity().findViewById(
R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.e("Button", "click--------------");
}
});